context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.42. // namespace WebsitePanel.EnterpriseServer { using System.Diagnostics; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Xml.Serialization; using System.Data; using WebsitePanel.Providers; using WebsitePanel.Providers.OS; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name = "esOperatingSystemsSoap", Namespace = "http://smbsaas/websitepanel/enterpriseserver")] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ServiceProviderItem))] public partial class esOperatingSystems : Microsoft.Web.Services3.WebServicesClientProtocol { private System.Threading.SendOrPostCallback GetRawOdbcSourcesPagedOperationCompleted; private System.Threading.SendOrPostCallback GetInstalledOdbcDriversOperationCompleted; private System.Threading.SendOrPostCallback GetOdbcSourcesOperationCompleted; private System.Threading.SendOrPostCallback GetOdbcSourceOperationCompleted; private System.Threading.SendOrPostCallback AddOdbcSourceOperationCompleted; private System.Threading.SendOrPostCallback UpdateOdbcSourceOperationCompleted; private System.Threading.SendOrPostCallback DeleteOdbcSourceOperationCompleted; /// <remarks/> public esOperatingSystems() { this.Url = "http://localhost/WebsitePanelEnterpriseServer11/esOperatingSystems.asmx"; } /// <remarks/> public event GetRawOdbcSourcesPagedCompletedEventHandler GetRawOdbcSourcesPagedCompleted; /// <remarks/> public event GetInstalledOdbcDriversCompletedEventHandler GetInstalledOdbcDriversCompleted; /// <remarks/> public event GetOdbcSourcesCompletedEventHandler GetOdbcSourcesCompleted; /// <remarks/> public event GetOdbcSourceCompletedEventHandler GetOdbcSourceCompleted; /// <remarks/> public event AddOdbcSourceCompletedEventHandler AddOdbcSourceCompleted; /// <remarks/> public event UpdateOdbcSourceCompletedEventHandler UpdateOdbcSourceCompleted; /// <remarks/> public event DeleteOdbcSourceCompletedEventHandler DeleteOdbcSourceCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetRawOdbcSourcesPaged", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetRawOdbcSourcesPaged(int packageId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { object[] results = this.Invoke("GetRawOdbcSourcesPaged", new object[] { packageId, filterColumn, filterValue, sortColumn, startRow, maximumRows}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetRawOdbcSourcesPaged(int packageId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetRawOdbcSourcesPaged", new object[] { packageId, filterColumn, filterValue, sortColumn, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetRawOdbcSourcesPaged(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetRawOdbcSourcesPagedAsync(int packageId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { this.GetRawOdbcSourcesPagedAsync(packageId, filterColumn, filterValue, sortColumn, startRow, maximumRows, null); } /// <remarks/> public void GetRawOdbcSourcesPagedAsync(int packageId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, object userState) { if ((this.GetRawOdbcSourcesPagedOperationCompleted == null)) { this.GetRawOdbcSourcesPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRawOdbcSourcesPagedOperationCompleted); } this.InvokeAsync("GetRawOdbcSourcesPaged", new object[] { packageId, filterColumn, filterValue, sortColumn, startRow, maximumRows}, this.GetRawOdbcSourcesPagedOperationCompleted, userState); } private void OnGetRawOdbcSourcesPagedOperationCompleted(object arg) { if ((this.GetRawOdbcSourcesPagedCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetRawOdbcSourcesPagedCompleted(this, new GetRawOdbcSourcesPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetInstalledOdbcDrivers", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string[] GetInstalledOdbcDrivers(int packageId) { object[] results = this.Invoke("GetInstalledOdbcDrivers", new object[] { packageId}); return ((string[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetInstalledOdbcDrivers(int packageId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetInstalledOdbcDrivers", new object[] { packageId}, callback, asyncState); } /// <remarks/> public string[] EndGetInstalledOdbcDrivers(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string[])(results[0])); } /// <remarks/> public void GetInstalledOdbcDriversAsync(int packageId) { this.GetInstalledOdbcDriversAsync(packageId, null); } /// <remarks/> public void GetInstalledOdbcDriversAsync(int packageId, object userState) { if ((this.GetInstalledOdbcDriversOperationCompleted == null)) { this.GetInstalledOdbcDriversOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetInstalledOdbcDriversOperationCompleted); } this.InvokeAsync("GetInstalledOdbcDrivers", new object[] { packageId}, this.GetInstalledOdbcDriversOperationCompleted, userState); } private void OnGetInstalledOdbcDriversOperationCompleted(object arg) { if ((this.GetInstalledOdbcDriversCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetInstalledOdbcDriversCompleted(this, new GetInstalledOdbcDriversCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetOdbcSources", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SystemDSN[] GetOdbcSources(int packageId, bool recursive) { object[] results = this.Invoke("GetOdbcSources", new object[] { packageId, recursive}); return ((SystemDSN[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetOdbcSources(int packageId, bool recursive, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetOdbcSources", new object[] { packageId, recursive}, callback, asyncState); } /// <remarks/> public SystemDSN[] EndGetOdbcSources(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SystemDSN[])(results[0])); } /// <remarks/> public void GetOdbcSourcesAsync(int packageId, bool recursive) { this.GetOdbcSourcesAsync(packageId, recursive, null); } /// <remarks/> public void GetOdbcSourcesAsync(int packageId, bool recursive, object userState) { if ((this.GetOdbcSourcesOperationCompleted == null)) { this.GetOdbcSourcesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetOdbcSourcesOperationCompleted); } this.InvokeAsync("GetOdbcSources", new object[] { packageId, recursive}, this.GetOdbcSourcesOperationCompleted, userState); } private void OnGetOdbcSourcesOperationCompleted(object arg) { if ((this.GetOdbcSourcesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetOdbcSourcesCompleted(this, new GetOdbcSourcesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetOdbcSource", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SystemDSN GetOdbcSource(int itemId) { object[] results = this.Invoke("GetOdbcSource", new object[] { itemId}); return ((SystemDSN)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetOdbcSource(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetOdbcSource", new object[] { itemId}, callback, asyncState); } /// <remarks/> public SystemDSN EndGetOdbcSource(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SystemDSN)(results[0])); } /// <remarks/> public void GetOdbcSourceAsync(int itemId) { this.GetOdbcSourceAsync(itemId, null); } /// <remarks/> public void GetOdbcSourceAsync(int itemId, object userState) { if ((this.GetOdbcSourceOperationCompleted == null)) { this.GetOdbcSourceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetOdbcSourceOperationCompleted); } this.InvokeAsync("GetOdbcSource", new object[] { itemId}, this.GetOdbcSourceOperationCompleted, userState); } private void OnGetOdbcSourceOperationCompleted(object arg) { if ((this.GetOdbcSourceCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetOdbcSourceCompleted(this, new GetOdbcSourceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AddOdbcSource", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int AddOdbcSource(SystemDSN item) { object[] results = this.Invoke("AddOdbcSource", new object[] { item}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddOdbcSource(SystemDSN item, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddOdbcSource", new object[] { item}, callback, asyncState); } /// <remarks/> public int EndAddOdbcSource(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void AddOdbcSourceAsync(SystemDSN item) { this.AddOdbcSourceAsync(item, null); } /// <remarks/> public void AddOdbcSourceAsync(SystemDSN item, object userState) { if ((this.AddOdbcSourceOperationCompleted == null)) { this.AddOdbcSourceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddOdbcSourceOperationCompleted); } this.InvokeAsync("AddOdbcSource", new object[] { item}, this.AddOdbcSourceOperationCompleted, userState); } private void OnAddOdbcSourceOperationCompleted(object arg) { if ((this.AddOdbcSourceCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddOdbcSourceCompleted(this, new AddOdbcSourceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateOdbcSource", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateOdbcSource(SystemDSN item) { object[] results = this.Invoke("UpdateOdbcSource", new object[] { item}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateOdbcSource(SystemDSN item, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateOdbcSource", new object[] { item}, callback, asyncState); } /// <remarks/> public int EndUpdateOdbcSource(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateOdbcSourceAsync(SystemDSN item) { this.UpdateOdbcSourceAsync(item, null); } /// <remarks/> public void UpdateOdbcSourceAsync(SystemDSN item, object userState) { if ((this.UpdateOdbcSourceOperationCompleted == null)) { this.UpdateOdbcSourceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateOdbcSourceOperationCompleted); } this.InvokeAsync("UpdateOdbcSource", new object[] { item}, this.UpdateOdbcSourceOperationCompleted, userState); } private void OnUpdateOdbcSourceOperationCompleted(object arg) { if ((this.UpdateOdbcSourceCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateOdbcSourceCompleted(this, new UpdateOdbcSourceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteOdbcSource", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteOdbcSource(int itemId) { object[] results = this.Invoke("DeleteOdbcSource", new object[] { itemId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteOdbcSource(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteOdbcSource", new object[] { itemId}, callback, asyncState); } /// <remarks/> public int EndDeleteOdbcSource(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteOdbcSourceAsync(int itemId) { this.DeleteOdbcSourceAsync(itemId, null); } /// <remarks/> public void DeleteOdbcSourceAsync(int itemId, object userState) { if ((this.DeleteOdbcSourceOperationCompleted == null)) { this.DeleteOdbcSourceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteOdbcSourceOperationCompleted); } this.InvokeAsync("DeleteOdbcSource", new object[] { itemId}, this.DeleteOdbcSourceOperationCompleted, userState); } private void OnDeleteOdbcSourceOperationCompleted(object arg) { if ((this.DeleteOdbcSourceCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteOdbcSourceCompleted(this, new DeleteOdbcSourceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } //CO Changes /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/CheckFileServicesInstallation", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool CheckFileServicesInstallation(int serviceId) { object[] results = this.Invoke("CheckFileServicesInstallation", new object[] { serviceId}); return ((bool)(results[0])); } //END /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetRawOdbcSourcesPagedCompletedEventHandler(object sender, GetRawOdbcSourcesPagedCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetRawOdbcSourcesPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetRawOdbcSourcesPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetInstalledOdbcDriversCompletedEventHandler(object sender, GetInstalledOdbcDriversCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetInstalledOdbcDriversCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetInstalledOdbcDriversCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string[] Result { get { this.RaiseExceptionIfNecessary(); return ((string[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetOdbcSourcesCompletedEventHandler(object sender, GetOdbcSourcesCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetOdbcSourcesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetOdbcSourcesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SystemDSN[] Result { get { this.RaiseExceptionIfNecessary(); return ((SystemDSN[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetOdbcSourceCompletedEventHandler(object sender, GetOdbcSourceCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetOdbcSourceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetOdbcSourceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SystemDSN Result { get { this.RaiseExceptionIfNecessary(); return ((SystemDSN)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddOdbcSourceCompletedEventHandler(object sender, AddOdbcSourceCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddOdbcSourceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddOdbcSourceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateOdbcSourceCompletedEventHandler(object sender, UpdateOdbcSourceCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateOdbcSourceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateOdbcSourceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteOdbcSourceCompletedEventHandler(object sender, DeleteOdbcSourceCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteOdbcSourceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteOdbcSourceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Reflection; namespace NUnit.Gui { public class AboutBox : System.Windows.Forms.Form { private System.Windows.Forms.Button OkButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label versionLabel; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label copyright; private System.Windows.Forms.Label dotNetVersionLabel; private System.Windows.Forms.Label clrTypeLabel; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public AboutBox() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // Assembly executingAssembly = Assembly.GetExecutingAssembly(); string versionText = executingAssembly.GetName().Version.ToString(); object [] objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); if ( objectAttrs.Length > 0 ) versionText = ((AssemblyInformationalVersionAttribute)objectAttrs[0]).InformationalVersion; objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false); if ( objectAttrs.Length > 0 ) { string configText = ((AssemblyConfigurationAttribute)objectAttrs[0]).Configuration; if ( configText != "" ) versionText += string.Format(" ({0})",configText); } string copyrightText = "Copyright (C) 2002-2009 Charlie Poole.\r\nCopyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.\r\nCopyright (C) 2000-2002 Philip Craig.\r\nAll Rights Reserved."; objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if ( objectAttrs.Length > 0 ) copyrightText = ((AssemblyCopyrightAttribute)objectAttrs[0]).Copyright; versionLabel.Text = versionText; copyright.Text = copyrightText; dotNetVersionLabel.Text = string.Format( "{0} ( {1} )", Environment.Version, NUnit.Core.RuntimeFramework.CurrentFramework.DisplayName ); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(AboutBox)); this.OkButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.versionLabel = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.copyright = new System.Windows.Forms.Label(); this.clrTypeLabel = new System.Windows.Forms.Label(); this.dotNetVersionLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); // // OkButton // this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.OkButton.Location = new System.Drawing.Point(368, 304); this.OkButton.Name = "OkButton"; this.OkButton.Size = new System.Drawing.Size(96, 29); this.OkButton.TabIndex = 0; this.OkButton.Text = "OK"; this.OkButton.Click += new System.EventHandler(this.button1_Click); // // label1 // this.label1.Location = new System.Drawing.Point(31, 240); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(102, 15); this.label1.TabIndex = 1; this.label1.Text = "Version:"; // // versionLabel // this.versionLabel.Location = new System.Drawing.Point(164, 240); this.versionLabel.Name = "versionLabel"; this.versionLabel.Size = new System.Drawing.Size(156, 23); this.versionLabel.TabIndex = 2; this.versionLabel.Text = "label2"; // // label2 // this.label2.Location = new System.Drawing.Point(31, 144); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(102, 29); this.label2.TabIndex = 3; this.label2.Text = "Developers:"; // // label3 // this.label3.Location = new System.Drawing.Point(164, 144); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(287, 48); this.label3.TabIndex = 4; this.label3.Text = "James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Philip Craig, Ethan Smith," + " Doug de la Torre, Charlie Poole"; // // linkLabel1 // this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 21); this.linkLabel1.Location = new System.Drawing.Point(164, 112); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(266, 16); this.linkLabel1.TabIndex = 5; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "http://www.nunit.org "; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // label4 // this.label4.Location = new System.Drawing.Point(31, 112); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(102, 16); this.label4.TabIndex = 6; this.label4.Text = "Information:"; // // label5 // this.label5.Location = new System.Drawing.Point(31, 200); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(102, 29); this.label5.TabIndex = 7; this.label5.Text = "Thanks to:"; // // label6 // this.label6.Location = new System.Drawing.Point(164, 200); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(215, 29); this.label6.TabIndex = 8; this.label6.Text = "Kent Beck and Erich Gamma"; // // label7 // this.label7.Location = new System.Drawing.Point(31, 20); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(102, 28); this.label7.TabIndex = 9; this.label7.Text = "Copyright:"; // // copyright // this.copyright.Location = new System.Drawing.Point(164, 20); this.copyright.Name = "copyright"; this.copyright.Size = new System.Drawing.Size(297, 84); this.copyright.TabIndex = 10; this.copyright.Text = "label8"; // // clrTypeLabel // this.clrTypeLabel.Location = new System.Drawing.Point(31, 272); this.clrTypeLabel.Name = "clrTypeLabel"; this.clrTypeLabel.Size = new System.Drawing.Size(102, 15); this.clrTypeLabel.TabIndex = 11; this.clrTypeLabel.Text = "CLR Version:"; // // dotNetVersionLabel // this.dotNetVersionLabel.Location = new System.Drawing.Point(164, 272); this.dotNetVersionLabel.Name = "dotNetVersionLabel"; this.dotNetVersionLabel.Size = new System.Drawing.Size(284, 23); this.dotNetVersionLabel.TabIndex = 12; this.dotNetVersionLabel.Text = "label9"; // // AboutBox // this.AcceptButton = this.OkButton; this.CancelButton = this.OkButton; this.ClientSize = new System.Drawing.Size(490, 346); this.Controls.Add(this.dotNetVersionLabel); this.Controls.Add(this.clrTypeLabel); this.Controls.Add(this.copyright); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.versionLabel); this.Controls.Add(this.label1); this.Controls.Add(this.OkButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AboutBox"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "About NUnit"; this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { this.Close(); } private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://nunit.org"); linkLabel1.LinkVisited = true; } } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap26 : YsMap { public override int MapIndex => 26; protected override int RandomEncounterChance => 10; protected override int RandomEncounterExtraCount => 0; public YserMap26() { MapEvent01 = FnLAVA_01; MapEvent02 = FnTEMPEST_02; MapEvent03 = FnDUNGEON_03; MapEvent04 = FnHEAVENS_04; MapEvent05 = FnTXTTEMPS_05; MapEvent06 = FnTXTHEAVN_06; MapEvent07 = FnTXTCSTLG_07; MapEvent09 = FnTXTLOOKO_09; MapEvent0C = FnBDOORCGC_0C; MapEvent10 = FnRAPID_10; MapEvent11 = FnRIVER_11; MapEvent12 = FnTXTPHNX_12; MapEvent13 = FnDBENCPHO_13; MapEvent14 = FnDBENCA_14; MapEvent15 = FnDBENCB_15; MapEvent16 = FnDBENCC_16; MapEvent17 = FnDBENCD_17; MapEvent18 = FnBAZZENCA_18; MapEvent19 = FnBAZZENCB_19; MapEvent1A = FnBAZZENCC_1A; MapEvent1B = FnTOELVES_1B; MapEvent1C = FnPHOEGURD_1C; MapEvent1D = FnTXTBAZZA_1D; MapEvent1E = FnTXTBAZZB_1E; MapEvent1F = FnTXTBAZZC_1F; MapEvent20 = FnTXTBAZZD_20; MapEvent21 = FnPHOEREW_21; MapEvent24 = FnMYSTICS_24; MapEvent25 = FnFNTNBAZZ_25; MapEvent26 = FnLOOKENCA_26; MapEvent2A = FnTXTLOOKB_2A; MapEvent2B = FnFNTNLOOK_2B; MapEvent2C = FnCSTLENCA_2C; MapEvent2D = FnCSTLENCB_2D; MapEvent2E = FnCSTLENCC_2E; MapEvent2F = FnCSTLENCD_2F; MapEvent30 = FnCSTLENCE_30; MapEvent35 = FnTXTCSTLA_35; MapEvent36 = FnTXTCSTLB_36; MapEvent37 = FnFNTNHEAL_37; MapEvent38 = FnFNTNMANA_38; MapEvent3B = FnTXTCSTLC_3B; } // === Strings ================================================ private const string String03FC = "You stumble into the lava river and die."; private const string String0425 = "This gate leads to the entrance of Arnakkian's Arena."; private const string String045B = "Of all the winds, the TEMPEST is the most violent and dangerous."; private const string String049C = "Enter HEAVEN'S FURY if you must. It is here Voranti cursed the winds."; private const string String04E3 = "A doorway leads to the town of Castlegate, a village just outside Arnakkian's Castle."; private const string String0539 = "It is rumored that a band of dwarves once lived behind the doors of LookOut."; private const string String0586 = "With a massive effort, you manage to force the door open."; private const string String05C0 = "The door is stuck and will not open."; private const string String05E5 = "A plaque reads.."; private const string String05F6 = "'Thanks to the gracious generosity of the Mage Council, the survivors of the Arnakkian disaster hereby proclaim a new teleport to the top.'"; private const string String0682 = "Fighting the raging River of Eternity taps your life energy."; private const string String06BF = "You have died."; private const string String06CE = "The Phoenix is being reborn and may not be disturbed."; private const string String0704 = "Ahead, bound by the River of Eternity, is the shadow of the Phoenix Firebird. "; private const string String0753 = "The raging waters of the river look daunting."; private const string String0781 = "You hear the sound of rushing water behind the wall."; private const string String07B6 = "You also hear muffled roars."; private const string String07D3 = "Loose rocks tumble away, revealing a narrow passageway down."; private const string String0810 = "A Gnome Wizard greets you."; private const string String082B = "'Thank you for helping my master the Phoenix be reborn."; private const string String0863 = "The Phoenix may no longer be disturbed.'"; private const string String088C = "'I am the Guardian of the Phoenix. That you have passed my Dragon Guards is proof of your courage."; private const string String08F0 = "The way is now clear for you to meet the Phoenix."; private const string String0922 = "It is time for the Phoenix to die and so be reborn from its own ashes."; private const string String0969 = "Go! Let the glorious Phoenix die and be renewed!'"; private const string String099C = "A frightened Halfling Cleric hides in the shadows."; private const string String09CF = "'You must do something about these trolls. They're everywhere.'"; private const string String0A10 = "An exhausted Dwarf Knight hides in a large barrel."; private const string String0A43 = "'Hail! I welcome your help. These trolls have been giving me fits.'"; private const string String0A89 = "A Gnome Wizard suddenly appears."; private const string String0AAA = "'Past the CastleGates and past the Elves, you will find a place where the blue light of the sky meets the underworld below.'"; private const string String0B27 = "An Elf Ranger is delighted at your presense."; private const string String0B54 = "'I got clobbered by Andreas, the Earth Elemental! I wish you luck in your adventurers.'"; private const string String0BAD = "You feel a sudden increase in your Dexterity."; private const string String0BDB = "Nothing happens."; private const string String0BEC = "A small band of gypsies has formed camp in an old bazaar stall."; private const string String0C2C = "A young gypsy stares at you, gestures you closer, and whispers.."; private const string String0C6D = "'It is written on the Lava Walls that a Hero will someday reach the end of the rainbow and confront time.'"; private const string String0CD8 = "He pauses, then says, 'Go now, before more Trolls come! Go!' "; private const string String0D17 = "You sip the cool purple waters of the ElfFoot Fountain"; private const string String0D4E = "You gain the skill of Rune Reading!"; private const string String0D72 = "You gain the Channel skill!"; private const string String0D8E = "You gain the Staff skill!"; private const string String0DA8 = "You gain the Deep Trance skill!"; private const string String0DC8 = "Nothing happens."; private const string String0DD9 = "The purple waters of the ElfFoot Fountain slip through your fingers before you can wet your lips."; private const string String0E3B = "An inscription on the wall reads..."; private const string String0E5F = "'We, the Dwarves of NottiRock, seek brightly colored metals to forge magnificent treasures.'"; private const string String0EBC = "Ranger banners decorate the woodwork of Lookout Fountain."; private const string String0EF6 = "You gain the skill of Stamina!"; private const string String0F15 = "You gain the skill of Furtiveness!"; private const string String0F38 = "You gain the skill of Reading Tracks!"; private const string String0F5E = "You gain the skill of Archery!"; private const string String0F7D = "The waters are refreshing, but not enlightening!"; private const string String0FAE = "A message is etched on wall..."; private const string String0FCD = "'The runes seem to spell names. That is the way to Arnakkian.'"; private const string String100D = "A Human Barbarian belches, then looks up at you."; private const string String103E = "'Andreas built a great pit. Two.'"; private const string String1060 = "Holding up three fingers, he repeats..."; private const string String1088 = "'Two. Must need two to cross.'"; private const string String10A8 = "DayFrost Fountain restores your Health."; private const string String10D0 = "NightFrost Fountain renews your Mana."; private const string String10F6 = "A Phantasm appears..."; private const string String110C = "'Dare time? Yes? Ah, adventurers should not challenge En-Li-Kil!'"; private const string String1150 = "The Phantasm drains your life energies."; private const string String1178 = "You have died."; // === Functions ================================================ private void FnLAVA_01(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String03FC); // You stumble into the lava river and die. L0010: DamagePlayer(player, GetMaxHits(player)); L0021: return; // RETURN; } private void FnTEMPEST_02(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x35, 0x01, 0x4F, 0x01, type); L001E: return; // RETURN; } private void FnDUNGEON_03(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0425); // This gate leads to the entrance of Arnakkian's Arena. L0010: TeleportParty(player, 0x36, 0x02, 0x40, 0x02, type); L002B: return; // RETURN; } private void FnHEAVENS_04(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x35, 0x01, 0xF6, 0x02, type); L001E: return; // RETURN; } private void FnTXTTEMPS_05(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String045B); // Of all the winds, the TEMPEST is the most violent and dangerous. L0010: return; // RETURN; } private void FnTXTHEAVN_06(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String049C); // Enter HEAVEN'S FURY if you must. It is here Voranti cursed the winds. L0010: return; // RETURN; } private void FnTXTCSTLG_07(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String04E3); // A doorway leads to the town of Castlegate, a village just outside Arnakkian's Castle. L0010: return; // RETURN; } private void FnTXTLOOKO_09(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0539); // It is rumored that a band of dwarves once lived behind the doors of LookOut. L0010: return; // RETURN; } private void FnBDOORCGC_0C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(CheckStrength(player), 0x0014); L0012: if (JumpBelow) goto L0041; L0014: ShowMessage(player, doMsgs, String0586); // With a massive effort, you manage to force the door open. L0021: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01); L003F: goto L004E; L0041: ShowMessage(player, doMsgs, String05C0); // The door is stuck and will not open. L004E: return; // RETURN; } private void FnRAPID_10(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabyrinthICastleGateTeleport, 0x01); L0018: ShowMessage(player, doMsgs, String05E5); // A plaque reads.. L0025: ShowMessage(player, doMsgs, String05F6); // 'Thanks to the gracious generosity of the Mage Council, the survivors of the Arnakkian disaster hereby proclaim a new teleport to the top.' L0032: TeleportParty(player, 0x33, 0x01, GetCurrentTile(player), 0x02, type); L0051: return; // RETURN; } private void FnRIVER_11(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0682); // Fighting the raging River of Eternity taps your life energy. L0010: ax = GetMaxHits(player); L0017: bx = 0x0004; L001A: dx = ax % bx; ax = ax / bx; L001D: DamagePlayer(player, ax); L003F: return; // RETURN; } private void FnTXTPHNX_12(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = IsFlagOn(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVPhoenixReborn1); L0016: if (JumpEqual) goto L0028; L0018: ShowMessage(player, doMsgs, String06CE); // The Phoenix is being reborn and may not be disturbed. L0025: goto L00A7; L0028: ax = IsFlagOn(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVPhoenixReborn); L003B: if (JumpEqual) goto L008D; L003D: ShowMessage(player, doMsgs, String0704); // Ahead, bound by the River of Eternity, is the shadow of the Phoenix Firebird. L004A: ShowMessage(player, doMsgs, String0753); // The raging waters of the river look daunting. L0057: SetWallPassable(player, GetCurrentTile(player), 0x02, 0x01); L0071: SetWallItem(player, 0x01, GetCurrentTile(player), 0x02); L008B: goto L00A7; L008D: ShowMessage(player, doMsgs, String0781); // You hear the sound of rushing water behind the wall. L009A: ShowMessage(player, doMsgs, String07B6); // You also hear muffled roars. L00A7: return; // RETURN; } private void FnDBENCPHO_13(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x0E); L0015: AddEncounter(player, 0x02, 0x0E); L0027: AddEncounter(player, 0x03, 0x25); L0039: AddEncounter(player, 0x04, 0x25); L004B: AddEncounter(player, 0x06, 0x26); L005D: return; // RETURN; } private void FnDBENCA_14(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x19); L0015: AddEncounter(player, 0x02, 0x19); L0027: AddEncounter(player, 0x03, 0x19); L0039: AddEncounter(player, 0x04, 0x19); L004B: return; // RETURN; } private void FnDBENCB_15(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x19); L0015: AddEncounter(player, 0x02, 0x19); L0027: AddEncounter(player, 0x03, 0x1A); L0039: AddEncounter(player, 0x04, 0x1A); L004B: AddTreasure(player, 0x1388, 0x00, 0x00, 0x00, 0x00, 0x71); L006A: return; // RETURN; } private void FnDBENCC_16(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x19); L0015: AddEncounter(player, 0x02, 0x19); L0027: AddEncounter(player, 0x03, 0x18); L0039: AddEncounter(player, 0x04, 0x18); L004B: AddEncounter(player, 0x05, 0x1A); L005D: AddEncounter(player, 0x06, 0x1A); L006F: return; // RETURN; } private void FnDBENCD_17(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x24); L0015: AddEncounter(player, 0x02, 0x24); L0027: return; // RETURN; } private void FnBAZZENCA_18(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x1B); L0015: AddEncounter(player, 0x02, 0x1B); L0027: AddEncounter(player, 0x03, 0x1C); L0039: AddEncounter(player, 0x04, 0x1C); L004B: return; // RETURN; } private void FnBAZZENCB_19(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x1C); L0015: AddEncounter(player, 0x02, 0x1C); L0027: AddEncounter(player, 0x03, 0x1C); L0039: AddEncounter(player, 0x04, 0x1C); L004B: AddTreasure(player, 0x1388, 0x00, 0x00, 0x00, 0x00, 0x76); L006A: return; // RETURN; } private void FnBAZZENCC_1A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x0F); L0015: AddEncounter(player, 0x02, 0x10); L0027: AddEncounter(player, 0x03, 0x11); L0039: AddEncounter(player, 0x04, 0x1C); L004B: ax = HasItem(player, YsIndexes.ItemBlueMetal); L0059: if (JumpEqual) goto L007C; L005B: AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, 0x00, 0xD0); L007A: goto L009B; L007C: AddTreasure(player, 0x1388, 0x00, 0x00, 0x00, 0x00, YsIndexes.ItemBlueMetal); L009B: return; // RETURN; } private void FnTOELVES_1B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String07D3); // Loose rocks tumble away, revealing a narrow passageway down. L0010: TeleportParty(player, 0x37, 0x01, 0x1A, 0x03, type); L002B: return; // RETURN; } private void FnPHOEGURD_1C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x002D); L0010: ShowMessage(player, doMsgs, String0810); // A Gnome Wizard greets you. L001D: ax = IsFlagOn(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVPhoenixReborn1); L0030: if (JumpEqual) goto L004E; L0032: ShowMessage(player, doMsgs, String082B); // 'Thank you for helping my master the Phoenix be reborn. L003F: ShowMessage(player, doMsgs, String0863); // The Phoenix may no longer be disturbed.' L004C: goto L0097; L004E: ShowMessage(player, doMsgs, String088C); // 'I am the Guardian of the Phoenix. That you have passed my Dragon Guards is proof of your courage. L005B: ShowMessage(player, doMsgs, String08F0); // The way is now clear for you to meet the Phoenix. L0068: ShowMessage(player, doMsgs, String0922); // It is time for the Phoenix to die and so be reborn from its own ashes. L0075: ShowMessage(player, doMsgs, String0969); // Go! Let the glorious Phoenix die and be renewed!' L0082: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVPhoenixReborn, 0x01); L0097: return; // RETURN; } private void FnTXTBAZZA_1D(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x0029); L0010: ShowMessage(player, doMsgs, String099C); // A frightened Halfling Cleric hides in the shadows. L001D: ShowMessage(player, doMsgs, String09CF); // 'You must do something about these trolls. They're everywhere.' L002A: return; // RETURN; } private void FnTXTBAZZB_1E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x001C); L0010: ShowMessage(player, doMsgs, String0A10); // An exhausted Dwarf Knight hides in a large barrel. L001D: ShowMessage(player, doMsgs, String0A43); // 'Hail! I welcome your help. These trolls have been giving me fits.' L002A: return; // RETURN; } private void FnTXTBAZZC_1F(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x002D); L0010: ShowMessage(player, doMsgs, String0A89); // A Gnome Wizard suddenly appears. L001D: ShowMessage(player, doMsgs, String0AAA); // 'Past the CastleGates and past the Elves, you will find a place where the blue light of the sky meets the underworld below.' L002A: return; // RETURN; } private void FnTXTBAZZD_20(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x001F); L0010: ShowMessage(player, doMsgs, String0B27); // An Elf Ranger is delighted at your presense. L001D: ShowMessage(player, doMsgs, String0B54); // 'I got clobbered by Andreas, the Earth Elemental! I wish you luck in your adventurers.' L002A: return; // RETURN; } private void FnPHOEREW_21(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: RefreshCompareFlags(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagModAttr_Map26Dex)); L0016: if (JumpNotEqual) goto L0063; L0018: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagModAttr_Map26Dex, 0x01); L002D: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVPhoenixReborn1, 0x01); L0042: ModifyAttribute(player, 0x04, 0x00C8); L0054: ShowMessage(player, doMsgs, String0BAD); // You feel a sudden increase in your Dexterity. L0061: goto L0070; L0063: ShowMessage(player, doMsgs, String0BDB); // Nothing happens. L0070: return; // RETURN; } private void FnMYSTICS_24(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x0016); L0010: ShowMessage(player, doMsgs, String0BEC); // A small band of gypsies has formed camp in an old bazaar stall. L001D: ShowMessage(player, doMsgs, String0C2C); // A young gypsy stares at you, gestures you closer, and whispers.. L002A: ShowMessage(player, doMsgs, String0C6D); // 'It is written on the Lava Walls that a Hero will someday reach the end of the rainbow and confront time.' L0037: ShowMessage(player, doMsgs, String0CD8); // He pauses, then says, 'Go now, before more Trolls come! Go!' L0044: return; // RETURN; } private void FnFNTNBAZZ_25(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: RefreshCompareFlags(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVTeachSkill)); L0016: if (JumpEqual) goto L001B; L0018: goto L011A; L001B: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVTeachSkill, 0x01); L0030: ShowPortrait(player, 0x0042); L003D: ShowMessage(player, doMsgs, String0D17); // You sip the cool purple waters of the ElfFoot Fountain L004A: RefreshCompareFlags(GetSkillLevel(player, 0x14)); L0058: if (JumpNotEqual) goto L007B; L005A: SetSkillLevel(player, 0x14, 0x01); L006B: ShowMessage(player, doMsgs, String0D4E); // You gain the skill of Rune Reading! L0078: goto L0118; L007B: RefreshCompareFlags(GetSkillLevel(player, 0x16)); L0089: if (JumpNotEqual) goto L00AB; L008B: SetSkillLevel(player, 0x16, 0x01); L009C: ShowMessage(player, doMsgs, String0D72); // You gain the Channel skill! L00A9: goto L0118; L00AB: RefreshCompareFlags(GetSkillLevel(player, 0x15)); L00B9: if (JumpNotEqual) goto L00DB; L00BB: SetSkillLevel(player, 0x15, 0x01); L00CC: ShowMessage(player, doMsgs, String0D8E); // You gain the Staff skill! L00D9: goto L0118; L00DB: RefreshCompareFlags(GetSkillLevel(player, 0x17)); L00E9: if (JumpNotEqual) goto L010B; L00EB: SetSkillLevel(player, 0x17, 0x01); L00FC: ShowMessage(player, doMsgs, String0DA8); // You gain the Deep Trance skill! L0109: goto L0118; L010B: ShowMessage(player, doMsgs, String0DC8); // Nothing happens. L0118: goto L0127; L011A: ShowMessage(player, doMsgs, String0DD9); // The purple waters of the ElfFoot Fountain slip through your fingers before you can wet your lips. L0127: return; // RETURN; } private void FnLOOKENCA_26(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x1E); L0015: AddEncounter(player, 0x02, 0x1E); L0027: AddEncounter(player, 0x03, 0x25); L0039: AddEncounter(player, 0x04, 0x25); L004B: AddEncounter(player, 0x05, 0x1F); L005D: AddEncounter(player, 0x06, 0x1F); L006F: return; // RETURN; } private void FnTXTLOOKB_2A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0E3B); // An inscription on the wall reads... L0010: ShowRunes(player, doMsgs, String0E5F); // 'We, the Dwarves of NottiRock, seek brightly colored metals to forge magnificent treasures.' L001D: return; // RETURN; } private void FnFNTNLOOK_2B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x0042); L0010: ShowMessage(player, doMsgs, String0EBC); // Ranger banners decorate the woodwork of Lookout Fountain. L001D: RefreshCompareFlags(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVTeachSkill1)); L0030: if (JumpEqual) goto L0035; L0032: goto L0118; L0035: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagLabryinthIVTeachSkill1, 0x01); L004A: RefreshCompareFlags(GetSkillLevel(player, 0x09)); L0058: if (JumpNotEqual) goto L007B; L005A: SetSkillLevel(player, 0x09, 0x02); L006B: ShowMessage(player, doMsgs, String0EF6); // You gain the skill of Stamina! L0078: goto L0118; L007B: RefreshCompareFlags(GetSkillLevel(player, 0x0A)); L0089: if (JumpNotEqual) goto L00AB; L008B: SetSkillLevel(player, 0x0A, 0x02); L009C: ShowMessage(player, doMsgs, String0F15); // You gain the skill of Furtiveness! L00A9: goto L0118; L00AB: RefreshCompareFlags(GetSkillLevel(player, 0x0B)); L00B9: if (JumpNotEqual) goto L00DB; L00BB: SetSkillLevel(player, 0x0B, 0x02); L00CC: ShowMessage(player, doMsgs, String0F38); // You gain the skill of Reading Tracks! L00D9: goto L0118; L00DB: RefreshCompareFlags(GetSkillLevel(player, 0x08)); L00E9: if (JumpNotEqual) goto L010B; L00EB: SetSkillLevel(player, 0x08, 0x02); L00FC: ShowMessage(player, doMsgs, String0F5E); // You gain the skill of Archery! L0109: goto L0118; L010B: ShowMessage(player, doMsgs, String0F7D); // The waters are refreshing, but not enlightening! L0118: return; // RETURN; } private void FnCSTLENCA_2C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x17); L0015: AddEncounter(player, 0x02, 0x17); L0027: AddEncounter(player, 0x04, 0x20); L0039: AddEncounter(player, 0x05, 0x17); L004B: AddEncounter(player, 0x06, 0x17); L005D: return; // RETURN; } private void FnCSTLENCB_2D(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x1D); L0015: AddEncounter(player, 0x02, 0x1D); L0027: AddEncounter(player, 0x04, 0x1D); L0039: AddEncounter(player, 0x06, 0x1D); L004B: return; // RETURN; } private void FnCSTLENCC_2E(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x18); L0015: AddEncounter(player, 0x02, 0x18); L0027: AddEncounter(player, 0x03, 0x22); L0039: AddEncounter(player, 0x04, 0x22); L004B: return; // RETURN; } private void FnCSTLENCD_2F(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x1D); L0015: AddEncounter(player, 0x02, 0x1D); L0027: AddEncounter(player, 0x04, 0x1D); L0039: AddEncounter(player, 0x05, 0x18); L004B: AddEncounter(player, 0x06, 0x18); L005D: return; // RETURN; } private void FnCSTLENCE_30(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddEncounter(player, 0x01, 0x21); L0015: AddEncounter(player, 0x02, 0x21); L0027: AddEncounter(player, 0x04, 0x21); L0039: AddEncounter(player, 0x05, 0x0A); L004B: AddEncounter(player, 0x06, 0x21); L005D: return; // RETURN; } private void FnTXTCSTLA_35(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0FAE); // A message is etched on wall... L0010: ShowMessage(player, doMsgs, String0FCD); // 'The runes seem to spell names. That is the way to Arnakkian.' L001D: return; // RETURN; } private void FnTXTCSTLB_36(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x0016); L0010: ShowMessage(player, doMsgs, String100D); // A Human Barbarian belches, then looks up at you. L001D: ShowMessage(player, doMsgs, String103E); // 'Andreas built a great pit. Two.' L002A: ShowMessage(player, doMsgs, String1060); // Holding up three fingers, he repeats... L0037: ShowMessage(player, doMsgs, String1088); // 'Two. Must need two to cross.' L0044: return; // RETURN; } private void FnFNTNHEAL_37(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: HealPlayer(player, (ushort)GetMaxHits(player)); L0014: ShowPortrait(player, 0x0042); L0021: ShowMessage(player, doMsgs, String10A8); // DayFrost Fountain restores your Health. L002E: return; // RETURN; } private void FnFNTNMANA_38(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: AddMana(player, 0x2710); L0010: ShowPortrait(player, 0x0042); L001D: ShowMessage(player, doMsgs, String10D0); // NightFrost Fountain renews your Mana. L002A: return; // RETURN; } private void FnTXTCSTLC_3B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowPortrait(player, 0x0011); L0010: ShowMessage(player, doMsgs, String10F6); // A Phantasm appears... L001D: ShowMessage(player, doMsgs, String110C); // 'Dare time? Yes? Ah, adventurers should not challenge En-Li-Kil!' L002A: ShowMessage(player, doMsgs, String1150); // The Phantasm drains your life energies. L0037: ax = GetCurrentHits(player); L003E: bx = 0x0002; L0041: dx = ax % bx; ax = ax / bx; L0044: DamagePlayer(player, ax); L0066: return; // RETURN; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Statistics; using OpenSim.Region.ClientStack; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; namespace OpenSim { /// <summary> /// Common OpenSimulator simulator code /// </summary> public class OpenSimBase : RegionApplicationBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // These are the names of the plugin-points extended by this // class during system startup. private const string PLUGIN_ASSET_CACHE = "/OpenSim/AssetCache"; private const string PLUGIN_ASSET_SERVER_CLIENT = "/OpenSim/AssetClient"; protected string proxyUrl; protected int proxyOffset = 0; public string userStatsURI = String.Empty; protected bool m_autoCreateClientStack = true; /// <value> /// The file used to load and save prim backup xml if no filename has been specified /// </value> protected const string DEFAULT_PRIM_BACKUP_FILENAME = "prim-backup.xml"; public ConfigSettings ConfigurationSettings { get { return m_configSettings; } set { m_configSettings = value; } } protected ConfigSettings m_configSettings; protected ConfigurationLoader m_configLoader; public ConsoleCommand CreateAccount = null; protected List<IApplicationPlugin> m_plugins = new List<IApplicationPlugin>(); /// <value> /// The config information passed into the OpenSimulator region server. /// </value> public OpenSimConfigSource ConfigSource { get { return m_config; } set { m_config = value; } } protected OpenSimConfigSource m_config; public List<IClientNetworkServer> ClientServers { get { return m_clientServers; } } protected List<IClientNetworkServer> m_clientServers = new List<IClientNetworkServer>(); public uint HttpServerPort { get { return m_httpServerPort; } } public ModuleLoader ModuleLoader { get { return m_moduleLoader; } set { m_moduleLoader = value; } } protected ModuleLoader m_moduleLoader; protected IRegistryCore m_applicationRegistry = new RegistryCore(); public IRegistryCore ApplicationRegistry { get { return m_applicationRegistry; } } /// <summary> /// Constructor. /// </summary> /// <param name="configSource"></param> public OpenSimBase(IConfigSource configSource) : base() { LoadConfigSettings(configSource); } protected virtual void LoadConfigSettings(IConfigSource configSource) { m_configLoader = new ConfigurationLoader(); m_config = m_configLoader.LoadConfigSettings(configSource, out m_configSettings, out m_networkServersInfo); ReadExtraConfigSettings(); } protected virtual void ReadExtraConfigSettings() { IConfig networkConfig = m_config.Source.Configs["Network"]; if (networkConfig != null) { proxyUrl = networkConfig.GetString("proxy_url", ""); proxyOffset = Int32.Parse(networkConfig.GetString("proxy_offset", "0")); } } protected virtual void LoadPlugins() { using (PluginLoader<IApplicationPlugin> loader = new PluginLoader<IApplicationPlugin>(new ApplicationPluginInitialiser(this))) { loader.Load("/OpenSim/Startup"); m_plugins = loader.Plugins; } } protected override List<string> GetHelpTopics() { List<string> topics = base.GetHelpTopics(); Scene s = SceneManager.CurrentOrFirstScene; if (s != null && s.GetCommanders() != null) topics.AddRange(s.GetCommanders().Keys); return topics; } /// <summary> /// Performs startup specific to the region server, including initialization of the scene /// such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { IConfig startupConfig = m_config.Source.Configs["Startup"]; if (startupConfig != null) { string pidFile = startupConfig.GetString("PIDFile", String.Empty); if (pidFile != String.Empty) CreatePIDFile(pidFile); userStatsURI = startupConfig.GetString("Stats_URI", String.Empty); } base.StartupSpecific(); m_stats = StatsManager.StartCollectingSimExtraStats(); // Create a ModuleLoader instance m_moduleLoader = new ModuleLoader(m_config.Source); LoadPlugins(); foreach (IApplicationPlugin plugin in m_plugins) { plugin.PostInitialise(); } AddPluginCommands(); } protected virtual void AddPluginCommands() { // If console exists add plugin commands. if (m_console != null) { List<string> topics = GetHelpTopics(); foreach (string topic in topics) { m_console.Commands.AddCommand("plugin", false, "help " + topic, "help " + topic, "Get help on plugin command '" + topic + "'", HandleCommanderHelp); m_console.Commands.AddCommand("plugin", false, topic, topic, "Execute subcommand for plugin '" + topic + "'", null); ICommander commander = null; Scene s = SceneManager.CurrentOrFirstScene; if (s != null && s.GetCommanders() != null) { if (s.GetCommanders().ContainsKey(topic)) commander = s.GetCommanders()[topic]; } if (commander == null) continue; foreach (string command in commander.Commands.Keys) { m_console.Commands.AddCommand(topic, false, topic + " " + command, topic + " " + commander.Commands[command].ShortHelp(), String.Empty, HandleCommanderCommand); } } } } private void HandleCommanderCommand(string module, string[] cmd) { m_sceneManager.SendCommandToPluginModules(cmd); } private void HandleCommanderHelp(string module, string[] cmd) { // Only safe for the interactive console, since it won't // let us come here unless both scene and commander exist // ICommander moduleCommander = SceneManager.CurrentOrFirstScene.GetCommander(cmd[1]); if (moduleCommander != null) m_console.Output(moduleCommander.Help); } protected override void Initialize() { // Called from base.StartUp() m_httpServerPort = m_networkServersInfo.HttpListenerPort; m_sceneManager.OnRestartSim += handleRestartRegion; } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <param name="portadd_flag"></param> /// <returns></returns> public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, out IScene scene) { return CreateRegion(regionInfo, portadd_flag, false, out scene); } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <returns></returns> public IClientNetworkServer CreateRegion(RegionInfo regionInfo, out IScene scene) { return CreateRegion(regionInfo, false, true, out scene); } /// <summary> /// Execute the region creation process. This includes setting up scene infrastructure. /// </summary> /// <param name="regionInfo"></param> /// <param name="portadd_flag"></param> /// <param name="do_post_init"></param> /// <returns></returns> public IClientNetworkServer CreateRegion(RegionInfo regionInfo, bool portadd_flag, bool do_post_init, out IScene mscene) { int port = regionInfo.InternalEndPoint.Port; // set initial RegionID to originRegionID in RegionInfo. (it needs for loding prims) // Commented this out because otherwise regions can't register with // the grid as there is already another region with the same UUID // at those coordinates. This is required for the load balancer to work. // --Mike, 2009.02.25 //regionInfo.originRegionID = regionInfo.RegionID; // set initial ServerURI regionInfo.ServerURI = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.InternalEndPoint.Port; regionInfo.HttpPort = m_httpServerPort; regionInfo.osSecret = m_osSecret; if ((proxyUrl.Length > 0) && (portadd_flag)) { // set proxy url to RegionInfo regionInfo.proxyUrl = proxyUrl; regionInfo.ProxyOffset = proxyOffset; Util.XmlRpcCommand(proxyUrl, "AddPort", port, port + proxyOffset, regionInfo.ExternalHostName); } IClientNetworkServer clientServer; Scene scene = SetupScene(regionInfo, proxyOffset, m_config.Source, out clientServer); m_log.Info("[MODULES]: Loading Region's modules (old style)"); List<IRegionModule> modules = m_moduleLoader.PickupModules(scene, "."); // This needs to be ahead of the script engine load, so the // script module can pick up events exposed by a module m_moduleLoader.InitialiseSharedModules(scene); // Use this in the future, the line above will be deprecated soon m_log.Info("[MODULES]: Loading Region's modules (new style)"); IRegionModulesController controller; if (ApplicationRegistry.TryGet(out controller)) { controller.AddRegionToModules(scene); } else m_log.Error("[MODULES]: The new RegionModulesController is missing..."); scene.SetModuleInterfaces(); // Prims have to be loaded after module configuration since some modules may be invoked during the load scene.LoadPrimsFromStorage(regionInfo.originRegionID); // moved these here as the terrain texture has to be created after the modules are initialized // and has to happen before the region is registered with the grid. scene.CreateTerrainTexture(); // TODO : Try setting resource for region xstats here on scene MainServer.Instance.AddStreamHandler(new Region.Framework.Scenes.RegionStatsHandler(regionInfo)); try { scene.RegisterRegionWithGrid(); } catch (Exception e) { m_log.ErrorFormat("[STARTUP]: Registration of region with grid failed, aborting startup - {0}", e.StackTrace); // Carrying on now causes a lot of confusion down the // line - we need to get the user's attention Environment.Exit(1); } scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID); scene.EventManager.TriggerParcelPrimCountUpdate(); // We need to do this after we've initialized the // scripting engines. scene.CreateScriptInstances(); m_sceneManager.Add(scene); if (m_autoCreateClientStack) { m_clientServers.Add(clientServer); clientServer.Start(); } if (do_post_init) { foreach (IRegionModule module in modules) { module.PostInitialise(); } } scene.EventManager.OnShutdown += delegate() { ShutdownRegion(scene); }; mscene = scene; scene.StartTimer(); return clientServer; } private void ShutdownRegion(Scene scene) { m_log.DebugFormat("[SHUTDOWN]: Shutting down region {0}", scene.RegionInfo.RegionName); IRegionModulesController controller; if (ApplicationRegistry.TryGet<IRegionModulesController>(out controller)) { controller.RemoveRegionFromModules(scene); } } public void RemoveRegion(Scene scene, bool cleanup) { // only need to check this if we are not at the // root level if ((m_sceneManager.CurrentScene != null) && (m_sceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID)) { m_sceneManager.TrySetCurrentScene(".."); } scene.DeleteAllSceneObjects(); m_sceneManager.CloseScene(scene); ShutdownClientServer(scene.RegionInfo); if (!cleanup) return; if (!String.IsNullOrEmpty(scene.RegionInfo.RegionFile)) { if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".xml")) { File.Delete(scene.RegionInfo.RegionFile); m_log.InfoFormat("[OPENSIM]: deleting region file \"{0}\"", scene.RegionInfo.RegionFile); } if (scene.RegionInfo.RegionFile.ToLower().EndsWith(".ini")) { try { IniConfigSource source = new IniConfigSource(scene.RegionInfo.RegionFile); if (source.Configs[scene.RegionInfo.RegionName] != null) { source.Configs.Remove(scene.RegionInfo.RegionName); if (source.Configs.Count == 0) { File.Delete(scene.RegionInfo.RegionFile); } else { source.Save(scene.RegionInfo.RegionFile); } } } catch (Exception) { } } } } public void RemoveRegion(string name, bool cleanUp) { Scene target; if (m_sceneManager.TryGetScene(name, out target)) RemoveRegion(target, cleanUp); } /// <summary> /// Remove a region from the simulator without deleting it permanently. /// </summary> /// <param name="scene"></param> /// <returns></returns> public void CloseRegion(Scene scene) { // only need to check this if we are not at the // root level if ((m_sceneManager.CurrentScene != null) && (m_sceneManager.CurrentScene.RegionInfo.RegionID == scene.RegionInfo.RegionID)) { m_sceneManager.TrySetCurrentScene(".."); } m_sceneManager.CloseScene(scene); ShutdownClientServer(scene.RegionInfo); } /// <summary> /// Remove a region from the simulator without deleting it permanently. /// </summary> /// <param name="name"></param> /// <returns></returns> public void CloseRegion(string name) { Scene target; if (m_sceneManager.TryGetScene(name, out target)) CloseRegion(target); } /// <summary> /// Create a scene and its initial base structures. /// </summary> /// <param name="regionInfo"></param> /// <param name="clientServer"> </param> /// <returns></returns> protected Scene SetupScene(RegionInfo regionInfo, out IClientNetworkServer clientServer) { return SetupScene(regionInfo, 0, null, out clientServer); } /// <summary> /// Create a scene and its initial base structures. /// </summary> /// <param name="regionInfo"></param> /// <param name="proxyOffset"></param> /// <param name="configSource"></param> /// <param name="clientServer"> </param> /// <returns></returns> protected Scene SetupScene( RegionInfo regionInfo, int proxyOffset, IConfigSource configSource, out IClientNetworkServer clientServer) { AgentCircuitManager circuitManager = new AgentCircuitManager(); IPAddress listenIP = regionInfo.InternalEndPoint.Address; //if (!IPAddress.TryParse(regionInfo.InternalEndPoint, out listenIP)) // listenIP = IPAddress.Parse("0.0.0.0"); uint port = (uint) regionInfo.InternalEndPoint.Port; if (m_autoCreateClientStack) { clientServer = m_clientStackManager.CreateServer( listenIP, ref port, proxyOffset, regionInfo.m_allow_alternate_ports, configSource, circuitManager); } else { clientServer = null; } regionInfo.InternalEndPoint.Port = (int) port; Scene scene = CreateScene(regionInfo, m_storageManager, circuitManager); if (m_autoCreateClientStack) { clientServer.AddScene(scene); } scene.LoadWorldMap(); scene.PhysicsScene = GetPhysicsScene(scene.RegionInfo.RegionName); scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); scene.PhysicsScene.SetWaterLevel((float) regionInfo.RegionSettings.WaterHeight); return scene; } protected override StorageManager CreateStorageManager() { return CreateStorageManager(m_configSettings.StorageConnectionString, m_configSettings.EstateConnectionString); } protected StorageManager CreateStorageManager(string connectionstring, string estateconnectionstring) { return new StorageManager(m_configSettings.StorageDll, connectionstring, estateconnectionstring); } protected override ClientStackManager CreateClientStackManager() { return new ClientStackManager(m_configSettings.ClientstackDll); } protected override Scene CreateScene(RegionInfo regionInfo, StorageManager storageManager, AgentCircuitManager circuitManager) { SceneCommunicationService sceneGridService = new SceneCommunicationService(); return new Scene( regionInfo, circuitManager, sceneGridService, storageManager, m_moduleLoader, false, m_configSettings.PhysicalPrim, m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version); } protected void ShutdownClientServer(RegionInfo whichRegion) { // Close and remove the clientserver for a region bool foundClientServer = false; int clientServerElement = 0; Location location = new Location(whichRegion.RegionHandle); for (int i = 0; i < m_clientServers.Count; i++) { if (m_clientServers[i].HandlesRegion(location)) { clientServerElement = i; foundClientServer = true; break; } } if (foundClientServer) { m_clientServers[clientServerElement].NetworkStop(); m_clientServers.RemoveAt(clientServerElement); } } public void handleRestartRegion(RegionInfo whichRegion) { m_log.Info("[OPENSIM]: Got restart signal from SceneManager"); ShutdownClientServer(whichRegion); IScene scene; CreateRegion(whichRegion, true, out scene); } # region Setup methods protected override PhysicsScene GetPhysicsScene(string osSceneIdentifier) { return GetPhysicsScene( m_configSettings.PhysicsEngine, m_configSettings.MeshEngineName, m_config.Source, osSceneIdentifier); } /// <summary> /// Handler to supply the current status of this sim /// </summary> /// Currently this is always OK if the simulator is still listening for connections on its HTTP service public class SimStatusHandler : IStreamedRequestHandler { public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return Util.UTF8.GetBytes("OK"); } public string ContentType { get { return "text/plain"; } } public string HttpMethod { get { return "GET"; } } public string Path { get { return "/simstatus/"; } } } /// <summary> /// Handler to supply the current extended status of this sim /// Sends the statistical data in a json serialization /// </summary> public class XSimStatusHandler : IStreamedRequestHandler { OpenSimBase m_opensim; string osXStatsURI = String.Empty; public XSimStatusHandler(OpenSimBase sim) { m_opensim = sim; osXStatsURI = Util.SHA1Hash(sim.osSecret); } public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); } public string ContentType { get { return "text/plain"; } } public string HttpMethod { get { return "GET"; } } public string Path { // This is for the OpenSimulator instance and is the osSecret hashed get { return "/" + osXStatsURI + "/"; } } } /// <summary> /// Handler to supply the current extended status of this sim to a user configured URI /// Sends the statistical data in a json serialization /// If the request contains a key, "callback" the response will be wrappend in the /// associated value for jsonp used with ajax/javascript /// </summary> public class UXSimStatusHandler : IStreamedRequestHandler { OpenSimBase m_opensim; string osUXStatsURI = String.Empty; public UXSimStatusHandler(OpenSimBase sim) { m_opensim = sim; osUXStatsURI = sim.userStatsURI; } public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); } public string ContentType { get { return "text/plain"; } } public string HttpMethod { get { return "GET"; } } public string Path { // This is for the OpenSimulator instance and is the user provided URI get { return "/" + osUXStatsURI + "/"; } } } #endregion /// <summary> /// Performs any last-minute sanity checking and shuts down the region server /// </summary> public override void ShutdownSpecific() { if (proxyUrl.Length > 0) { Util.XmlRpcCommand(proxyUrl, "Stop"); } m_log.Info("[SHUTDOWN]: Closing all threads"); m_log.Info("[SHUTDOWN]: Killing listener thread"); m_log.Info("[SHUTDOWN]: Killing clients"); // TODO: implement this m_log.Info("[SHUTDOWN]: Closing console and terminating"); try { m_sceneManager.Close(); } catch (Exception e) { m_log.ErrorFormat("[SHUTDOWN]: Ignoring failure during shutdown - {0}", e); } } /// <summary> /// Get the start time and up time of Region server /// </summary> /// <param name="starttime">The first out parameter describing when the Region server started</param> /// <param name="uptime">The second out parameter describing how long the Region server has run</param> public void GetRunTime(out string starttime, out string uptime) { starttime = m_startuptime.ToString(); uptime = (DateTime.Now - m_startuptime).ToString(); } /// <summary> /// Get the number of the avatars in the Region server /// </summary> /// <param name="usernum">The first out parameter describing the number of all the avatars in the Region server</param> public void GetAvatarNumber(out int usernum) { usernum = m_sceneManager.GetCurrentSceneAvatars().Count; } /// <summary> /// Get the number of regions /// </summary> /// <param name="regionnum">The first out parameter describing the number of regions</param> public void GetRegionNumber(out int regionnum) { regionnum = m_sceneManager.Scenes.Count; } } public class OpenSimConfigSource { public IConfigSource Source; public void Save(string path) { if (Source is IniConfigSource) { IniConfigSource iniCon = (IniConfigSource) Source; iniCon.Save(path); } else if (Source is XmlConfigSource) { XmlConfigSource xmlCon = (XmlConfigSource) Source; xmlCon.Save(path); } } } }
// 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.Globalization; using System.Runtime.Serialization; namespace Cake.Common.Tools.GitVersion { [DataContract(Name = "GitVersion")] internal class GitVersionInternal { private GitVersion _gitVersion; internal GitVersion GitVersion => _gitVersion ?? (_gitVersion = new GitVersion()); [DataMember] public string Major { get => ToString(GitVersion.Major); set => GitVersion.Major = ToInt(value); } [DataMember] public string Minor { get => ToString(GitVersion.Minor); set => GitVersion.Minor = ToInt(value); } [DataMember] public string Patch { get => ToString(GitVersion.Patch); set => GitVersion.Patch = ToInt(value); } [DataMember] public string PreReleaseTag { get => GitVersion.PreReleaseTag; set => GitVersion.PreReleaseTag = value; } [DataMember] public string PreReleaseTagWithDash { get => GitVersion.PreReleaseTagWithDash; set => GitVersion.PreReleaseTagWithDash = value; } [DataMember] public string PreReleaseLabel { get => GitVersion.PreReleaseLabel; set => GitVersion.PreReleaseLabel = value; } [DataMember] public string PreReleaseNumber { get => ToString(GitVersion.PreReleaseNumber); set => GitVersion.PreReleaseNumber = ToNullableInt(value); } [DataMember] public string BuildMetaData { get => GitVersion.BuildMetaData; set => GitVersion.BuildMetaData = value; } [DataMember] public string BuildMetaDataPadded { get => GitVersion.BuildMetaDataPadded; set => GitVersion.BuildMetaDataPadded = value; } [DataMember] public string FullBuildMetaData { get => GitVersion.FullBuildMetaData; set => GitVersion.FullBuildMetaData = value; } [DataMember] public string MajorMinorPatch { get => GitVersion.MajorMinorPatch; set => GitVersion.MajorMinorPatch = value; } [DataMember] public string SemVer { get => GitVersion.SemVer; set => GitVersion.SemVer = value; } [DataMember] public string LegacySemVer { get => GitVersion.LegacySemVer; set => GitVersion.LegacySemVer = value; } [DataMember] public string LegacySemVerPadded { get => GitVersion.LegacySemVerPadded; set => GitVersion.LegacySemVerPadded = value; } [DataMember] public string AssemblySemVer { get => GitVersion.AssemblySemVer; set => GitVersion.AssemblySemVer = value; } [DataMember] public string AssemblySemFileVer { get => GitVersion.AssemblySemFileVer; set => GitVersion.AssemblySemFileVer = value; } [DataMember] public string FullSemVer { get => GitVersion.FullSemVer; set => GitVersion.FullSemVer = value; } [DataMember] public string InformationalVersion { get => GitVersion.InformationalVersion; set => GitVersion.InformationalVersion = value; } [DataMember] public string BranchName { get => GitVersion.BranchName; set => GitVersion.BranchName = value; } [DataMember] public string Sha { get => GitVersion.Sha; set => GitVersion.Sha = value; } [DataMember] public string NuGetVersionV2 { get => GitVersion.NuGetVersionV2; set => GitVersion.NuGetVersionV2 = value; } [DataMember] public string NuGetVersion { get => GitVersion.NuGetVersion; set => GitVersion.NuGetVersion = value; } [DataMember] public string CommitsSinceVersionSource { get => ToString(GitVersion.CommitsSinceVersionSource); set => GitVersion.CommitsSinceVersionSource = ToNullableInt(value); } [DataMember] public string CommitsSinceVersionSourcePadded { get => GitVersion.CommitsSinceVersionSourcePadded; set => GitVersion.CommitsSinceVersionSourcePadded = value; } [DataMember] public string CommitDate { get => GitVersion.CommitDate; set => GitVersion.CommitDate = value; } private static int? ToNullableInt(string value) => int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out int numericValue) ? numericValue : null as int?; private static int ToInt(string value) => int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out int numericValue) ? numericValue : -1; private static string ToString(int value) => value.ToString(CultureInfo.InvariantCulture); private static string ToString(int? value) => value.HasValue ? ToString(value.Value) : null; } }
using EpisodeInformer.Data; using EpisodeInformer.Data.Basics; using Ionic.Zip; using System; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.IO; using System.Threading; using System.Windows.Forms; namespace ServiceManager { public partial class frmDataCopy : Form { private string ovPath = (string)null; private bool cancel = false; public frmDataCopy() { this.InitializeComponent(); } private void frmDataCopy_Load(object sender, EventArgs e) { } private void btnCopy_Click(object sender, EventArgs e) { try { if (MessageBox.Show("Do you want to copy the data from this old backup file to your existing database?\n\n*** Important ***\nAny existing data will be overwritten (Event new data in the database will be overwritten with older data.)", "Copy Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; this.lblStatus.Text = "Copying :"; this.prgStatus.Style = ProgressBarStyle.Marquee; this.btnClose.Enabled = false; this.btnClear.Enabled = false; this.btnCopy.Enabled = false; new Thread(new ParameterizedThreadStart(this.DoProcess)).Start((object)this.txtBKFPath.Text); } catch (Exception) { } } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private void btnBKFOpen_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Multiselect = false; openFileDialog.Filter = "ZipFile (*.zip)|*.zip"; if (openFileDialog.ShowDialog() != DialogResult.OK) return; if (this.IsValidBackup(openFileDialog.FileName)) { this.txtBKFPath.Text = openFileDialog.FileName; string[] strArray = this.BKFInfo(openFileDialog.FileName); this.lblBKFDate.Text = strArray[0]; this.lblBKFVer.Text = strArray[1]; } else { int num = (int)MessageBox.Show("Backup file is invalid.", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } private void btnClear_Click(object sender, EventArgs e) { this.ResetForm(frmDataCopy.ResetReason.NORMAL, (string)null); } private void txtBKFPath_TextChanged(object sender, EventArgs e) { if (this.txtBKFPath.Text.Length == 0) { this.btnCopy.Enabled = false; this.lblStatus.Text = "Status :"; } else { this.btnCopy.Enabled = true; this.lblStatus.Text = "Waiting :"; } } private void DoProcess(object param) { try { string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempData"); if (!Directory.Exists(str)) { Directory.CreateDirectory(str); } else { Directory.Delete(str, true); Directory.CreateDirectory(str); } ZipFile zipFile = new ZipFile((string)param); zipFile.Password = "HMLROCKX"; zipFile.ExtractAll(str); zipFile.Dispose(); this.con = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Path.Combine(str, "Data\\EPIDB.mdb") + ";"); this.con.Open(); this.ovPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempData\\Data\\Overviews"); this.CopySeries(); this.CopyEpisode(); this.CopyDLSettings(); this.con.Close(); this.con.Dispose(); this.con = (OleDbConnection)null; Directory.Delete(str, true); this.ResetForm(frmDataCopy.ResetReason.DONE, (string)null); } catch (Exception ex) { this.ResetForm(frmDataCopy.ResetReason.ERROR, ex.Message); } } private void CopySeries() { try { OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(new OleDbCommand("SELECT * FROM Series", this.con)); DataSet dataSet = new DataSet(); oleDbDataAdapter.Fill(dataSet); if (dataSet.Tables[0].Rows.Count <= 0) return; foreach (DataRow dataRow in (InternalDataCollectionBase)dataSet.Tables[0].Rows) { try { int sID = (int)dataRow["sID"]; string Title = (string)dataRow["sTitle"]; int NoSea = (int)dataRow["sNoSeasons"]; int NoEpi = (int)dataRow["sNoEpisodes"]; string Overview = (string)null; string path = Path.Combine(this.ovPath, string.Format("{0}.epio", (object)sID)); if (File.Exists(path)) Overview = ProgramUtils.ReadOverviewFile(path); DBEMainActions.InsertSeries(sID, Title, Overview, NoSea, NoEpi); } catch (Exception) { } } } catch (Exception) { } } private void CopyEpisode() { try { OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(new OleDbCommand("SELECT * FROM Episodes", this.con)); DataSet dataSet = new DataSet(); oleDbDataAdapter.Fill(dataSet); if (dataSet.Tables[0].Rows.Count <= 0) return; foreach (DataRow dataRow in (InternalDataCollectionBase)dataSet.Tables[0].Rows) { try { int sID = (int)dataRow["sID"]; int eID = (int)dataRow["eID"]; string Name = (string)dataRow["eName"]; int EpisodeNum = (int)dataRow["eNumber"]; int SeasonNum = (int)dataRow["eSNumber"]; DateTime FAired = DateTime.Parse(dataRow["eAirDate"].ToString()); DateTime DLDate = DateTime.Parse(dataRow["eDownloadDate"].ToString()); DownloadStatus DLstatus = (DownloadStatus)Enum.Parse(typeof(DownloadStatus), dataRow["eDLStatus"].ToString()); string Overview = (string)null; string path = Path.Combine(this.ovPath, string.Format("{0}E{1}.epieo", (object)sID, (object)eID)); if (File.Exists(path)) Overview = ProgramUtils.ReadOverviewFile(path); DBEMainActions.InsertEpisode(sID, eID, Name, Overview, EpisodeNum, SeasonNum, FAired, DLDate, DLstatus); } catch (Exception) { } } } catch (Exception) { } } private void CopyDLSettings() { try { OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(new OleDbCommand("SELECT * FROM DownloadSettings", this.con)); DataSet dataSet = new DataSet(); oleDbDataAdapter.Fill(dataSet); if (dataSet.Tables[0].Rows.Count <= 0) return; foreach (DataRow dataRow in (InternalDataCollectionBase)dataSet.Tables[0].Rows) { try { DBEMainActions.InsertDLSettings((int)dataRow["sID"], (string)dataRow["sDLLocation"], (byte)dataRow["sDLQuality"], (string)dataRow["sDLKeywords"], (string)dataRow["sDLKeywordsEx"], (byte)dataRow["sPriority"], int.Parse(dataRow["sEpisodeFormat"].ToString())); } catch (Exception) { } } } catch (Exception) { } } private void ResetForm(frmDataCopy.ResetReason reasons, string msg) { if (this.InvokeRequired) { this.Invoke((Delegate)new frmDataCopy.delResetCallback(this.ResetForm), (object)reasons, (object)msg); } else { if (reasons == frmDataCopy.ResetReason.DONE) { this.lblStatus.Text = "Done :"; this.btnCopy.Enabled = true; int num = (int)MessageBox.Show("All possible data is copied to your database.", "Done Copying", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else if (reasons == frmDataCopy.ResetReason.ERROR) { this.lblStatus.Text = "Error :"; this.btnCopy.Enabled = true; int num = (int)MessageBox.Show("Error(s) occurred while copying data from the backup file, Please verify the backup file is valid and DBMS service is active and try-again.", "Error occured", MessageBoxButtons.OK, MessageBoxIcon.Hand); } else { this.lblStatus.Text = "Status :"; this.txtBKFPath.Text = ""; this.lblBKFDate.Text = "Unknown"; this.lblBKFVer.Text = "Unknown"; this.btnCopy.Enabled = false; } this.btnClear.Enabled = true; this.btnClose.Enabled = true; this.prgStatus.Style = ProgressBarStyle.Blocks; } } private string[] BKFInfo(string path) { string[] strArray1 = new string[2] { "Unknown", "Unknown" }; try { string[] strArray2 = new ZipFile(path).Comment.Split('|'); strArray1[0] = strArray2[0]; strArray1[1] = strArray2[1]; } catch (Exception) { strArray1 = new string[2] { "Unknown", "Unknown" }; } return strArray1; } private bool IsValidBackup(string path) { bool flag; try { ZipFile zipFile = new ZipFile(path); int.Parse(zipFile.Comment.Split('|')[1]); zipFile.Dispose(); flag = true; } catch (Exception) { flag = false; } return flag; } private void frmDataCopy_FormClosing(object sender, FormClosingEventArgs e) { if (!this.cancel) return; e.Cancel = true; int num = (int)MessageBox.Show("Cannot close this window until copy process compleates.", "Cannot Exit", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } private enum ResetReason { ERROR, DONE, NORMAL, } private delegate void delResetCallback(frmDataCopy.ResetReason reason, string msg); } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using EnvDTE; using VSLangProj; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// Represents an automation friendly version of a language-specific project. /// </summary> [ComVisible(true), CLSCompliant(false)] public class OAVSProject : VSProject { #region fields private ProjectNode project; private OAVSProjectEvents events; #endregion #region ctors internal OAVSProject(ProjectNode project) { this.project = project; } #endregion #region VSProject Members public virtual ProjectItem AddWebReference(string bstrUrl) { throw new NotImplementedException(); } public virtual BuildManager BuildManager { get { return null; //throw new NotImplementedException(); //return new OABuildManager(this.project); } } public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword) { throw new NotImplementedException(); } public virtual ProjectItem CreateWebReferencesFolder() { throw new NotImplementedException(); } public virtual DTE DTE { get { return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE)); } } public virtual VSProjectEvents Events { get { if (events == null) events = new OAVSProjectEvents(this); return events; } } public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut) { throw new NotImplementedException(); ; } public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile) { throw new NotImplementedException(); ; } public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt) { throw new NotImplementedException(); ; } public virtual Imports Imports { get { throw new NotImplementedException(); } } public virtual EnvDTE.Project Project { get { return this.project.GetAutomationObject() as EnvDTE.Project; } } public virtual References References { get { ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode; if (null == references) { return new OAReferences(null, project); } return references.Object as References; } } public virtual void Refresh() { } public virtual string TemplatePath { get { throw new NotImplementedException(); } } public virtual ProjectItem WebReferencesFolder { get { throw new NotImplementedException(); } } public virtual bool WorkOffline { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion } /// <summary> /// Provides access to language-specific project events /// </summary> [ComVisible(true), CLSCompliant(false)] public class OAVSProjectEvents : VSProjectEvents { #region fields private OAVSProject vsProject; #endregion #region ctors public OAVSProjectEvents(OAVSProject vsProject) { this.vsProject = vsProject; } #endregion #region VSProjectEvents Members public virtual BuildManagerEvents BuildManagerEvents { get { return vsProject.BuildManager as BuildManagerEvents; } } public virtual ImportsEvents ImportsEvents { get { throw new NotImplementedException(); } } public virtual ReferencesEvents ReferencesEvents { get { return vsProject.References as ReferencesEvents; } } #endregion } }
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Channels; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading; using System.Runtime.Serialization; using Belikov.Common.ThreadProcessing; using Belikov.GenuineChannels.BufferPooling; using Belikov.GenuineChannels.Connection; using Belikov.GenuineChannels.DotNetRemotingLayer; using Belikov.GenuineChannels.Logbook; using Belikov.GenuineChannels.Messaging; using Belikov.GenuineChannels.Parameters; using Belikov.GenuineChannels.Receiving; using Belikov.GenuineChannels.Security; using Belikov.GenuineChannels.TransportContext; using Belikov.GenuineChannels.Utilities; namespace Belikov.GenuineChannels.GenuineHttp { /// <summary> /// Implements HTTP transport manager working via .NET Remoting http web request implementation. /// </summary> internal class HttpClientConnectionManager : ConnectionManager, ITimerConsumer { /// <summary> /// Constructs an instance of the HttpClientConnectionManager class. /// </summary> /// <param name="iTransportContext">The transport context.</param> public HttpClientConnectionManager(ITransportContext iTransportContext) : base(iTransportContext) { this.Local = new HostInformation("_ghttp://" + iTransportContext.HostIdentifier, iTransportContext); // calculate host renewing timespan this._hostRenewingSpan = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]) + GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); this._internal_TimerCallback = new WaitCallback(Internal_TimerCallback); this._pool_Sender_OnEndSending_ContinueExchange = new WaitCallback(this.Pool_Sender_OnEndSending_ContinueExchange); this._listener_OnEndReceiving_ContinueExchange = new WaitCallback(this.Pool_Sender_OnEndSending_ContinueExchange); this._webRequestInitiationTimeout = (TimeSpan) iTransportContext.IParameterProvider[GenuineParameter.HttpWebRequestInitiationTimeout]; this._httpAsynchronousRequestTimeout = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.HttpAsynchronousRequestTimeout]); TimerProvider.Attach(this); } /// <summary> /// Sends the message to the remote host. /// </summary> /// <param name="message">The message to be sent.</param> protected override void InternalSend(Message message) { switch (message.SecuritySessionParameters.GenuineConnectionType) { case GenuineConnectionType.Persistent: this.InternalSend(message, this.Pool_GetConnectionForSending(message)); break; case GenuineConnectionType.Named: throw new NotSupportedException("Genuine HTTP client connection manager doesn't support named connections."); case GenuineConnectionType.Invocation: HttpInvocationConnection httpInvocationConnection = this.FindInvocationConnection(message); httpInvocationConnection.SendMessage(message); break; } } /// <summary> /// Sends the message to the remote host. /// </summary> /// <param name="message">The message to be sent.</param> /// <param name="httpClientConnection">The connection.</param> private void InternalSend(Message message, HttpClientConnection httpClientConnection) { bool sendingLockObtained = false; lock (httpClientConnection.SendingLock) { if (! httpClientConnection.IsSent) { httpClientConnection.IsSent = true; sendingLockObtained = true; } else { httpClientConnection.MessageContainer.AddMessage(message, false); } } if (sendingLockObtained) this.LowLevel_Sender_Send(message, httpClientConnection, httpClientConnection.OnEndSending, false); } #region -- Invocation connections ---------------------------------------------------------- /// <summary> /// Set of invocation connections { remote url => connection }. /// </summary> private Hashtable _invocation = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Gets an invocation connection that is able to deliver a message and receive a result. /// </summary> /// <param name="message">The source message.</param> /// <returns>An invocation connection that is able to deliver a message and receive a result.</returns> private HttpInvocationConnection FindInvocationConnection(Message message) { lock (this._invocation.SyncRoot) { HttpInvocationConnection httpInvocationConnection = this._invocation[message.Recipient.Url] as HttpInvocationConnection; if (httpInvocationConnection == null) this._invocation[message.Recipient.Url] = httpInvocationConnection = new HttpInvocationConnection(this.ITransportContext, message.Recipient); return httpInvocationConnection; } } #endregion #region -- Pool management ----------------------------------------------------------------- /// <summary> /// Set of connections {remote url => connection}. /// </summary> private Hashtable _persistent = Hashtable.Synchronized(new Hashtable()); /// <summary> /// TimeSpan to renew the host resource for. /// </summary> private int _hostRenewingSpan; /// <summary> /// Opens or returns established connection according to message parameters. /// </summary> /// <param name="message">The message.</param> /// <returns>The established connection.</returns> private HttpClientConnection Pool_GetConnectionForSending(Message message) { HttpClientConnection httpClientConnection = null; using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) throw OperationException.WrapException(this._disposeReason); } string connectionName = message.ConnectionName; if (connectionName == null || connectionName.Length <= 0) connectionName = "$/__GC/" + message.Recipient.PrimaryUri; if (! Monitor.TryEnter(message.Recipient.PersistentConnectionEstablishingLock, GenuineUtility.GetMillisecondsLeft(message.FinishTime))) throw GenuineExceptions.Get_Send_Timeout(); try { lock (this._persistent.SyncRoot) { httpClientConnection = this._persistent[message.Recipient.Url] as HttpClientConnection; if (httpClientConnection != null && httpClientConnection._disposed) { this._persistent.Remove(message.Recipient.Url); httpClientConnection = null; } if (httpClientConnection != null) return httpClientConnection; } // it's necessary to open the connection to the remote host httpClientConnection = this.LowLevel_OpenConnection(message.Recipient, message.SecuritySessionParameters.GenuineConnectionType, connectionName); using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) { httpClientConnection.Dispose(this._disposeReason); throw OperationException.WrapException(this._disposeReason); } this._persistent[message.Recipient.Url] = httpClientConnection; } httpClientConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); httpClientConnection.MessageContainer = new MessageContainer(this.ITransportContext); } finally { Monitor.Exit(message.Recipient.PersistentConnectionEstablishingLock); } return httpClientConnection; } /// <summary> /// Finishes sending a message through the connection. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="httpWebResponse">The received response.</param> public void Pool_Sender_OnEndSending(HttpClientConnection httpClientConnection, HttpWebResponse httpWebResponse) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; Stream inputStream = null; try { httpClientConnection.Remote.Renew(this._hostRenewingSpan, false); httpClientConnection.LastMessageWasReceviedAt = GenuineUtility.TickCount; httpClientConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); httpClientConnection.SentContent.Close(); httpClientConnection.SentContent = null; httpClientConnection.MessagesBeingSent.Clear(); // process the content inputStream = httpWebResponse.GetResponseStream(); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { GenuineChunkedStream content = null; if (binaryLogWriter[LogCategory.Transport] > 1) { content = new GenuineChunkedStream(false); GenuineUtility.CopyStreamToStream(inputStream, content, (int) httpWebResponse.ContentLength); } binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.Pool_Sender_OnEndSending", LogMessageType.AsynchronousSendingFinished, null, null, httpClientConnection.Remote, binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? content : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.DbgConnectionId, (int) httpWebResponse.ContentLength, null, null, null, "The content of the response received by the sender connection."); if (binaryLogWriter[LogCategory.Transport] > 1) inputStream = content; } BinaryReader binaryReader = new BinaryReader(inputStream); string serverUri; int sequenceNo; HttpPacketType httpPacketType; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier); if (sequenceNo != httpClientConnection.SendSequenceNo) throw GenuineExceptions.Get_Receive_IncorrectData(); if (httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent) httpClientConnection.Remote.UpdateUri(serverUri, remoteHostUniqueIdentifier); if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.Pool_Sender_OnEndSending", LogMessageType.LowLevelTransport_AsyncSendingCompleted, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, httpClientConnection.Sender_ConnectionLevelSecurity == null ? null : httpClientConnection.Sender_ConnectionLevelSecurity.Name, httpClientConnection.DbgConnectionId, (int) httpPacketType, sequenceNo, 0, null, null, null, null, "SENDER invocation completed. Type of the packet: {0}. Server Uri: {1}. Seq No: {2}", Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), serverUri, sequenceNo); } if (httpPacketType == HttpPacketType.Desynchronization) { this.ConnectionFailed(httpClientConnection, true, GenuineExceptions.Get_Channel_Desynchronization(), false); return ; } if (httpPacketType == HttpPacketType.SenderError) { Exception deserializedException = null; try { BinaryFormatter binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other)); deserializedException = binaryFormatter.Deserialize(inputStream) as Exception; } catch { } if (deserializedException != null) this.ConnectionFailed(httpClientConnection, true, GenuineExceptions.Get_Receive_ConnectionClosed(deserializedException.Message), false); else this.ConnectionFailed(httpClientConnection, true, GenuineExceptions.Get_Receive_ConnectionClosed("Remote host was not able to parse the request. Probably due to the security reasons."), false); return ; } // fetch and process messages this.LowLevel_ParseLabelledStream(inputStream, httpClientConnection.Sender_ReceiveBuffer, httpClientConnection, httpClientConnection.Sender_ConnectionLevelSecurity); } finally { if (inputStream != null) inputStream.Close(); httpWebResponse.Close(); // TODO: remove this if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Debugging] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.Pool_Sender_OnEndSending", LogMessageType.DebuggingSuccess, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, null, httpClientConnection.DbgConnectionId, -1, -1, -1, null, null, null, null, "HttpClientConnectionManager.Pool_Sender_OnEndSending is completed."); } } GenuineThreadPool.QueueUserWorkItem(this._pool_Sender_OnEndSending_ContinueExchange, httpClientConnection, false); } private WaitCallback _pool_Sender_OnEndSending_ContinueExchange; /// <summary> /// This is the second part of the Pool_Sender_OnEndSending implementation being /// executed in the separate thread to prevent .NET Framework internal deadlock. /// </summary> /// <param name="httpClientConnectionAsObject">The connection.</param> private void Pool_Sender_OnEndSending_ContinueExchange(object httpClientConnectionAsObject) { Message message = null; HttpClientConnection httpClientConnection = (HttpClientConnection) httpClientConnectionAsObject; lock (httpClientConnection.SendingLock) { // analyze the queue message = httpClientConnection.MessageContainer.GetMessage(); if (message == null) { // release the lock httpClientConnection.IsSent = false; return ; } } Debug.Assert(httpClientConnection.IsSent == true); this.LowLevel_Sender_Send(message, httpClientConnection, httpClientConnection.OnEndSending, false); } /// <summary> /// Processes failed or closed connections. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="sender">The type of the failed connection (P/Async).</param> /// <param name="exception">The exception.</param> /// <param name="tryToReestablish">True if it's a good idea to try to reestablish the connection.</param> public void ConnectionFailed(HttpClientConnection httpClientConnection, bool sender, Exception exception, bool tryToReestablish) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; try { if (tryToReestablish) tryToReestablish = ! ConnectionManager.IsExceptionCritical(exception as OperationException); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ConnectionFailed", LogMessageType.ConnectionFailed, exception, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Connection failure. Sender: {0}. Connection type: {1}. Try to reestablish: {2}.", sender.ToString(), Enum.GetName(typeof(GenuineConnectionType), httpClientConnection.GenuineConnectionType), tryToReestablish.ToString()); } using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) tryToReestablish = false; } lock (httpClientConnection.Remote.PersistentConnectionEstablishingLock) { if (! tryToReestablish || httpClientConnection._disposed) { using (new ReaderAutoLocker(this._disposeLock)) { this._persistent.Remove(httpClientConnection.Remote.Url); } // close the content if (httpClientConnection.SentContent != null) { httpClientConnection.SentContent.Close(); httpClientConnection.SentContent = null; } // release all resources this.ITransportContext.KnownHosts.ReleaseHostResources(httpClientConnection.Remote, exception); foreach (Message message in httpClientConnection.MessagesBeingSent) this.ITransportContext.IIncomingStreamHandler.DispatchException(message, exception); httpClientConnection.MessagesBeingSent.Clear(); httpClientConnection.Dispose(exception); httpClientConnection.SignalState(GenuineEventType.GeneralConnectionClosed, exception, null); if (exception is OperationException && ((OperationException) exception).OperationErrorMessage.ErrorIdentifier == "GenuineChannels.Exception.Receive.ServerHasBeenRestarted") httpClientConnection.SignalState(GenuineEventType.GeneralServerRestartDetected, exception, null); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ConnectionFailed", LogMessageType.ConnectionFailed, exception, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection has been completely terminated and removed from all collection. Sender: {0}. Connection type: {1}. Try to reestablish: {2}.", sender.ToString(), Enum.GetName(typeof(GenuineConnectionType), httpClientConnection.GenuineConnectionType), tryToReestablish.ToString()); } return ; } httpClientConnection.SignalState(GenuineEventType.GeneralConnectionReestablishing, exception, null); HttpClientConnection.ReconnectionContainer reconnectionContainer = sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; lock (reconnectionContainer.SyncLock) { if (GenuineUtility.IsTimeoutExpired(reconnectionContainer.ReconnectionStartedAt + GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]))) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ConnectionFailed", LogMessageType.ConnectionReestablishing, GenuineExceptions.Get_Debugging_GeneralWarning("Connection was not reestablished within the specified time boundaries."), null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection has not been reestablished within the specified time boundaries."); } // just close the connection using (new ReaderAutoLocker(this._disposeLock)) { this._persistent.Remove(httpClientConnection.Remote.Url); } this.ITransportContext.KnownHosts.ReleaseHostResources(httpClientConnection.Remote, exception); httpClientConnection.Dispose(exception); httpClientConnection.MessageContainer.Dispose(exception); // and fire a warning httpClientConnection.SignalState(GenuineEventType.GeneralConnectionClosed, exception, null); return ; } // resend the content or rerequest the previous content if (sender) { if (httpClientConnection.SentContent != null) this.LowLevel_Sender_Send(null, httpClientConnection, httpClientConnection.OnEndSending, true); } else this.LowLevel_InitiateListening(httpClientConnection, false); } } } catch(Exception ex) { if ( binaryLogWriter != null ) binaryLogWriter.WriteImplementationWarningEvent("HttpClientConnectionManager.ConnectionFailed", LogMessageType.Error, ex, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, "Unexpected exception occurred in the HttpClientConnectionManager.ConnectionFailed method. Most likely, something must be fixed."); } } /// <summary> /// Closes expired connections and sends ping via inactive connections. /// </summary> public void TimerCallback() { GenuineThreadPool.QueueUserWorkItem(_internal_TimerCallback, null, false); } private WaitCallback _internal_TimerCallback; /// <summary> /// Closes expired connections and sends ping via inactive connections. /// </summary> /// <param name="ignored">Ignored.</param> private void Internal_TimerCallback(object ignored) { int now = GenuineUtility.TickCount; int sendPingAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.PersistentConnectionSendPingAfterInactivity]); int closePersistentConnectionAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]); int closeInvocationConnectionsAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.CloseInvocationConnectionAfterInactivity]); int closeOneWayConnectionsAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.CloseOneWayConnectionAfterInactivity]); int reconnectionFailedAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); // go through the pool and close all expired connections // persistent ArrayList connectionsBeingRemoved = new ArrayList(); DictionaryEntry[] entries = null; lock (this._persistent.SyncRoot) { entries = new DictionaryEntry[this._persistent.Count]; this._persistent.CopyTo(entries, 0); } foreach (DictionaryEntry dictionaryEntry in entries) { HttpClientConnection httpClientConnection = (HttpClientConnection) dictionaryEntry.Value; if (httpClientConnection._disposed) { connectionsBeingRemoved.Add(dictionaryEntry.Key); continue; } // retrieve reconnection information in a transaction bool isReconnectionStarted = false; int reconnectionStarted = 0; lock (httpClientConnection.ListenerReconnectionLock.SyncLock) { isReconnectionStarted |= httpClientConnection.ListenerReconnectionLock.IsReconnectionStarted; if (httpClientConnection.ListenerReconnectionLock.IsReconnectionStarted) reconnectionStarted = httpClientConnection.ListenerReconnectionLock.ReconnectionStartedAt; } lock (httpClientConnection.SenderReconnectionLock.SyncLock) { isReconnectionStarted |= httpClientConnection.SenderReconnectionLock.IsReconnectionStarted; if (httpClientConnection.SenderReconnectionLock.IsReconnectionStarted) reconnectionStarted = httpClientConnection.SenderReconnectionLock.ReconnectionStartedAt; } if (GenuineUtility.IsTimeoutExpired(httpClientConnection.LastMessageWasReceviedAt + closePersistentConnectionAfter, now)) { // if connection is not being reestablished, then it's necessary to close it // if it's being reestablished, it comes under reestablishing rules if ( ! isReconnectionStarted ) GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.PerformConnectionFailure), httpClientConnection, false); } if (GenuineUtility.IsTimeoutExpired(httpClientConnection.LastMessageWasSentAt + sendPingAfter, now)) GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.SendPing), httpClientConnection, false); if ( isReconnectionStarted && GenuineUtility.IsTimeoutExpired(reconnectionStarted + reconnectionFailedAfter, now)) GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.PerformConnectionFailure), httpClientConnection, false); } foreach (object key in connectionsBeingRemoved) this._persistent.Remove(key); } /// <summary> /// Closes the expired connection. /// </summary> /// <param name="httpClientConnectionAsObject">The connection to be closed.</param> private void PerformConnectionFailure(object httpClientConnectionAsObject) { this.ConnectionFailed(httpClientConnectionAsObject as HttpClientConnection, true, GenuineExceptions.Get_Channel_ConnectionClosedAfterTimeout(), false); } /// <summary> /// Sends a ping through the specified connection. /// </summary> /// <param name="httpClientConnectionAsObject">The connection.</param> private void SendPing(object httpClientConnectionAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection httpClientConnection = null; try { httpClientConnection = (HttpClientConnection) httpClientConnectionAsObject; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.SendPing", LogMessageType.ConnectionPingSending, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Sending a ping."); } //Message message = new Message(this.ITransportContext, httpClientConnection.Remote, GenuineReceivingHandler.PING_MESSAGE_REPLYID, new TransportHeaders(), Stream.Null); Message message = new Message(this.ITransportContext, httpClientConnection.Remote, -1, new TransportHeaders(), Stream.Null); message.IsSynchronous = false; this.Send(message); } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.SendPing", LogMessageType.ConnectionPingSending, ex, null, httpClientConnection == null ? null : httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection == null ? -1 : httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Exception occurred while sending a ping."); } } } #endregion #region -- Connection recovering ----------------------------------------------------------- /// <summary> /// Represents a failed HTTP request. /// </summary> private class FailedHttpRequest { /// <summary> /// The connection. /// </summary> public HttpClientConnection HttpClientConnection; /// <summary> /// The reason of failure. /// </summary> public Exception Exception; /// <summary> /// Represents a value indicating the type of the failed connection. /// </summary> public bool Sender; } /// <summary> /// Tries to reestablish the failed connection. /// </summary> /// <param name="failedHttpRequestAsObject">The failed request.</param> private void ReestablishFailedConnection(object failedHttpRequestAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; using(new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) return ; } FailedHttpRequest failedHttpRequest = (FailedHttpRequest) failedHttpRequestAsObject; HttpClientConnection httpClientConnection = failedHttpRequest.HttpClientConnection; HttpClientConnection.ReconnectionContainer reconnectionContainer = failedHttpRequest.Sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; // this variable is used to prevent from setting reconnectionContainer.IsReconnectionStarted to false // within a very short period of time bool closureClosed = false; try { Exception exception = failedHttpRequest.Exception; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.ConnectionReestablishing, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} HTTP connection. System.Net.ServicePointManager.DefaultConnectionLimit = {1}.", failedHttpRequest.Sender ? "SENDER" : "LISTENER", System.Net.ServicePointManager.DefaultConnectionLimit); } int reconnectionMustBeFinishedBefore = GenuineUtility.GetTimeout((TimeSpan) httpClientConnection.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); for ( int i = 0; i < (int) httpClientConnection.ITransportContext.IParameterProvider[GenuineParameter.ReconnectionTries] && ! GenuineUtility.IsTimeoutExpired(reconnectionMustBeFinishedBefore) && ! httpClientConnection._disposed; i++ ) { Thread.Sleep((TimeSpan) httpClientConnection.ITransportContext.IParameterProvider[GenuineParameter.SleepBetweenReconnections]); using(new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) return ; } lock (reconnectionContainer.SyncLock) { reconnectionContainer.RequestFailed = false; } if (httpClientConnection._disposed) return ; try { // TODO: remove this // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.DebuggingWarning, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} attempt #{1}", failedHttpRequest.Sender ? "SENDER" : "LISTENER", i); } this.ConnectionFailed(httpClientConnection, failedHttpRequest.Sender, exception, true); lock (reconnectionContainer.SyncLock) { // TODO: remove this // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.DebuggingWarning, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} attempt N{1} RESULT: {2}", failedHttpRequest.Sender ? "SENDER" : "LISTENER", i, reconnectionContainer.RequestFailed ? "FAILURE" : "SUCCESS"); } if (reconnectionContainer.RequestFailed) continue; closureClosed = true; reconnectionContainer.IsReconnectionStarted = false; return; } } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.ConnectionReestablishing, ex, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing attempt failed. Reestablishing the {0} HTTP connection will be continued. Try: {1}. Milliseconds left: {2}", failedHttpRequest.Sender ? "SENDER" : "LISTENER", i, GenuineUtility.CompareTickCounts(reconnectionMustBeFinishedBefore, GenuineUtility.TickCount)); } httpClientConnection.SignalState(GenuineEventType.GeneralConnectionReestablishing, ex, null); } } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReestablishFailedConnection", LogMessageType.ConnectionReestablished, GenuineExceptions.Get_Debugging_GeneralWarning("Reestablishing failed."), null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Reestablishing the {0} HTTP connection has failed.", failedHttpRequest.Sender ? "SENDER" : "LISTENER"); } // connection can not be restored this.ConnectionFailed(httpClientConnection, failedHttpRequest.Sender, exception, false); } finally { if (! closureClosed) reconnectionContainer.IsReconnectionStarted = false; } } #endregion #region -- Low-level layer ----------------------------------------------------------------- /// <summary> /// Represents a value indicating the maximum time period of WebRequest initialization. /// </summary> private TimeSpan _webRequestInitiationTimeout; private int _httpAsynchronousRequestTimeout; /// <summary> /// Sends the message to the remote host through the sender connection. /// </summary> /// <param name="message">Message to be sent.</param> /// <param name="httpClientConnection">The connection.</param> /// <param name="asyncCallback">The callback to be called after the operation will be completed.</param> /// <param name="repeatSending">Whether to send the previous content again.</param> private void LowLevel_Sender_Send(Message message, HttpClientConnection httpClientConnection, AsyncCallback asyncCallback, bool repeatSending) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; // connection lock obtained, assemble the packet and send it try { if (! repeatSending) { httpClientConnection.SendSequenceNo ++; httpClientConnection.LastMessageWasSentAt = GenuineUtility.TickCount; httpClientConnection.SentContent = new GenuineChunkedStream(false); MessageCoder.FillInLabelledStream(message, httpClientConnection.MessageContainer, httpClientConnection.MessagesBeingSent, httpClientConnection.SentContent, httpClientConnection.Sender_SendBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Transport] > 0 ) { for ( int i = 0; i < httpClientConnection.MessagesBeingSent.Count; i++) { Message nextMessage = (Message) httpClientConnection.MessagesBeingSent[i]; binaryLogWriter.WriteEvent(LogCategory.Transport, "HttpClientConnectionManager.LowLevel_Sender_Send", LogMessageType.MessageIsSentAsynchronously, null, nextMessage, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, null, httpClientConnection.DbgConnectionId, httpClientConnection.SendSequenceNo, 0, 0, null, null, null, null, "The message will be sent in the SENDER stream N: {0}.", httpClientConnection.SendSequenceNo); } } // apply CLSSE if (httpClientConnection.Sender_ConnectionLevelSecurity != null) { GenuineChunkedStream encryptedContent = new GenuineChunkedStream(false); httpClientConnection.Sender_ConnectionLevelSecurity.Encrypt(httpClientConnection.SentContent, encryptedContent); httpClientConnection.SentContent = encryptedContent; } // prepare the final version of the content GenuineChunkedStream resultStream = new GenuineChunkedStream(false); BinaryWriter binaryWriter = new BinaryWriter(resultStream); HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, httpClientConnection.GenuineConnectionType, httpClientConnection.HostId, HttpPacketType.Usual, httpClientConnection.SendSequenceNo, httpClientConnection.ConnectionName, httpClientConnection.Remote.LocalHostUniqueIdentifier); if (httpClientConnection.SentContent.CanSeek) resultStream.WriteStream(httpClientConnection.SentContent); else GenuineUtility.CopyStreamToStream(httpClientConnection.SentContent, resultStream); httpClientConnection.SentContent = resultStream; } else { httpClientConnection.SentContent.Position = 0; } // try to send it httpClientConnection.Sender = httpClientConnection.InitializeRequest(true, httpClientConnection._keepalive); httpClientConnection.Sender.ContentLength = httpClientConnection.SentContent.Length; this.LowLevel_InitiateHttpWebRequest(httpClientConnection.Sender, httpClientConnection.SentContent, httpClientConnection.SenderClosed, true, asyncCallback, httpClientConnection); } catch(Exception ex) { // sending failed, rollback the entire operation // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_Sender_Send", LogMessageType.AsynchronousSendingFinished, ex, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Error occurred while sending a message to the remote host."); } this.StartReestablishingIfNecessary(httpClientConnection, ex, true); } } /// <summary> /// Initiates the HTTP request. /// </summary> /// <param name="httpWebRequest">The instance of the HttpWebRequest class.</param> /// <param name="inputStream">The input stream.</param> /// <param name="closed">The state event.</param> /// <param name="sender">Indicates whether the sender request is being sent.</param> /// <param name="asyncCallback">The callback.</param> /// <param name="dbgHttpClientConnection">The connection provided for debugging purposes.</param> private void LowLevel_InitiateHttpWebRequest(HttpWebRequest httpWebRequest, Stream inputStream, ManualResetEvent closed, bool sender, AsyncCallback asyncCallback, HttpClientConnection dbgHttpClientConnection) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; using(new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) throw OperationException.WrapException(this._disposeReason); } Stream requestStream = null; try { if (! closed.WaitOne(this._webRequestInitiationTimeout, false)) throw GenuineExceptions.Get_Processing_LogicError("[0] Deadlock or a heavy load."); closed.Reset(); requestStream = httpWebRequest.GetRequestStream(); if (binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.LowLevel_InitiateHttpWebRequest", LogMessageType.LowLevelTransport_AsyncSendingInitiating, null, null, dbgHttpClientConnection == null ? null : dbgHttpClientConnection.Remote, binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? inputStream : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, dbgHttpClientConnection == null ? -1 : dbgHttpClientConnection.DbgConnectionId, (int) inputStream.Length, null, null, null, "HTTP {0} Request is being sent. Size: {1}.", sender ? "SENDER" : "LISTENER", (int) inputStream.Length); } GenuineUtility.CopyStreamToStream(inputStream, requestStream, (int) inputStream.Length); this.IncreaseBytesSent((int) inputStream.Length); HttpWebRequestCop webRequestCop = new HttpWebRequestCop(httpWebRequest, asyncCallback, httpWebRequest, this._httpAsynchronousRequestTimeout); //httpWebRequest.BeginGetResponse(asyncCallback, httpWebRequest); } catch(Exception ex) { if (binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.LowLevel_InitiateHttpWebRequest", LogMessageType.LowLevelTransport_AsyncSendingInitiating, ex, null, dbgHttpClientConnection == null ? null : dbgHttpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, dbgHttpClientConnection == null ? -1 : dbgHttpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Exception occurred while initiating HTTP request."); } try { httpWebRequest.Abort(); } catch(Exception) { } throw; } finally { try { if (requestStream != null) requestStream.Close(); } catch(Exception ex) { // ignore & warning if (binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.LowLevel_InitiateHttpWebRequest", LogMessageType.LowLevelTransport_AsyncSendingInitiating, ex, null, dbgHttpClientConnection == null ? null : dbgHttpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, dbgHttpClientConnection == null ? -1 : dbgHttpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Can't close the stream!"); } } closed.Set(); } } /// <summary> /// Opens connection to the remote host. /// </summary> /// <param name="remote">The remote host.</param> /// <param name="genuineConnectionType">The type of the connection.</param> /// <param name="connectionName">The name of the connection.</param> /// <returns>The opened connection.</returns> private HttpClientConnection LowLevel_OpenConnection(HostInformation remote, GenuineConnectionType genuineConnectionType, string connectionName) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; using (new ReaderAutoLocker(this._disposeLock)) { if (this._disposed) throw OperationException.WrapException(this._disposeReason); } // the time we should finish connection establishing before int timeout = GenuineUtility.GetTimeout((TimeSpan) this.ITransportContext.IParameterProvider[GenuineParameter.ConnectTimeout]); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablishing, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "The connection is being established to \"{0}\".", remote == null ? "?" : remote.Url == null ? "?" : remote.Url); } // first - send the check request and start CLSSE HttpClientConnection httpClientConnection = new HttpClientConnection(this.ITransportContext, connectionName); httpClientConnection.Remote = remote; httpClientConnection.GenuineConnectionType = genuineConnectionType; httpClientConnection.Sender_ConnectionLevelSecurity = this.CreateConnectionLevelSecuritySession(genuineConnectionType); httpClientConnection.Listener_ConnectionLevelSecurity = this.CreateConnectionLevelSecuritySession(genuineConnectionType); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteConnectionParameterEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionParameters, null, remote, this.ITransportContext.IParameterProvider, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.DbgConnectionId, "An HTTP connection is being established."); } // gather the output stream Stream senderInputClsseStream = Stream.Null; Stream listenerInputClsseStream = Stream.Null; Stream clsseStream = null; GenuineChunkedStream outputStream = null; bool resend = false; bool firstFailure = false; // CLSS establishing for ( int i = 0; ; i++ ) { bool noClsseToSend = true; if (! resend) { // build the content outputStream = new GenuineChunkedStream(false); BinaryWriter binaryWriter = new BinaryWriter(outputStream); HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, genuineConnectionType, httpClientConnection.HostId, i == 0 ? HttpPacketType.Establishing_ResetConnection : HttpPacketType.Establishing, ++httpClientConnection.SendSequenceNo, httpClientConnection.ConnectionName, remote.LocalHostUniqueIdentifier); // CLSSE info using (new GenuineChunkedStreamSizeLabel(outputStream)) { if (httpClientConnection.Sender_ConnectionLevelSecurity != null && ! httpClientConnection.Sender_ConnectionLevelSecurity.IsEstablished) { clsseStream = httpClientConnection.Sender_ConnectionLevelSecurity.EstablishSession(senderInputClsseStream, true); if (clsseStream != null) { noClsseToSend = false; GenuineUtility.CopyStreamToStream(clsseStream, outputStream); } } } // CLSSE info using (new GenuineChunkedStreamSizeLabel(outputStream)) { if (httpClientConnection.Listener_ConnectionLevelSecurity != null && ! httpClientConnection.Listener_ConnectionLevelSecurity.IsEstablished) { clsseStream = httpClientConnection.Listener_ConnectionLevelSecurity.EstablishSession(listenerInputClsseStream, true); if (clsseStream != null) { noClsseToSend = false; GenuineUtility.CopyStreamToStream(clsseStream, outputStream); } } } } else outputStream.Position = 0; // parse the response HttpWebRequest httpWebRequest = httpClientConnection.InitializeRequest(true, httpClientConnection._keepalive); int millisecondsRemain = GenuineUtility.CompareTickCounts(timeout, GenuineUtility.TickCount); if ( millisecondsRemain <= 0) throw GenuineExceptions.Get_Channel_ConnectionClosedAfterTimeout(); httpWebRequest.Timeout = millisecondsRemain; httpWebRequest.ContentLength = outputStream.Length; Stream requestStream = null; try { requestStream = httpWebRequest.GetRequestStream(); GenuineUtility.CopyStreamToStream(outputStream, requestStream, (int) outputStream.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse()) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { StringBuilder stringBuilderHeaders = new StringBuilder(1024); foreach (string headerName in httpWebResponse.Headers.Keys) stringBuilderHeaders.AppendFormat("{0}=\"{1}\"; ", headerName, httpWebResponse.Headers.Get(headerName)); binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablishing, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The trial connection has been successfully completed. Content-Length: {0}; Content encoding: {1}; Content type: {2}; Protocol version: {3}; Respose uri: {4}; Status code: {5}; Status description: {6}; HTTP headers: {7}.", httpWebResponse.ContentLength, httpWebResponse.ContentEncoding, httpWebResponse.ContentType, httpWebResponse.ProtocolVersion, httpWebResponse.ResponseUri, httpWebResponse.StatusCode, httpWebResponse.StatusDescription, stringBuilderHeaders.ToString()); } using (Stream responseStream = httpWebResponse.GetResponseStream()) { BinaryReader binaryReader = new BinaryReader(responseStream); string serverUri; int sequenceNo; HttpPacketType httpPacketType; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier); if ( httpPacketType != HttpPacketType.Establishing && httpPacketType != HttpPacketType.Establishing_ResetConnection ) throw GenuineExceptions.Get_Connect_CanNotConnectToRemoteHost(remote.ToString(), "Wrong response received from the remote host."); // check the restartion if either CLSS or the persistent connection is used if (genuineConnectionType == GenuineConnectionType.Persistent || httpClientConnection.Sender_ConnectionLevelSecurity != null) remote.UpdateUri(serverUri, remoteHostUniqueIdentifier); // the first SS int writtenSize = binaryReader.ReadInt32(); senderInputClsseStream = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(responseStream, senderInputClsseStream, writtenSize); writtenSize = binaryReader.ReadInt32(); listenerInputClsseStream = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(responseStream, listenerInputClsseStream, writtenSize); } } outputStream.Close(); } catch(Exception ex) { if (firstFailure) throw; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablishing, ex, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Exception occurred while establishing the connection to \"{0}\". The connection establishing will be continued.", remote == null ? "?" : remote.Url == null ? "?" : remote.Url); } // try to recover resend = true; continue; } finally { if (requestStream != null) requestStream.Close(); } firstFailure = false; resend = false; if (httpClientConnection.Sender_ConnectionLevelSecurity != null && ! httpClientConnection.Sender_ConnectionLevelSecurity.IsEstablished) continue; if (httpClientConnection.Listener_ConnectionLevelSecurity != null && ! httpClientConnection.Listener_ConnectionLevelSecurity.IsEstablished) continue; if (! noClsseToSend) continue; break; } // start listener if it's a persistent connection remote.PhysicalAddress = remote.Url; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 ) { binaryLogWriter.WriteHostInformationEvent("HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.HostInformationCreated, null, remote, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, httpClientConnection.Sender_ConnectionLevelSecurity == null ? null : httpClientConnection.Sender_ConnectionLevelSecurity.Name, httpClientConnection.DbgConnectionId, "HostInformation is ready for actions."); } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_OpenConnection", LogMessageType.ConnectionEstablished, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Sender_ConnectionLevelSecurity, httpClientConnection.Sender_ConnectionLevelSecurity == null ? null : httpClientConnection.Sender_ConnectionLevelSecurity.Name, httpClientConnection.DbgConnectionId, (int) genuineConnectionType, 0, 0, this.GetType().Name, remote.Url, remote.Url, null, "The connection to the remote host is established."); } if (genuineConnectionType == GenuineConnectionType.Persistent) this.LowLevel_InitiateListening(httpClientConnection, true); return httpClientConnection; } /// <summary> /// Reads messages from the stream and processes them. /// </summary> /// <param name="stream">The source stream.</param> /// <param name="intermediateBuffer">The intermediate buffer.</param> /// <param name="httpClientConnection">The connection.</param> /// <param name="connectionLevelSecuritySession">The Connection Level Security Session that decrypted this message.</param> public void LowLevel_ParseLabelledStream(Stream stream, byte[] intermediateBuffer, HttpClientConnection httpClientConnection, SecuritySession connectionLevelSecuritySession) { bool directExecution = httpClientConnection.GenuineConnectionType == GenuineConnectionType.Invocation; BinaryReader binaryReader = new BinaryReader(stream); while ( binaryReader.ReadByte() == 0 ) { using (LabelledStream labelledStream = new LabelledStream(this.ITransportContext, stream, intermediateBuffer)) { if (directExecution) this.ITransportContext.IIncomingStreamHandler.HandleMessage(labelledStream, httpClientConnection.Remote, httpClientConnection.GenuineConnectionType, httpClientConnection.ConnectionName, httpClientConnection.DbgConnectionId, true, null, connectionLevelSecuritySession, null); else { GenuineChunkedStream receivedContent = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(labelledStream, receivedContent); this.ITransportContext.IIncomingStreamHandler.HandleMessage(receivedContent, httpClientConnection.Remote, httpClientConnection.GenuineConnectionType, httpClientConnection.ConnectionName, httpClientConnection.DbgConnectionId, false, null, connectionLevelSecuritySession, null); } } } } #endregion #region -- P/listener management ----------------------------------------------------------- /// <summary> /// Initiates the listening request. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="requestNextPacket">Whether to request the next packet.</param> private void LowLevel_InitiateListening(HttpClientConnection httpClientConnection, bool requestNextPacket) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; try { #if DEBUG Debug.Assert(httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent); #endif if (requestNextPacket) httpClientConnection.ListenerSequenceNo ++; // write the request header using (GenuineChunkedStream listenerStream = new GenuineChunkedStream(false)) { BinaryWriter binaryWriter = new BinaryWriter(listenerStream); HttpMessageCoder.WriteRequestHeader(binaryWriter, MessageCoder.PROTOCOL_VERSION, httpClientConnection.GenuineConnectionType, httpClientConnection.HostId, HttpPacketType.Listening, httpClientConnection.ListenerSequenceNo, httpClientConnection.ConnectionName, httpClientConnection.Remote.LocalHostUniqueIdentifier); // start the request httpClientConnection.Listener = httpClientConnection.InitializeRequest(false, httpClientConnection._keepalive); httpClientConnection.Listener.ContentLength = listenerStream.Length; this.LowLevel_InitiateHttpWebRequest(httpClientConnection.Listener, listenerStream, httpClientConnection.ListenerClosed, false, httpClientConnection.OnEndReceiving, httpClientConnection); } } catch(Exception ex) { // It's necessary to schedule connection reestablishing // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.LowLevel_InitiateListening", LogMessageType.ConnectionFailed, ex, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The LISTENER request Seq No={0} has failed. The connection will be reestablished, if possible.", httpClientConnection.ListenerSequenceNo); } this.StartReestablishingIfNecessary(httpClientConnection, ex, false); } } /// <summary> /// Finishes sending a message through the connection. /// </summary> /// <param name="httpClientConnection">The connection.</param> /// <param name="httpWebResponse">The received response.</param> public void Listener_OnEndReceiving(HttpClientConnection httpClientConnection, HttpWebResponse httpWebResponse) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; Stream inputStream = null; try { #if DEBUG Debug.Assert(httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent); #endif httpClientConnection.Remote.Renew(this._hostRenewingSpan, false); httpClientConnection.LastMessageWasReceviedAt = GenuineUtility.TickCount; httpClientConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); // process the content inputStream = httpWebResponse.GetResponseStream(); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1; GenuineChunkedStream content = null; if (writeContent) { content = new GenuineChunkedStream(false); GenuineUtility.CopyStreamToStream(inputStream, content, (int) httpWebResponse.ContentLength); } binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpClientConnectionManager.Listener_OnEndReceiving", LogMessageType.LowLevelTransport_AsyncReceivingCompleted, null, null, httpClientConnection.Remote, writeContent ? content : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.DbgConnectionId, (int) httpWebResponse.ContentLength, null, null, null, "The content has been received."); if (writeContent) inputStream = content; } if (httpClientConnection.Listener_ConnectionLevelSecurity != null) inputStream = httpClientConnection.Listener_ConnectionLevelSecurity.Decrypt(inputStream); BinaryReader binaryReader = new BinaryReader(inputStream); string serverUri; int sequenceNo; HttpPacketType httpPacketType; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadResponseHeader(binaryReader, out serverUri, out sequenceNo, out httpPacketType, out remoteHostUniqueIdentifier); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.Listener_OnEndReceiving", LogMessageType.ReceivingFinished, null, null, httpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpClientConnection.Listener_ConnectionLevelSecurity, null, httpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "A response to the listener request has been received. Server uri: {0}. Sequence no: {1}. Packet type: {2}. Content-encoding: {3}. Content-length: {4}. Protocol version: {5}. Response uri: \"{6}\". Server: \"{7}\". Status code: {8}. Status description: \"{9}\".", serverUri, sequenceNo, Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), httpWebResponse.ContentEncoding, httpWebResponse.ContentLength, httpWebResponse.ProtocolVersion, httpWebResponse.ResponseUri, httpWebResponse.Server, httpWebResponse.StatusCode, httpWebResponse.StatusDescription); } if (httpPacketType == HttpPacketType.Desynchronization) throw GenuineExceptions.Get_Channel_Desynchronization(); if (sequenceNo != httpClientConnection.ListenerSequenceNo) throw GenuineExceptions.Get_Processing_LogicError( string.Format("Impossible situation. The request stream number: {0}. The received stream number: {1}.", httpClientConnection.ListenerSequenceNo, sequenceNo) ); if (httpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent) httpClientConnection.Remote.UpdateUri(serverUri, remoteHostUniqueIdentifier); // if the remote host has asked to terminate a connection if (httpPacketType == HttpPacketType.ClosedManually || httpPacketType == HttpPacketType.Desynchronization) throw GenuineExceptions.Get_Receive_ConnectionClosed(); // fetch and process messages if (httpPacketType != HttpPacketType.ListenerTimedOut) this.LowLevel_ParseLabelledStream(inputStream, httpClientConnection.Listener_ReceiveBuffer, httpClientConnection, httpClientConnection.Listener_ConnectionLevelSecurity); GenuineUtility.CopyStreamToStream(inputStream, Stream.Null); } catch(Exception ex) { this.ConnectionFailed(httpClientConnection, false, ex, true); return ; } finally { if (inputStream != null) inputStream.Close(); httpWebResponse.Close(); } GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.Listener_OnEndReceiving_ContinueExchange), httpClientConnection, false); } private WaitCallback _listener_OnEndReceiving_ContinueExchange; /// <summary> /// The second part of the Listener_OnEndReceiving member implementation which is executed /// in the separate thread to avoid internal .NET Framework deadlock. /// </summary> /// <param name="httpClientConnectionAsObject">The connection represented as a reference to an instance of the Object class.</param> private void Listener_OnEndReceiving_ContinueExchange(object httpClientConnectionAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection httpClientConnection = (HttpClientConnection) httpClientConnectionAsObject; this.LowLevel_InitiateListening(httpClientConnection, true); } #endregion #region -- Listening ----------------------------------------------------------------------- /// <summary> /// Starts listening to the specified end point and accepting incoming connections. /// </summary> /// <param name="endPoint">The end point.</param> public override void StartListening(object endPoint) { throw new NotSupportedException(); } /// <summary> /// Stops listening to the specified end point. Does not close any connections. /// </summary> /// <param name="endPoint">The end point</param> public override void StopListening(object endPoint) { throw new NotSupportedException(); } #endregion #region -- Resource releasing -------------------------------------------------------------- /// <summary> /// Closes the specified connections to the remote host and releases acquired resources. /// </summary> /// <param name="hostInformation">Host information.</param> /// <param name="genuineConnectionType">What kind of connections will be affected by this operation.</param> /// <param name="reason">Reason of resource releasing.</param> public override void ReleaseConnections(HostInformation hostInformation, GenuineConnectionType genuineConnectionType, Exception reason) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection httpClientConnection = null; ArrayList connectionsToClose = new ArrayList(); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReleaseConnections", LogMessageType.ReleaseConnections, reason, null, hostInformation, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null, null, null, "\"{0}\" connections will be terminated.", Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null); } // TODO: 2.5.3. fix (deadlock by design), will be completely fixed in 3.0 // using (new WriterAutoLocker(this._disposeLock)) { // persistent if ( (genuineConnectionType & GenuineConnectionType.Persistent) != 0 ) lock (this._persistent.SyncRoot) { foreach (DictionaryEntry entry in this._persistent) { httpClientConnection = (HttpClientConnection) entry.Value; if (hostInformation != null && httpClientConnection.Remote != hostInformation) continue; connectionsToClose.Add(httpClientConnection); } } // close connections foreach (HttpClientConnection nextHttpClientConnection in connectionsToClose) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReleaseConnections", LogMessageType.ConnectionShuttingDown, reason, null, nextHttpClientConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, nextHttpClientConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection is being shut down manually."); } this.ConnectionFailed(nextHttpClientConnection, true, GenuineExceptions.Get_Channel_ConnectionShutDown(reason), false); if (nextHttpClientConnection.GenuineConnectionType == GenuineConnectionType.Persistent) { nextHttpClientConnection.SignalState(GenuineEventType.GeneralConnectionClosed, reason, null); } } } } /// <summary> /// Returns names of connections opened to the specified destination. /// Not all Connection Manager support this member. /// </summary> /// <param name="uri">The URI or URL of the remote host.</param> /// <returns>Names of connections opened to the specified destination.</returns> public override string[] GetConnectionNames(string uri) { lock (this._persistent.SyncRoot) { if (this._persistent.ContainsKey(uri)) { string[] result = new string[1]; result[0] = uri; return result; } } return null; } /// <summary> /// Releases all resources. /// </summary> /// <param name="reason">The reason of disposing.</param> public override void InternalDispose(Exception reason) { this.ReleaseConnections(null, GenuineConnectionType.All, reason); } #endregion #region -- Reestablishing ------------------------------------------------------------------ /// <summary> /// Starts reestablishing if it has not been started. /// </summary> /// <param name="httpClientConnection">The HTTP client connection.</param> /// <param name="exception">The reason of the connection failure.</param> /// <param name="sender">A flag indicating the role of the connection.</param> public void StartReestablishingIfNecessary(HttpClientConnection httpClientConnection, Exception exception, bool sender) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpClientConnection.ReconnectionContainer reconnectionContainer = sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; lock (reconnectionContainer.SyncLock) { if (! reconnectionContainer.IsReconnectionStarted) { // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.StartReestablishingIfNecessary", LogMessageType.ConnectionReestablishing, exception, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Reconnection is being started."); } reconnectionContainer.IsReconnectionStarted = true; reconnectionContainer.ReconnectionStartedAt = GenuineUtility.TickCount; FailedHttpRequest failedHttpRequest = new FailedHttpRequest(); failedHttpRequest.HttpClientConnection = httpClientConnection; failedHttpRequest.Exception = exception; failedHttpRequest.Sender = sender; GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.ReestablishFailedConnection), failedHttpRequest, true); } else { // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.Debugging, "HttpClientConnectionManager.StartReestablishingIfNecessary", LogMessageType.ConnectionReestablishing, exception, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Reconnection is already in progress."); } reconnectionContainer.RequestFailed = true; } } } /// <summary> /// Resets the reestablishing flag. /// </summary> /// <param name="httpClientConnection">The HTTP client connection.</param> /// <param name="sender">A flag indicating the role of the connection.</param> public void ReestablishingCompleted(HttpClientConnection httpClientConnection, bool sender) { HttpClientConnection.ReconnectionContainer reconnectionContainer = sender ? httpClientConnection.SenderReconnectionLock : httpClientConnection.ListenerReconnectionLock; reconnectionContainer.IsReconnectionStarted = false; } #endregion } }
using System; using System.Text; using Assets.Sources.Scripts.UI.Common; namespace Memoria.Assets { public sealed class DialogLabelFilter { public static String PhrasePreOpcodeSymbol(UILabel label, Char[] text, ref Single additionalWidth) { DialogLabelFilter filter = new DialogLabelFilter(label, text, additionalWidth); try { filter.PhrasePreOpcodeSymbol(); return filter._sb.ToString(); } finally { additionalWidth = filter._additionalWidth; } } private readonly Char[] _chars; private readonly StringBuilder _sb; private readonly UILabel _label; private Single _additionalWidth; private Single _currentWidth; public DialogLabelFilter(UILabel label, Char[] chars, Single additionalWidth) { _label = label; _chars = chars; _additionalWidth = additionalWidth; _sb = new StringBuilder(chars.Length); } public void PhrasePreOpcodeSymbol() { for (Int32 index = 0; index < _chars.Length; index++) { Char ch = _chars[index]; if (ch == '\n') { if (_currentWidth > _additionalWidth) _additionalWidth = _currentWidth; _currentWidth = 0f; _sb.Append(ch); continue; } Int32 left = _chars.Length - index; FFIXTextTag tag = FFIXTextTag.TryRead(_chars, ref index, ref left); if (tag != null) { index--; ProcessMemoriaTag(tag, ref index); } else if (ch == '[' && (index + 6 <= _chars.Length)) { ProcessOriginalTag(ref index); } else { _sb.Append(ch); } } } private void ProcessMemoriaTag(FFIXTextTag tag, ref Int32 index) { switch (tag.Code) { case FFIXTextTagCode.Icon: OnIcon(tag.Param[0]); break; case FFIXTextTagCode.Mobile: OnMobileIcon(tag.Param[0]); break; case FFIXTextTagCode.Zidane: OnCharacterName(0); break; case FFIXTextTagCode.Vivi: OnCharacterName(1); break; case FFIXTextTagCode.Dagger: OnCharacterName(2); break; case FFIXTextTagCode.Steiner: OnCharacterName(3); break; case FFIXTextTagCode.Fraya: OnCharacterName(4); break; case FFIXTextTagCode.Quina: OnCharacterName(5); break; case FFIXTextTagCode.Eiko: OnCharacterName(6); break; case FFIXTextTagCode.Amarant: OnCharacterName(7); break; case FFIXTextTagCode.Party: OnPartyMemberName(tag.Param[0] - 1); break; case FFIXTextTagCode.Variable: OnVariable(tag.Param[0]); break; case FFIXTextTagCode.DialogX: OnMessageX(tag.Param[0]); break; case FFIXTextTagCode.DialogF: OnMessageFeed(tag.Param[0]); break; default: StringBuilder sb; if (NGUIText.ForceShowButton || !FF9StateSystem.MobilePlatform) sb = _sb; else sb = new StringBuilder(16); if (DialogBoxConstructor.KeepKeyIcon(sb, tag.Code) || DialogBoxConstructor.KeepKeyExIcon(sb, tag)) return; _sb.Append(tag); break; } } private void ProcessOriginalTag(ref Int32 index) { Int32 num2 = index; String text3 = new String(_chars, index, 5); if (text3 == "[" + NGUIText.IconVar) { Int32 oneParameterFromTag = NGUIText.GetOneParameterFromTag(_chars, index, ref num2); OnIcon(oneParameterFromTag); } else if (text3 == "[" + NGUIText.CustomButtonIcon || text3 == "[" + NGUIText.ButtonIcon || text3 == "[" + NGUIText.JoyStickButtonIcon || text3 == "[" + NGUIText.KeyboardButtonIcon) { num2 = Array.IndexOf(_chars, ']', index + 4); String text5 = new String(_chars, index + 6, num2 - index - 6); if (!FF9StateSystem.MobilePlatform || NGUIText.ForceShowButton) { _sb.Append(text3); _sb.Append("="); _sb.Append(text5); _sb.Append("] "); } } else if (text3 == "[" + NGUIText.MobileIcon) { Int32 oneParameterFromTag2 = NGUIText.GetOneParameterFromTag(_chars, index, ref num2); OnMobileIcon(oneParameterFromTag2); } else if (NGUIText.nameKeywordList.Contains(text3.Remove(0, 1))) { String a = text3.Remove(0, 1); num2 = Array.IndexOf(_chars, ']', index + 4); if (a == NGUIText.Zidane) { OnCharacterName(0); } else if (a == NGUIText.Vivi) { OnCharacterName(1); } else if (a == NGUIText.Dagger) { OnCharacterName(2); } else if (a == NGUIText.Steiner) { OnCharacterName(3); } else if (a == NGUIText.Fraya) { OnCharacterName(4); } else if (a == NGUIText.Quina) { OnCharacterName(5); } else if (a == NGUIText.Eiko) { OnCharacterName(6); } else if (a == NGUIText.Amarant) { OnCharacterName(7); } else if (a == NGUIText.Party1) { OnPartyMemberName(0); } else if (a == NGUIText.Party2) { OnPartyMemberName(1); } else if (a == NGUIText.Party3) { OnPartyMemberName(2); } else if (a == NGUIText.Party4) { OnPartyMemberName(3); } } else if (text3 == "[" + NGUIText.NumberVar) { Int32 num4 = 0; Int32 oneParameterFromTag3 = NGUIText.GetOneParameterFromTag(_chars, index, ref num4); num2 = Array.IndexOf(_chars, ']', index + 4); OnVariable(oneParameterFromTag3); } else if (text3 == "[" + NGUIText.MessageTab) { Int32 oneParameterFromTag4 = NGUIText.GetOneParameterFromTag(_chars, index, ref num2); OnMessageX(oneParameterFromTag4); } else if (text3 == "[" + NGUIText.MessageFeed) { Int32 oneParameterFromTag5 = NGUIText.GetOneParameterFromTag(_chars, index, ref num2); OnMessageFeed(oneParameterFromTag5); } else if (text3 == "[" + NGUIText.SpacingY) { _label.spacingY = NGUIText.GetOneParameterFromTag(_chars, index, ref num2); } if (num2 == index) { _sb.Append(_chars[index]); } else if (num2 != -1) { index = num2; } else { index = _chars.Length; } } private void OnMessageFeed(Int32 oneParameterFromTag5) { _currentWidth += oneParameterFromTag5 * 3; _sb.Append("[FEED="); _sb.Append(oneParameterFromTag5); _sb.Append(']'); } private void OnMessageX(Int32 oneParameterFromTag4) { _currentWidth += oneParameterFromTag4 * 3; _sb.Append("[XTAB="); _sb.Append(oneParameterFromTag4); _sb.Append(']'); } private void OnVariable(Int32 oneParameterFromTag3) { Int32 num5 = PersistenSingleton<EventEngine>.Instance.eTb.gMesValue[oneParameterFromTag3]; _sb.Append(num5.ToString()); _currentWidth += NGUIText.GetTextWidthFromFF9Font(_label, num5.ToString()); } private void OnCharacterName(Int32 index) { _sb.Append(FF9StateSystem.Common.FF9.player[index].name); } private void OnPartyMemberName(Int32 index) { String name = FF9StateSystem.Common.FF9.party.member[index].name; _sb.Append(name); _currentWidth += NGUIText.GetTextWidthFromFF9Font(_label, name); } private void OnMobileIcon(Int32 oneParameterFromTag2) { DialogBoxConstructor.KeepMobileIcon(_sb, oneParameterFromTag2); _currentWidth += FF9UIDataTool.GetIconSize(oneParameterFromTag2).x; } private void OnIcon(Int32 oneParameterFromTag) { String text4; Boolean flag = true; Int32 num3 = oneParameterFromTag; switch (num3) { case 34: text4 = "[sub]0[/sub]"; break; case 35: text4 = "[sub]1[/sub]"; break; case 36: case 37: case 38: IL_D2: switch (num3) { case 159: text4 = "[sup]" + Localization.Get("Miss") + "[/sup]"; break; case 160: text4 = "[sup]" + Localization.Get("Death") + "[/sup]"; break; case 161: text4 = "[sup]" + Localization.Get("Guard") + "[/sup]"; break; case 162: text4 = "[B880E0][sup]" + Localization.Get("Critical") + "[/sup][C8C8C8]"; break; case 163: text4 = "[sup]MP[/sup]"; break; default: if (num3 == 173) { text4 = "9"; } else { if (num3 == 174) { text4 = "/"; } else { if (num3 == 45) { text4 = "[sub]/[/sub]"; } else { text4 = String.Concat("[ICON", "=", oneParameterFromTag, "] "); flag = false; } } } break; } break; case 39: text4 = "[sub]5[/sub]"; break; default: goto IL_D2; } _sb.Append(text4); if (flag) { _currentWidth += NGUIText.GetTextWidthFromFF9Font(_label, FF9TextTool.RemoveOpCode(text4)); } else { _currentWidth += FF9UIDataTool.GetIconSize(oneParameterFromTag).x; } } } }
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /* Original license and copyright from file copied from https://github.com/AArnott/Nerdbank.Streams/blob/d656899be26d4d7c72c11c9232b4952c64a89bcb/src/Nerdbank.Streams/Sequence%601.cs * Copyright (c) Andrew Arnott. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. */ using System; using System.Buffers; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Nerdbank.Streams { /// <summary> /// Manages a sequence of elements, readily castable as a <see cref="ReadOnlySequence{T}"/>. /// </summary> /// <typeparam name="T">The type of element stored by the sequence.</typeparam> /// <remarks> /// Instance members are not thread-safe. /// </remarks> [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] internal class Sequence<T> : IBufferWriter<T>, IDisposable { private static readonly int DefaultLengthFromArrayPool = 1 + (4095 / Marshal.SizeOf<T>()); private readonly Stack<SequenceSegment> segmentPool = new Stack<SequenceSegment>(); private readonly MemoryPool<T> memoryPool; private readonly ArrayPool<T> arrayPool; private SequenceSegment first; private SequenceSegment last; /// <summary> /// Initializes a new instance of the <see cref="Sequence{T}"/> class /// that uses a private <see cref="ArrayPool{T}"/> for recycling arrays. /// </summary> public Sequence() : this(ArrayPool<T>.Create()) { } /// <summary> /// Initializes a new instance of the <see cref="Sequence{T}"/> class. /// </summary> /// <param name="memoryPool">The pool to use for recycling backing arrays.</param> public Sequence(MemoryPool<T> memoryPool) { Requires.NotNull(memoryPool, nameof(memoryPool)); this.memoryPool = memoryPool; } /// <summary> /// Initializes a new instance of the <see cref="Sequence{T}"/> class. /// </summary> /// <param name="arrayPool">The pool to use for recycling backing arrays.</param> public Sequence(ArrayPool<T> arrayPool) { Requires.NotNull(arrayPool, nameof(arrayPool)); this.arrayPool = arrayPool; } /// <summary> /// Gets or sets the minimum length for any array allocated as a segment in the sequence. /// Any non-positive value allows the pool to determine the length of the array. /// </summary> /// <value>The default value is 0.</value> /// <remarks> /// <para> /// Each time <see cref="GetSpan(int)"/> or <see cref="GetMemory(int)"/> is called, /// previously allocated memory is used if it is large enough to satisfy the length demand. /// If new memory must be allocated, the argument to one of these methods typically dictate /// the length of array to allocate. When the caller uses very small values (just enough for its immediate need) /// but the high level scenario can predict that a large amount of memory will be ultimately required, /// it can be advisable to set this property to a value such that just a few larger arrays are allocated /// instead of many small ones. /// </para> /// <para> /// The <see cref="MemoryPool{T}"/> in use may itself have a minimum array length as well, /// in which case the higher of the two minimums dictate the minimum array size that will be allocated. /// </para> /// </remarks> public int MinimumSpanLength { get; set; } = 0; /// <summary> /// Gets this sequence expressed as a <see cref="ReadOnlySequence{T}"/>. /// </summary> /// <returns>A read only sequence representing the data in this object.</returns> public ReadOnlySequence<T> AsReadOnlySequence => this; /// <summary> /// Gets the length of the sequence. /// </summary> public long Length => this.AsReadOnlySequence.Length; /// <summary> /// Gets the value to display in a debugger datatip. /// </summary> private string DebuggerDisplay => $"Length: {this.AsReadOnlySequence.Length}"; /// <summary> /// Expresses this sequence as a <see cref="ReadOnlySequence{T}"/>. /// </summary> /// <param name="sequence">The sequence to convert.</param> public static implicit operator ReadOnlySequence<T>(Sequence<T> sequence) { return sequence.first != null ? new ReadOnlySequence<T>(sequence.first, sequence.first.Start, sequence.last, sequence.last.End) : ReadOnlySequence<T>.Empty; } /// <summary> /// Removes all elements from the sequence from its beginning to the specified position, /// considering that data to have been fully processed. /// </summary> /// <param name="position"> /// The position of the first element that has not yet been processed. /// This is typically <see cref="ReadOnlySequence{T}.End"/> after reading all elements from that instance. /// </param> public void AdvanceTo(SequencePosition position) { var firstSegment = (SequenceSegment)position.GetObject(); int firstIndex = position.GetInteger(); // Before making any mutations, confirm that the block specified belongs to this sequence. var current = this.first; while (current != firstSegment && current != null) { current = current.Next; } Requires.Argument(current != null, nameof(position), "Position does not represent a valid position in this sequence."); // Also confirm that the position is not a prior position in the block. Requires.Argument(firstIndex >= current.Start, nameof(position), "Position must not be earlier than current position."); // Now repeat the loop, performing the mutations. current = this.first; while (current != firstSegment) { current = this.RecycleAndGetNext(current); } firstSegment.AdvanceTo(firstIndex); if (firstSegment.Length == 0) { firstSegment = this.RecycleAndGetNext(firstSegment); } this.first = firstSegment; if (this.first == null) { this.last = null; } } /// <summary> /// Advances the sequence to include the specified number of elements initialized into memory /// returned by a prior call to <see cref="GetMemory(int)"/>. /// </summary> /// <param name="count">The number of elements written into memory.</param> public void Advance(int count) { SequenceSegment last = this.last; Verify.Operation(last != null, "Cannot advance before acquiring memory."); last.Advance(count); } /// <summary> /// Gets writable memory that can be initialized and added to the sequence via a subsequent call to <see cref="Advance(int)"/>. /// </summary> /// <param name="sizeHint">The size of the memory required, or 0 to just get a convenient (non-empty) buffer.</param> /// <returns>The requested memory.</returns> public Memory<T> GetMemory(int sizeHint) => this.GetSegment(sizeHint).RemainingMemory; /// <summary> /// Gets writable memory that can be initialized and added to the sequence via a subsequent call to <see cref="Advance(int)"/>. /// </summary> /// <param name="sizeHint">The size of the memory required, or 0 to just get a convenient (non-empty) buffer.</param> /// <returns>The requested memory.</returns> public Span<T> GetSpan(int sizeHint) => this.GetSegment(sizeHint).RemainingSpan; /// <summary> /// Clears the entire sequence, recycles associated memory into pools, /// and resets this instance for reuse. /// This invalidates any <see cref="ReadOnlySequence{T}"/> previously produced by this instance. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public void Dispose() => this.Reset(); /// <summary> /// Clears the entire sequence and recycles associated memory into pools. /// This invalidates any <see cref="ReadOnlySequence{T}"/> previously produced by this instance. /// </summary> public void Reset() { var current = this.first; while (current != null) { current = this.RecycleAndGetNext(current); } this.first = this.last = null; } private SequenceSegment GetSegment(int sizeHint) { Requires.Range(sizeHint >= 0, nameof(sizeHint)); int? minBufferSize = null; if (sizeHint == 0) { if (this.last == null || this.last.WritableBytes == 0) { // We're going to need more memory. Take whatever size the pool wants to give us. minBufferSize = -1; } } else { sizeHint = Math.Max(this.MinimumSpanLength, sizeHint); if (this.last == null || this.last.WritableBytes < sizeHint) { minBufferSize = sizeHint; } } if (minBufferSize.HasValue) { var segment = this.segmentPool.Count > 0 ? this.segmentPool.Pop() : new SequenceSegment(); if (this.arrayPool != null) { segment.Assign(this.arrayPool.Rent(minBufferSize.Value == -1 ? DefaultLengthFromArrayPool : minBufferSize.Value)); } else { segment.Assign(this.memoryPool.Rent(minBufferSize.Value)); } this.Append(segment); } return this.last; } private void Append(SequenceSegment segment) { if (this.last == null) { this.first = this.last = segment; } else { if (this.last.Length > 0) { // Add a new block. this.last.SetNext(segment); } else { // The last block is completely unused. Replace it instead of appending to it. var current = this.first; if (this.first != this.last) { while (current.Next != this.last) { current = current.Next; } } else { this.first = segment; } current.SetNext(segment); this.RecycleAndGetNext(this.last); } this.last = segment; } } private SequenceSegment RecycleAndGetNext(SequenceSegment segment) { var recycledSegment = segment; segment = segment.Next; recycledSegment.ResetMemory(this.arrayPool); this.segmentPool.Push(recycledSegment); return segment; } private class SequenceSegment : ReadOnlySequenceSegment<T> { /// <summary> /// A value indicating whether the element may contain references (and thus must be cleared). /// </summary> private static readonly bool MayContainReferences = !typeof(T).GetTypeInfo().IsPrimitive; /// <summary> /// Gets the backing array, when using an <see cref="ArrayPool{T}"/> instead of a <see cref="MemoryPool{T}"/>. /// </summary> private T[] array; /// <summary> /// Gets the position within <see cref="ReadOnlySequenceSegment{T}.Memory"/> where the data starts. /// </summary> /// <remarks>This may be nonzero as a result of calling <see cref="Sequence{T}.AdvanceTo(SequencePosition)"/>.</remarks> internal int Start { get; private set; } /// <summary> /// Gets the position within <see cref="ReadOnlySequenceSegment{T}.Memory"/> where the data ends. /// </summary> internal int End { get; private set; } /// <summary> /// Gets the tail of memory that has not yet been committed. /// </summary> internal Memory<T> RemainingMemory => this.AvailableMemory.Slice(this.End); /// <summary> /// Gets the tail of memory that has not yet been committed. /// </summary> internal Span<T> RemainingSpan => this.AvailableMemory.Span.Slice(this.End); /// <summary> /// Gets the tracker for the underlying array for this segment, which can be used to recycle the array when we're disposed of. /// Will be <c>null</c> if using an array pool, in which case the memory is held by <see cref="array"/>. /// </summary> internal IMemoryOwner<T> MemoryOwner { get; private set; } /// <summary> /// Gets the full memory owned by the <see cref="MemoryOwner"/>. /// </summary> internal Memory<T> AvailableMemory => this.array ?? this.MemoryOwner?.Memory ?? default; /// <summary> /// Gets the number of elements that are committed in this segment. /// </summary> internal int Length => this.End - this.Start; /// <summary> /// Gets the amount of writable bytes in this segment. /// It is the amount of bytes between <see cref="Length"/> and <see cref="End"/>. /// </summary> internal int WritableBytes => this.AvailableMemory.Length - this.End; /// <summary> /// Gets or sets the next segment in the singly linked list of segments. /// </summary> internal new SequenceSegment Next { get => (SequenceSegment)base.Next; set => base.Next = value; } /// <summary> /// Assigns this (recyclable) segment a new area in memory. /// </summary> /// <param name="memoryOwner">The memory and a means to recycle it.</param> internal void Assign(IMemoryOwner<T> memoryOwner) { this.MemoryOwner = memoryOwner; this.Memory = memoryOwner.Memory; } /// <summary> /// Assigns this (recyclable) segment a new area in memory. /// </summary> /// <param name="array">An array drawn from an <see cref="ArrayPool{T}"/>.</param> internal void Assign(T[] array) { this.array = array; this.Memory = array; } /// <summary> /// Clears all fields in preparation to recycle this instance. /// </summary> internal void ResetMemory(ArrayPool<T> arrayPool) { this.ClearReferences(this.Start, this.End); this.Memory = default; this.Next = null; this.RunningIndex = 0; this.Start = 0; this.End = 0; if (this.array != null) { arrayPool.Return(this.array); this.array = null; } else { this.MemoryOwner?.Dispose(); this.MemoryOwner = null; } } /// <summary> /// Adds a new segment after this one. /// </summary> /// <param name="segment">The next segment in the linked list.</param> internal void SetNext(SequenceSegment segment) { Debug.Assert(segment != null, "Null not allowed."); this.Next = segment; segment.RunningIndex = this.RunningIndex + this.Start + this.Length; // When setting Memory, we start with index 0 instead of this.Start because // the first segment has an explicit index set anyway, // and we don't want to double-count it here. this.Memory = this.AvailableMemory.Slice(0, this.Start + this.Length); } /// <summary> /// Commits more elements as written in this segment. /// </summary> /// <param name="count">The number of elements written.</param> internal void Advance(int count) { Requires.Range(count >= 0 && this.End + count <= this.Memory.Length, nameof(count)); this.End += count; } /// <summary> /// Removes some elements from the start of this segment. /// </summary> /// <param name="offset">The number of elements to ignore from the start of the underlying array.</param> internal void AdvanceTo(int offset) { Debug.Assert(offset >= this.Start, "Trying to rewind."); this.ClearReferences(this.Start, offset - this.Start); this.Start = offset; } private void ClearReferences(int startIndex, int length) { // Clear the array to allow the objects to be GC'd. // Reference types need to be cleared. Value types can be structs with reference type members too, so clear everything. if (MayContainReferences) { this.AvailableMemory.Span.Slice(startIndex, length).Clear(); } } } } internal static class Requires { /// <summary> /// Throws an <see cref="ArgumentOutOfRangeException"/> if a condition does not evaluate to true. /// </summary> [DebuggerStepThrough] public static void Range(bool condition, string parameterName, string message = null) { if (!condition) { FailRange(parameterName, message); } } /// <summary> /// Throws an <see cref="ArgumentOutOfRangeException"/> if a condition does not evaluate to true. /// </summary> /// <returns>Nothing. This method always throws.</returns> [DebuggerStepThrough] public static Exception FailRange(string parameterName, string message = null) { if (string.IsNullOrEmpty(message)) { throw new ArgumentOutOfRangeException(parameterName); } else { throw new ArgumentOutOfRangeException(parameterName, message); } } /// <summary> /// Throws an exception if the specified parameter's value is null. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> /// <param name="value">The value of the argument.</param> /// <param name="parameterName">The name of the parameter to include in any thrown exception.</param> /// <returns>The value of the parameter.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is <c>null</c>.</exception> [DebuggerStepThrough] public static T NotNull<T>(T value, string parameterName) where T : class // ensures value-types aren't passed to a null checking method { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } /// <summary> /// Throws an ArgumentException if a condition does not evaluate to true. /// </summary> [DebuggerStepThrough] public static void Argument(bool condition, string parameterName, string message) { if (!condition) { throw new ArgumentException(message, parameterName); } } /// <summary> /// Throws an ArgumentException if a condition does not evaluate to true. /// </summary> [DebuggerStepThrough] public static void Argument(bool condition, string parameterName, string message, object arg1) { if (!condition) { throw new ArgumentException(String.Format(message, arg1), parameterName); } } /// <summary> /// Throws an ArgumentException if a condition does not evaluate to true. /// </summary> [DebuggerStepThrough] public static void Argument(bool condition, string parameterName, string message, object arg1, object arg2) { if (!condition) { throw new ArgumentException(String.Format(message, arg1, arg2), parameterName); } } /// <summary> /// Throws an ArgumentException if a condition does not evaluate to true. /// </summary> [DebuggerStepThrough] public static void Argument(bool condition, string parameterName, string message, params object[] args) { if (!condition) { throw new ArgumentException(String.Format(message, args), parameterName); } } } /// <summary> /// Common runtime checks that throw exceptions upon failure. /// </summary> internal static partial class Verify { /// <summary> /// Throws an <see cref="InvalidOperationException"/> if a condition is false. /// </summary> [DebuggerStepThrough] internal static void Operation(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } } }
namespace Gu.Wpf.UiAutomation.UiTests.Elements { using System.Linq; using NUnit.Framework; public class DataGridTests { private const string ExeFileName = "WpfApplication.exe"; [OneTimeTearDown] public void OneTimeTearDown() { Application.KillLaunched(ExeFileName); } [Test] public void Find() { using var app = Application.AttachOrLaunch(ExeFileName, "SingleDataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(); Assert.IsInstanceOf<DataGrid>(UiElement.FromAutomationElement(dataGrid.AutomationElement)); } [TestCase("DataGrid")] [TestCase("DataGridEmpty")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("ReadOnlyDataGrid")] [TestCase("ReadonlyColumnsDataGrid")] public void RowCellsCount(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); for (var i = 0; i < dataGrid.Rows.Count; i++) { var row = dataGrid.Rows[i]; Assert.AreEqual(2, row.Cells.Count); Assert.AreEqual(2, dataGrid.Row(0).Cells.Count); } } [TestCase("DataGrid", 4)] [TestCase("DataGridEmpty", 1)] [TestCase("DataGrid10", 11)] [TestCase("DataGridNoHeaders", 4)] [TestCase("ReadOnlyDataGrid", 3)] [TestCase("ReadonlyColumnsDataGrid", 4)] public void RowCount(string name, int expectedRows) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(expectedRows, dataGrid.RowCount); } [TestCase("DataGrid", new[] { "1, Item 1", "2, Item 2", "3, Item 3", ", " })] [TestCase("DataGridEmpty", new[] { ", " })] [TestCase("DataGrid10", new[] { "1, Item 1", "2, Item 2", "3, Item 3", "4, Item 4", "5, Item 5", "6, Item 6", "7, Item 7", "8, Item 8", "9, Item 9", "10, Item 10", ", " })] [TestCase("DataGridNoHeaders", new[] { "1, Item 1", "2, Item 2", "3, Item 3", ", " })] [TestCase("ReadOnlyDataGrid", new[] { "1, Item 1", "2, Item 2", "3, Item 3" })] [TestCase("ReadonlyColumnsDataGrid", new[] { "1, Item 1", "2, Item 2", "3, Item 3", ", " })] public void RowsCells(string name, string[] expected) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); CollectionAssert.AreEqual(expected, dataGrid.Rows.Select(x => string.Join(", ", x.Cells.Select(c => c.Value)))); } [TestCase("DataGrid", new[] { "Row 1", "Row 2", "Row 3", "" })] [TestCase("DataGridEmpty", new[] { "" })] [TestCase("DataGrid10", new[] { "Row 1", "Row 2", "Row 3", "Row 4", "Row 5", "Row 6", "Row 7", "Row 8", "Row 9", "Row 10", "" })] [TestCase("ReadOnlyDataGrid", new[] { "Row 1", "Row 2", "Row 3" })] [TestCase("ReadonlyColumnsDataGrid", new[] { "Row 1", "Row 2", "Row 3", "" })] public void RowsHeaders(string name, string[] expected) { if (name == "DataGrid10" && WindowsVersion.IsAzureDevops()) { Assert.Inconclusive("Not sure why this fails on devops."); } using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); CollectionAssert.AreEqual(expected, dataGrid.Rows.Select(x => x.Header.Text)); } [TestCase("DataGrid", 0, "Row 1")] [TestCase("DataGrid", 1, "Row 2")] [TestCase("DataGrid10", 0, "Row 1")] [TestCase("DataGrid10", 9, "Row 10")] [TestCase("ReadOnlyDataGrid", 0, "Row 1")] [TestCase("ReadonlyColumnsDataGrid", 0, "Row 1")] public void RowHeader(string name, int index, string expected) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(expected, dataGrid.RowHeader(index).Text); } [TestCase("DataGrid", false)] [TestCase("DataGridEmpty", false)] [TestCase("DataGrid10", false)] [TestCase("DataGridNoHeaders", false)] [TestCase("TemplateColumnDataGrid", false)] [TestCase("ReadOnlyDataGrid", true)] [TestCase("ReadonlyColumnsDataGrid", false)] public void IsReadOnly(string name, bool expected) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(expected, dataGrid.IsReadOnly); } [TestCase("DataGrid")] [TestCase("DataGridEmpty")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("ReadOnlyDataGrid")] [TestCase("ReadonlyColumnsDataGrid")] public void ColumnCount(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(2, dataGrid.ColumnCount); } [TestCase("DataGrid", 2)] [TestCase("DataGridEmpty", 2)] [TestCase("DataGrid10", 2)] [TestCase("DataGridNoHeaders", 0)] [TestCase("ReadOnlyDataGrid", 2)] [TestCase("ReadonlyColumnsDataGrid", 2)] public void ColumnHeadersCount(string name, int expected) { // We want launch here to repro a bug. using var app = Application.Launch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(expected, dataGrid.ColumnHeaders.Count); } [TestCase("DataGrid", 2)] [TestCase("DataGridEmpty", 2)] [TestCase("DataGrid10", 2)] [TestCase("DataGridNoHeaders", 0)] [TestCase("ReadOnlyDataGrid", 2)] [TestCase("ReadonlyColumnsDataGrid", 2)] public void ColumnHeaders(string name, int expectedCount) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual(expectedCount, dataGrid.ColumnHeaders.Count); if (expectedCount == 0) { return; } Assert.AreEqual("IntValue", dataGrid.ColumnHeaders[0].Text); Assert.AreEqual("StringValue", dataGrid.ColumnHeaders[1].Text); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("ReadOnlyDataGrid")] [TestCase("ReadonlyColumnsDataGrid")] [TestCase("TemplateColumnDataGrid")] public void RowIndexer(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual("1", dataGrid.Row(0).Cells[0].Value); Assert.AreEqual("Item 1", dataGrid.Row(0).Cells[1].Value); Assert.AreEqual("2", dataGrid.Row(1).Cells[0].Value); Assert.AreEqual("Item 2", dataGrid.Row(1).Cells[1].Value); Assert.AreEqual("3", dataGrid.Row(2).Cells[0].Value); Assert.AreEqual("Item 3", dataGrid.Row(2).Cells[1].Value); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] [TestCase("ReadOnlyDataGrid")] [TestCase("ReadonlyColumnsDataGrid")] [TestCase("TemplateColumnDataGrid")] public void CellIndexer(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); Assert.AreEqual("1", dataGrid[0, 0].Value); Assert.AreEqual("Item 1", dataGrid[0, 1].Value); Assert.AreEqual("2", dataGrid[1, 0].Value); Assert.AreEqual("Item 2", dataGrid[1, 1].Value); Assert.AreEqual("3", dataGrid[2, 0].Value); Assert.AreEqual("Item 3", dataGrid[2, 1].Value); } [TestCase("DataGrid", 0, 1)] [TestCase("DataGrid", 1, 2)] [TestCase("DataGrid", 2, 0)] [TestCase("DataGrid10", 0, 9)] [TestCase("DataGrid10", 1, 2)] [TestCase("DataGrid10", 9, 0)] [TestCase("DataGridNoHeaders", 0, 1)] [TestCase("DataGridNoHeaders", 1, 0)] [TestCase("DataGridNoHeaders", 2, 0)] public void SelectRowByIndex(string name, int index1, int index2) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var selectedRow = dataGrid.Select(index1); Assert.AreEqual($"{index1 + 1}", selectedRow.Cells[0].Value); Assert.AreEqual($"Item {index1 + 1}", selectedRow.Cells[1].Value); selectedRow = (DataGridRow)dataGrid.SelectedItem; Assert.AreEqual($"{index1 + 1}", selectedRow.Cells[0].Value); Assert.AreEqual($"Item {index1 + 1}", selectedRow.Cells[1].Value); selectedRow = dataGrid.Select(index2); Assert.AreEqual($"{index2 + 1}", selectedRow.Cells[0].Value); Assert.AreEqual($"Item {index2 + 1}", selectedRow.Cells[1].Value); selectedRow = (DataGridRow)dataGrid.SelectedItem; Assert.AreEqual($"{index2 + 1}", selectedRow.Cells[0].Value); Assert.AreEqual($"Item {index2 + 1}", selectedRow.Cells[1].Value); } [TestCase("SelectCellDataGrid", 2, 0)] public void SelectCellByIndex(string name, int index1, int index2) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var selectedCell = dataGrid.Select(index1, index2); Assert.AreEqual($"{index1 + 1}", selectedCell.Value); selectedCell = (DataGridCell)dataGrid.SelectedItem; Assert.AreEqual($"{index1 + 1}", selectedCell.Value); } [TestCase("DataGrid")] [TestCase("DataGrid10")] [TestCase("DataGridNoHeaders")] public void SelectByTextTest(string name) { using var app = Application.AttachOrLaunch(ExeFileName, "DataGridWindow"); var window = app.MainWindow; var dataGrid = window.FindDataGrid(name); var selectedRow = dataGrid.Select(1, "Item 2"); Assert.AreEqual("2", selectedRow.Cells[0].Value); Assert.AreEqual("Item 2", selectedRow.Cells[1].Value); selectedRow = (DataGridRow)dataGrid.SelectedItem; Assert.AreEqual("2", selectedRow.Cells[0].Value); Assert.AreEqual("Item 2", selectedRow.Cells[1].Value); selectedRow = dataGrid.Select(1, "Item 3"); Assert.AreEqual("3", selectedRow.Cells[0].Value); Assert.AreEqual("Item 3", selectedRow.Cells[1].Value); selectedRow = (DataGridRow)dataGrid.SelectedItem; Assert.AreEqual("3", selectedRow.Cells[0].Value); Assert.AreEqual("Item 3", selectedRow.Cells[1].Value); } } }
using System; using System.Collections; using System.Net.Http; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Text; using Newtonsoft.Json; using System.IO; using HttpUtility = System.Web.HttpUtility; using System.Threading; namespace Refit { class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null) { return new RequestBuilderImplementation(interfaceType, settings); } } class RequestBuilderImplementation : IRequestBuilder { readonly Type targetType; readonly Dictionary<string, RestMethodInfo> interfaceHttpMethods; readonly RefitSettings settings; public RequestBuilderImplementation(Type targetInterface, RefitSettings refitSettings = null) { settings = refitSettings ?? new RefitSettings(); if (targetInterface == null || !targetInterface.IsInterface()) { throw new ArgumentException("targetInterface must be an Interface"); } targetType = targetInterface; interfaceHttpMethods = targetInterface.GetMethods() .SelectMany(x => { var attrs = x.GetCustomAttributes(true); var hasHttpMethod = attrs.OfType<HttpMethodAttribute>().Any(); if (!hasHttpMethod) return Enumerable.Empty<RestMethodInfo>(); return EnumerableEx.Return(new RestMethodInfo(targetInterface, x, settings)); }) .ToDictionary(k => k.Name, v => v); } public IEnumerable<string> InterfaceHttpMethods { get { return interfaceHttpMethods.Keys; } } Func<object[], HttpRequestMessage> buildRequestFactoryForMethod(string methodName, string basePath, bool paramsContainsCancellationToken) { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; return paramList => { // make sure we strip out any cancelation tokens if (paramsContainsCancellationToken) { paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray(); } var ret = new HttpRequestMessage { Method = restMethod.HttpMethod, }; // set up multipart content MultipartFormDataContent multiPartContent = null; if (restMethod.IsMultipart) { multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); ret.Content = multiPartContent; } string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new Dictionary<string, string>(); var headersToAdd = new Dictionary<string, string>(restMethod.Headers); for(int i=0; i < paramList.Length; i++) { // if part of REST resource URL, substitute it in if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]), RegexOptions.IgnoreCase); continue; } // if marked as body, add to content if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) { var streamParam = paramList[i] as Stream; var stringParam = paramList[i] as string; var httpContentParam = paramList[i] as HttpContent; if (httpContentParam != null) { ret.Content = httpContentParam; } else if (streamParam != null) { ret.Content = new StreamContent(streamParam); } else if (stringParam != null) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i])); break; case BodySerializationMethod.Json: ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json"); break; } } continue; } // if header, add to request headers if (restMethod.HeaderParameterMap.ContainsKey(i)) { headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null ? paramList[i].ToString() : null; continue; } // ignore nulls if (paramList[i] == null) continue; // for anything that fell through to here, if this is not // a multipart method, add the parameter to the query string if (!restMethod.IsMultipart) { queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]); continue; } // we are in a multipart method, add the part to the content // the parameter name should be either the attachment name or the parameter name (as fallback) string itemName; if (! restMethod.AttachmentNameMap.TryGetValue(i, out itemName)) itemName = restMethod.QueryParameterMap[i]; addMultipartItem(multiPartContent, itemName, paramList[i]); } // NB: We defer setting headers until the body has been // added so any custom content headers don't get left out. foreach (var header in headersToAdd) { setHeader(ret, header.Key, header.Value); } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach(var kvp in queryParamsToAdd) { query.Add(kvp.Key, kvp.Value); } if (query.HasKeys()) { var pairs = query.Keys.Cast<string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x])); uri.Query = String.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }; } static void setHeader(HttpRequestMessage request, string name, string value) { // Clear any existing version of this header that might be set, because // we want to allow removal/redefinition of headers. // We also don't want to double up content headers which may have been // set for us automatically. // NB: We have to enumerate the header names to check existence because // Contains throws if it's the wrong header type for the collection. if (request.Headers.Any(x => x.Key == name)) { request.Headers.Remove(name); } if (request.Content != null && request.Content.Headers.Any(x => x.Key == name)) { request.Content.Headers.Remove(name); } if (value == null) return; var added = request.Headers.TryAddWithoutValidation(name, value); // Don't even bother trying to add the header as a content header // if we just added it to the other collection. if (!added && request.Content != null) { request.Content.Headers.TryAddWithoutValidation(name, value); } } void addMultipartItem(MultipartFormDataContent multiPartContent, string itemName, object itemValue) { var streamValue = itemValue as Stream; var stringValue = itemValue as String; var byteArrayValue = itemValue as byte[]; if (streamValue != null) { var streamContent = new StreamContent(streamValue); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = itemName }; multiPartContent.Add(streamContent); return; } if (stringValue != null) { multiPartContent.Add(new StringContent(stringValue), itemName); return; } #if !NETFX_CORE var fileInfoValue = itemValue as FileInfo; if (fileInfoValue != null) { var fileContent = new StreamContent(fileInfoValue.OpenRead()); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileInfoValue.Name }; multiPartContent.Add(fileContent); return; } #endif if (byteArrayValue != null) { var fileContent = new ByteArrayContent(byteArrayValue); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = itemName }; multiPartContent.Add(fileContent); return; } throw new ArgumentException(string.Format("Unexpected parameter type in a Multipart request. Parameter {0} is of type {1}, whereas allowed types are String, Stream, FileInfo, and Byte array", itemName, itemValue.GetType().Name), "itemValue"); } public Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName) { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; if (restMethod.ReturnType == typeof(Task)) { return buildVoidTaskFuncForMethod(restMethod); } else if (restMethod.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) { // NB: This jacked up reflection code is here because it's // difficult to upcast Task<object> to an arbitrary T, especially // if you need to AOT everything, so we need to reflectively // invoke buildTaskFuncForMethod. var taskFuncMi = GetType().GetMethod("buildTaskFuncForMethod", BindingFlags.NonPublic | BindingFlags.Instance); var taskFunc = (MulticastDelegate)taskFuncMi.MakeGenericMethod(restMethod.SerializedReturnType) .Invoke(this, new[] { restMethod }); return (client, args) => { return taskFunc.DynamicInvoke(new object[] { client, args } ); }; } else { // Same deal var rxFuncMi = GetType().GetMethod("buildRxFuncForMethod", BindingFlags.NonPublic | BindingFlags.Instance); var rxFunc = (MulticastDelegate)rxFuncMi.MakeGenericMethod(restMethod.SerializedReturnType) .Invoke(this, new[] { restMethod }); return (client, args) => { return rxFunc.DynamicInvoke(new object[] { client, args }); }; } } Func<HttpClient, object[], Task> buildVoidTaskFuncForMethod(RestMethodInfo restMethod) { return async (client, paramList) => { var factory = buildRequestFactoryForMethod(restMethod.Name, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null); var rq = factory(paramList); var ct = CancellationToken.None; if (restMethod.CancellationToken != null) { ct = paramList.OfType<CancellationToken>().FirstOrDefault(); } using (var resp = await client.SendAsync(rq, ct).ConfigureAwait(false)) { if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(resp, settings).ConfigureAwait(false); } } }; } Func<HttpClient, object[], Task<T>> buildTaskFuncForMethod<T>(RestMethodInfo restMethod) { var ret = buildCancellableTaskFuncForMethod<T>(restMethod); return (client, paramList) => { if(restMethod.CancellationToken != null) { return ret(client, paramList.OfType<CancellationToken>().FirstOrDefault(), paramList); } return ret(client, CancellationToken.None, paramList); }; } Func<HttpClient, CancellationToken, object[], Task<T>> buildCancellableTaskFuncForMethod<T>(RestMethodInfo restMethod) { return async (client, ct, paramList) => { var factory = buildRequestFactoryForMethod(restMethod.Name, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null); var rq = factory(paramList); var resp = await client.SendAsync(rq, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (restMethod.SerializedReturnType == typeof(HttpResponseMessage)) { // NB: This double-casting manual-boxing hate crime is the only way to make // this work without a 'class' generic constraint. It could blow up at runtime // and would be A Bad Idea if we hadn't already vetted the return type. return (T)(object)resp; } if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(resp, restMethod.RefitSettings).ConfigureAwait(false); } if (restMethod.SerializedReturnType == typeof(HttpContent)) { return (T)(object)resp.Content; } var ms = new MemoryStream(); using (var fromStream = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false)) { await fromStream.CopyToAsync(ms, 4096, ct).ConfigureAwait(false); } var bytes = ms.ToArray(); var content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (restMethod.SerializedReturnType == typeof(string)) { return (T)(object)content; } return JsonConvert.DeserializeObject<T>(content, settings.JsonSerializerSettings); }; } Func<HttpClient, object[], IObservable<T>> buildRxFuncForMethod<T>(RestMethodInfo restMethod) { var taskFunc = buildCancellableTaskFuncForMethod<T>(restMethod); return (client, paramList) => { return new TaskToObservable<T>(ct => { var methodCt = CancellationToken.None; if (restMethod.CancellationToken != null) { methodCt = paramList.OfType<CancellationToken>().FirstOrDefault(); } // link the two var cts = CancellationTokenSource.CreateLinkedTokenSource(methodCt, ct); return taskFunc(client, cts.Token, paramList); }); }; } class TaskToObservable<T> : IObservable<T> { Func<CancellationToken, Task<T>> taskFactory; public TaskToObservable(Func<CancellationToken, Task<T>> taskFactory) { this.taskFactory = taskFactory; } public IDisposable Subscribe(IObserver<T> observer) { var cts = new CancellationTokenSource(); taskFactory(cts.Token).ContinueWith(t => { if (cts.IsCancellationRequested) return; if (t.Exception != null) { observer.OnError(t.Exception.InnerExceptions.First()); return; } try { observer.OnNext(t.Result); } catch (Exception ex) { observer.OnError(ex); } observer.OnCompleted(); }); return new AnonymousDisposable(cts.Cancel); } } } sealed class AnonymousDisposable : IDisposable { readonly Action block; public AnonymousDisposable(Action block) { this.block = block; } public void Dispose() { block(); } } public class RestMethodInfo { public string Name { get; set; } public Type Type { get; set; } public MethodInfo MethodInfo { get; set; } public HttpMethod HttpMethod { get; set; } public string RelativePath { get; set; } public bool IsMultipart { get; private set; } public Dictionary<int, string> ParameterMap { get; set; } public ParameterInfo CancellationToken { get; set; } public Dictionary<string, string> Headers { get; set; } public Dictionary<int, string> HeaderParameterMap { get; set; } public Tuple<BodySerializationMethod, int> BodyParameterInfo { get; set; } public Dictionary<int, string> QueryParameterMap { get; set; } public Dictionary<int, string> AttachmentNameMap { get; set; } public Dictionary<int, ParameterInfo> ParameterInfoMap { get; set; } public Type ReturnType { get; set; } public Type SerializedReturnType { get; set; } public RefitSettings RefitSettings { get; set; } static readonly Regex parameterRegex = new Regex(@"{(.*?)}"); static readonly HttpMethod patchMethod = new HttpMethod("PATCH"); public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null) { RefitSettings = refitSettings ?? new RefitSettings(); Type = targetInterface; Name = methodInfo.Name; MethodInfo = methodInfo; var hma = methodInfo.GetCustomAttributes(true) .OfType<HttpMethodAttribute>() .First(); HttpMethod = hma.Method; RelativePath = hma.Path; IsMultipart = methodInfo.GetCustomAttributes(true) .OfType<MultipartAttribute>() .Any(); verifyUrlPathIsSane(RelativePath); determineReturnTypeInfo(methodInfo); // Exclude cancellation token parameters from this list var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList(); ParameterInfoMap = parameterList .Select((parameter, index) => new { index, parameter }) .ToDictionary(x => x.index, x => x.parameter); ParameterMap = buildParameterMap(RelativePath, parameterList); BodyParameterInfo = findBodyParameter(parameterList, IsMultipart, hma.Method); Headers = parseHeaders(methodInfo); HeaderParameterMap = buildHeaderParameterMap(parameterList); // get names for multipart attachments AttachmentNameMap = new Dictionary<int, string>(); if (IsMultipart) { for (int i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i)) { continue; } var attachmentName = getAttachmentNameForParameter(parameterList[i]); if (attachmentName == null) continue; AttachmentNameMap[i] = attachmentName; } } QueryParameterMap = new Dictionary<int, string>(); for (int i=0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item2 == i) || AttachmentNameMap.ContainsKey(i)) { continue; } QueryParameterMap[i] = getUrlNameForParameter(parameterList[i]); } var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList(); if(ctParams.Count > 1) { throw new ArgumentException("Argument list can only contain a single CancellationToken"); } CancellationToken = ctParams.FirstOrDefault(); } void verifyUrlPathIsSane(string relativePath) { if (relativePath == "") return; if (!relativePath.StartsWith("/")) { goto bogusPath; } var parts = relativePath.Split('/'); if (parts.Length == 0) { goto bogusPath; } return; bogusPath: throw new ArgumentException("URL path must be of the form '/foo/bar/baz'"); } Dictionary<int, string> buildParameterMap(string relativePath, List<ParameterInfo> parameterInfo) { var ret = new Dictionary<int, string>(); var parameterizedParts = relativePath.Split('/', '?') .SelectMany(x => parameterRegex.Matches(x).Cast<Match>()) .ToList(); if (parameterizedParts.Count == 0) { return ret; } var paramValidationDict = parameterInfo.ToDictionary(k => getUrlNameForParameter(k).ToLowerInvariant(), v => v); foreach (var match in parameterizedParts) { var name = match.Groups[1].Value.ToLowerInvariant(); if (!paramValidationDict.ContainsKey(name)) { throw new ArgumentException(String.Format("URL has parameter {0}, but no method parameter matches", name)); } ret.Add(parameterInfo.IndexOf(paramValidationDict[name]), name); } return ret; } string getUrlNameForParameter(ParameterInfo paramInfo) { var aliasAttr = paramInfo.GetCustomAttributes(true) .OfType<AliasAsAttribute>() .FirstOrDefault(); return aliasAttr != null ? aliasAttr.Name : paramInfo.Name; } string getAttachmentNameForParameter(ParameterInfo paramInfo) { var nameAttr = paramInfo.GetCustomAttributes(true) .OfType<AttachmentNameAttribute>() .FirstOrDefault(); return nameAttr != null ? nameAttr.Name : null; } Tuple<BodySerializationMethod, int> findBodyParameter(List<ParameterInfo> parameterList, bool isMultipart, HttpMethod method) { // The body parameter is found using the following logic / order of precedence: // 1) [Body] attribute // 2) POST/PUT/PATCH: Reference type other than string // 3) If there are two reference types other than string, without the body attribute, throw var bodyParams = parameterList .Select(x => new { Parameter = x, BodyAttribute = x.GetCustomAttributes(true).OfType<BodyAttribute>().FirstOrDefault() }) .Where(x => x.BodyAttribute != null) .ToList(); if (isMultipart && bodyParams.Count > 0) { throw new ArgumentException("Multipart requests may not contain a Body parameter"); } if (bodyParams.Count > 1) { throw new ArgumentException("Only one parameter can be a Body parameter"); } // #1, body attribute wins if (bodyParams.Count == 1) { var ret = bodyParams[0]; return Tuple.Create(ret.BodyAttribute.SerializationMethod, parameterList.IndexOf(ret.Parameter)); } // Not in post/put/patch? bail if (!method.Equals(HttpMethod.Post) && !method.Equals(HttpMethod.Put) && !method.Equals(patchMethod)) { return null; } // see if we're a post/put/patch var refParams = parameterList.Where(pi => !pi.ParameterType.GetTypeInfo().IsValueType && pi.ParameterType != typeof(string)).ToList(); // Check for rule #3 if (refParams.Count > 1) { throw new ArgumentException("Multiple complex types found. Specify one parameter as the body using BodyAttribute"); } if (refParams.Count == 1) { return Tuple.Create(BodySerializationMethod.Json, parameterList.IndexOf(refParams[0])); } return null; } Dictionary<string, string> parseHeaders(MethodInfo methodInfo) { var ret = new Dictionary<string, string>(); var declaringTypeAttributes = methodInfo.DeclaringType != null ? methodInfo.DeclaringType.GetCustomAttributes(true) : new Attribute[0]; // Headers set on the declaring type have to come first, // so headers set on the method can replace them. Switching // the order here will break stuff. var headers = declaringTypeAttributes.Concat(methodInfo.GetCustomAttributes(true)) .OfType<HeadersAttribute>() .SelectMany(ha => ha.Headers); foreach (var header in headers) { if (string.IsNullOrWhiteSpace(header)) continue; // NB: Silverlight doesn't have an overload for String.Split() // with a count parameter, but header values can contain // ':' so we have to re-join all but the first part to get the // value. var parts = header.Split(':'); ret[parts[0].Trim()] = parts.Length > 1 ? String.Join(":", parts.Skip(1)).Trim() : null; } return ret; } Dictionary<int, string> buildHeaderParameterMap(List<ParameterInfo> parameterList) { var ret = new Dictionary<int, string>(); for (int i = 0; i < parameterList.Count; i++) { var header = parameterList[i].GetCustomAttributes(true) .OfType<HeaderAttribute>() .Select(ha => ha.Header) .FirstOrDefault(); if (!string.IsNullOrWhiteSpace(header)) { ret[i] = header.Trim(); } } return ret; } void determineReturnTypeInfo(MethodInfo methodInfo) { if (methodInfo.ReturnType.IsGenericType() == false) { if (methodInfo.ReturnType != typeof (Task)) { goto bogusMethod; } ReturnType = methodInfo.ReturnType; SerializedReturnType = typeof(void); return; } var genericType = methodInfo.ReturnType.GetGenericTypeDefinition(); if (genericType != typeof(Task<>) && genericType != typeof(IObservable<>)) { goto bogusMethod; } ReturnType = methodInfo.ReturnType; SerializedReturnType = methodInfo.ReturnType.GetGenericArguments()[0]; return; bogusMethod: throw new ArgumentException("All REST Methods must return either Task<T> or IObservable<T>"); } } class FormValueDictionary : Dictionary<string, string> { static readonly Dictionary<Type, PropertyInfo[]> propertyCache = new Dictionary<Type, PropertyInfo[]>(); public FormValueDictionary(object source) { if (source == null) return; var dictionary = source as IDictionary; if (dictionary != null) { foreach (var key in dictionary.Keys) { Add(key.ToString(), string.Format("{0}", dictionary[key])); } return; } var type = source.GetType(); lock (propertyCache) { if (!propertyCache.ContainsKey(type)) { propertyCache[type] = getProperties(type); } foreach (var property in propertyCache[type]) { Add(getFieldNameForProperty(property), string.Format("{0}", property.GetValue(source, null))); } } } PropertyInfo[] getProperties(Type type) { return type.GetProperties() .Where(p => p.CanRead) .ToArray(); } string getFieldNameForProperty(PropertyInfo propertyInfo) { var aliasAttr = propertyInfo.GetCustomAttributes(true) .OfType<AliasAsAttribute>() .FirstOrDefault(); return aliasAttr != null ? aliasAttr.Name : propertyInfo.Name; } } class AuthenticatedHttpClientHandler : DelegatingHandler { readonly Func<Task<string>> getToken; public AuthenticatedHttpClientHandler(Func<Task<string>> getToken, HttpMessageHandler innerHandler = null) : base(innerHandler ?? new HttpClientHandler()) { if (getToken == null) throw new ArgumentNullException("getToken"); this.getToken = getToken; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // See if the request has an authorize header var auth = request.Headers.Authorization; if (auth != null) { var token = await getToken().ConfigureAwait(false); request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token); } return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } } }
// Copyright (c) 2013 SharpYaml - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ------------------------------------------------------------------------------- // SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet // published with the following license: // ------------------------------------------------------------------------------- // // Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace SharpYaml.Serialization.Descriptors { /// <summary> /// Default implementation of a <see cref="ITypeDescriptor"/>. /// </summary> public class ObjectDescriptor : ITypeDescriptor { protected static readonly string SystemCollectionsNamespace = typeof(int).Namespace; private readonly static object[] EmptyObjectArray = new object[0]; private readonly Type type; private readonly List<IMemberDescriptor> members; private readonly Dictionary<string, IMemberDescriptor> mapMembers; private readonly bool emitDefaultValues; private YamlStyle style; private bool isSorted; /// <summary> /// Initializes a new instance of the <see cref="ObjectDescriptor" /> class. /// </summary> /// <param name="attributeRegistry">The attribute registry.</param> /// <param name="type">The type.</param> /// <param name="emitDefaultValues"></param> /// <exception cref="System.ArgumentNullException">type</exception> /// <exception cref="YamlException">Failed to get ObjectDescriptor for type [{0}]. The member [{1}] cannot be registered as a member with the same name is already registered [{2}].DoFormat(type.FullName, member, existingMember)</exception> public ObjectDescriptor(IAttributeRegistry attributeRegistry, Type type, bool emitDefaultValues) { if (attributeRegistry == null) throw new ArgumentNullException("attributeRegistry"); if (type == null) throw new ArgumentNullException("type"); this.emitDefaultValues = emitDefaultValues; this.AttributeRegistry = attributeRegistry; this.type = type; var styleAttribute = AttributeRegistry.GetAttribute<YamlStyleAttribute>(type); this.style = styleAttribute != null ? styleAttribute.Style : YamlStyle.Any; this.IsCompilerGenerated = AttributeRegistry.GetAttribute<CompilerGeneratedAttribute>(type) != null; members = PrepareMembers(); // If no members found, we don't need to build a dictionary map if (members.Count <= 0) return; mapMembers = new Dictionary<string, IMemberDescriptor>(members.Count); foreach (var member in members) { IMemberDescriptor existingMember; if (mapMembers.TryGetValue(member.Name, out existingMember)) { throw new YamlException("Failed to get ObjectDescriptor for type [{0}]. The member [{1}] cannot be registered as a member with the same name is already registered [{2}]".DoFormat(type.FullName, member, existingMember)); } mapMembers.Add(member.Name, member); } } protected IAttributeRegistry AttributeRegistry { get; private set; } public Type Type { get { return type; } } public IEnumerable<IMemberDescriptor> Members { get { return members; } } public int Count { get { return members.Count; } } public bool HasMembers { get { return members.Count > 0; } } public YamlStyle Style { get { return style; } } /// <summary> /// Sorts the members of this instance with the specified instance. /// </summary> /// <param name="keyComparer">The key comparer.</param> public void SortMembers(IComparer<object> keyComparer) { if (keyComparer != null && !isSorted) { members.Sort(keyComparer.Compare); isSorted = true; } } public IMemberDescriptor this[string name] { get { if (mapMembers == null) throw new KeyNotFoundException(name); IMemberDescriptor member; mapMembers.TryGetValue(name, out member); return member; } } public bool IsCompilerGenerated { get; private set; } public bool Contains(string memberName) { return mapMembers != null && mapMembers.ContainsKey(memberName); } protected virtual List<IMemberDescriptor> PrepareMembers() { // Add all public properties with a readable get method var memberList = (from propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) where propertyInfo.CanRead && propertyInfo.GetGetMethod(false) != null && propertyInfo.GetIndexParameters().Length == 0 select new PropertyDescriptor(propertyInfo) into member where PrepareMember(member) select member).Cast<IMemberDescriptor>().ToList(); // Add all public fields memberList.AddRange((from fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public) where fieldInfo.IsPublic select new FieldDescriptor(fieldInfo) into member where PrepareMember(member) select member)); return memberList; } protected virtual bool PrepareMember(MemberDescriptorBase member) { var memberType = member.Type; // Remove all SyncRoot from members if (member is PropertyDescriptor && member.Name == "SyncRoot" && (member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace)) { return false; } // If the member has a set, this is a conventional assign method if (member.HasSet) { member.SerializeMemberMode = SerializeMemberMode.Assign; } else { // Else we cannot only assign its content if it is a class member.SerializeMemberMode = (memberType != typeof(string) && memberType.IsClass) || memberType.IsInterface || type.IsAnonymous() ? SerializeMemberMode.Content : SerializeMemberMode.Never; } // Member is not displayed if there is a YamlIgnore attribute on it if (AttributeRegistry.GetAttribute<YamlIgnoreAttribute>(member.MemberInfo, false) != null) return false; // Gets the style var styleAttribute = AttributeRegistry.GetAttribute<YamlStyleAttribute>(member.MemberInfo); member.Style = styleAttribute != null ? styleAttribute.Style : YamlStyle.Any; // Handle member attribute var memberAttribute = AttributeRegistry.GetAttribute<YamlMemberAttribute>(member.MemberInfo, false); if (memberAttribute != null) { if (!member.HasSet) { if (memberAttribute.SerializeMethod == SerializeMemberMode.Assign || (memberType.IsValueType && member.SerializeMemberMode == SerializeMemberMode.Content)) throw new ArgumentException("{0} {1} is not writeable by {2}.".DoFormat(memberType.FullName, member.Name, memberAttribute.SerializeMethod.ToString())); } if (memberAttribute.SerializeMethod != SerializeMemberMode.Default) { member.SerializeMemberMode = memberAttribute.SerializeMethod; } member.Order = memberAttribute.Order; } if (member.SerializeMemberMode == SerializeMemberMode.Binary) { if (!memberType.IsArray) throw new InvalidOperationException("{0} {1} of {2} is not an array. Can not be serialized as binary." .DoFormat(memberType.FullName, member.Name, type.FullName)); if (!memberType.GetElementType().IsPureValueType()) throw new InvalidOperationException("{0} is not a pure ValueType. {1} {2} of {3} can not serialize as binary.".DoFormat(memberType.GetElementType(), memberType.FullName, member.Name, type.FullName)); } // If this member cannot be serialized, remove it from the list if (member.SerializeMemberMode == SerializeMemberMode.Never) { return false; } // ShouldSerialize // YamlSerializeAttribute(Never) => false // ShouldSerializeSomeProperty => call it // DefaultValueAttribute(default) => compare to it // otherwise => true var shouldSerialize = type.GetMethod("ShouldSerialize" + member.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null) member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray); var defaultValueAttribute = AttributeRegistry.GetAttribute<DefaultValueAttribute>(member.MemberInfo); if (defaultValueAttribute != null && member.ShouldSerialize == null && !emitDefaultValues) { object defaultValue = defaultValueAttribute.Value; Type defaultType = defaultValue == null ? null : defaultValue.GetType(); if (defaultType.IsNumeric() && defaultType != memberType) defaultValue = memberType.CastToNumericType(defaultValue); member.ShouldSerialize = obj => !TypeExtensions.AreEqual(defaultValue, member.Get(obj)); } if (member.ShouldSerialize == null) member.ShouldSerialize = obj => true; if (memberAttribute != null && !string.IsNullOrEmpty(memberAttribute.Name)) { member.Name = memberAttribute.Name; } return true; } public override string ToString() { return type.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; namespace Microsoft.SqlServer.Server { // Utilities for manipulating smi-related metadata. // // Since this class is built on top of SMI, SMI should not have a dependency on this class // // These are all based off of knowing the clr type of the value // as an ExtendedClrTypeCode enum for rapid access. internal class MetaDataUtilsSmi { internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1); internal const long InvalidMaxLength = -2; // Standard type inference map to get SqlDbType when all you know is the value's type (typecode) // This map's index is off by one (add one to typecode locate correct entry) in order // to support ExtendedSqlDbType.Invalid // This array is meant to be accessed from InferSqlDbTypeFromTypeCode. private static readonly SqlDbType[] s_extendedTypeCodeToSqlDbTypeMap = { InvalidSqlDbType, // Invalid extended type code SqlDbType.Bit, // System.Boolean SqlDbType.TinyInt, // System.Byte SqlDbType.NVarChar, // System.Char SqlDbType.DateTime, // System.DateTime InvalidSqlDbType, // System.DBNull doesn't have an inferable SqlDbType SqlDbType.Decimal, // System.Decimal SqlDbType.Float, // System.Double InvalidSqlDbType, // null reference doesn't have an inferable SqlDbType SqlDbType.SmallInt, // System.Int16 SqlDbType.Int, // System.Int32 SqlDbType.BigInt, // System.Int64 InvalidSqlDbType, // System.SByte doesn't have an inferable SqlDbType SqlDbType.Real, // System.Single SqlDbType.NVarChar, // System.String InvalidSqlDbType, // System.UInt16 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt32 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt64 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.Object doesn't have an inferable SqlDbType SqlDbType.VarBinary, // System.ByteArray SqlDbType.NVarChar, // System.CharArray SqlDbType.UniqueIdentifier, // System.Guid SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBinary SqlDbType.Bit, // System.Data.SqlTypes.SqlBoolean SqlDbType.TinyInt, // System.Data.SqlTypes.SqlByte SqlDbType.DateTime, // System.Data.SqlTypes.SqlDateTime SqlDbType.Float, // System.Data.SqlTypes.SqlDouble SqlDbType.UniqueIdentifier, // System.Data.SqlTypes.SqlGuid SqlDbType.SmallInt, // System.Data.SqlTypes.SqlInt16 SqlDbType.Int, // System.Data.SqlTypes.SqlInt32 SqlDbType.BigInt, // System.Data.SqlTypes.SqlInt64 SqlDbType.Money, // System.Data.SqlTypes.SqlMoney SqlDbType.Decimal, // System.Data.SqlTypes.SqlDecimal SqlDbType.Real, // System.Data.SqlTypes.SqlSingle SqlDbType.NVarChar, // System.Data.SqlTypes.SqlString SqlDbType.NVarChar, // System.Data.SqlTypes.SqlChars SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBytes SqlDbType.Xml, // System.Data.SqlTypes.SqlXml SqlDbType.Structured, // System.Collections.IEnumerable, used for TVPs it must return IDataRecord SqlDbType.Structured, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> SqlDbType.Time, // System.TimeSpan SqlDbType.DateTimeOffset, // System.DateTimeOffset }; // Dictionary to map from clr type object to ExtendedClrTypeCodeMap enum. // This dictionary should only be accessed from DetermineExtendedTypeCode and class ctor for setup. private static readonly Dictionary<Type, ExtendedClrTypeCode> s_typeToExtendedTypeCodeMap = CreateTypeToExtendedTypeCodeMap(); private static Dictionary<Type, ExtendedClrTypeCode> CreateTypeToExtendedTypeCodeMap() { int Count = 42; // Keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating! var dictionary = new Dictionary<Type, ExtendedClrTypeCode>(Count) { { typeof(bool), ExtendedClrTypeCode.Boolean }, { typeof(byte), ExtendedClrTypeCode.Byte }, { typeof(char), ExtendedClrTypeCode.Char }, { typeof(DateTime), ExtendedClrTypeCode.DateTime }, { typeof(DBNull), ExtendedClrTypeCode.DBNull }, { typeof(decimal), ExtendedClrTypeCode.Decimal }, { typeof(double), ExtendedClrTypeCode.Double }, // lookup code will handle special-case null-ref, omitting the addition of ExtendedTypeCode.Empty { typeof(short), ExtendedClrTypeCode.Int16 }, { typeof(int), ExtendedClrTypeCode.Int32 }, { typeof(long), ExtendedClrTypeCode.Int64 }, { typeof(sbyte), ExtendedClrTypeCode.SByte }, { typeof(float), ExtendedClrTypeCode.Single }, { typeof(string), ExtendedClrTypeCode.String }, { typeof(ushort), ExtendedClrTypeCode.UInt16 }, { typeof(uint), ExtendedClrTypeCode.UInt32 }, { typeof(ulong), ExtendedClrTypeCode.UInt64 }, { typeof(object), ExtendedClrTypeCode.Object }, { typeof(byte[]), ExtendedClrTypeCode.ByteArray }, { typeof(char[]), ExtendedClrTypeCode.CharArray }, { typeof(Guid), ExtendedClrTypeCode.Guid }, { typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary }, { typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean }, { typeof(SqlByte), ExtendedClrTypeCode.SqlByte }, { typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime }, { typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble }, { typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid }, { typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16 }, { typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32 }, { typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64 }, { typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney }, { typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal }, { typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle }, { typeof(SqlString), ExtendedClrTypeCode.SqlString }, { typeof(SqlChars), ExtendedClrTypeCode.SqlChars }, { typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes }, { typeof(SqlXml), ExtendedClrTypeCode.SqlXml }, { typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader }, { typeof(IEnumerable<SqlDataRecord>), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord }, { typeof(TimeSpan), ExtendedClrTypeCode.TimeSpan }, { typeof(DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset }, }; Debug.Assert(dictionary.Count == Count); return dictionary; } internal static bool IsCharOrXmlType(SqlDbType type) { return IsUnicodeType(type) || IsAnsiType(type) || type == SqlDbType.Xml; } internal static bool IsUnicodeType(SqlDbType type) { return type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText; } internal static bool IsAnsiType(SqlDbType type) { return type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text; } internal static bool IsBinaryType(SqlDbType type) { return type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Image; } // Does this type use PLP format values? internal static bool IsPlpFormat(SmiMetaData metaData) { return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator || metaData.SqlDbType == SqlDbType.Image || metaData.SqlDbType == SqlDbType.NText || metaData.SqlDbType == SqlDbType.Text || metaData.SqlDbType == SqlDbType.Udt; } // If we know we're only going to use this object to assign to a specific SqlDbType back end object, // we can save some processing time by only checking for the few valid types that can be assigned to the dbType. // This assumes a switch statement over SqlDbType is faster than getting the ClrTypeCode and iterating over a // series of if statements, or using a hash table. // NOTE: the form of these checks is taking advantage of a feature of the JIT compiler that is supposed to // optimize checks of the form '(xxx.GetType() == typeof( YYY ))'. The JIT team claimed at one point that // this doesn't even instantiate a Type instance, thus was the fastest method for individual comparisons. // Given that there's a known SqlDbType, thus a minimal number of comparisons, it's likely this is faster // than the other approaches considered (both GetType().GetTypeCode() switch and hash table using Type keys // must instantiate a Type object. The typecode switch also degenerates into a large if-then-else for // all but the primitive clr types. internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType( SqlDbType dbType, bool isMultiValued, object value ) { ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid; // fast-track null, which is valid for all types if (null == value) { extendedCode = ExtendedClrTypeCode.Empty; } else if (DBNull.Value == value) { extendedCode = ExtendedClrTypeCode.DBNull; } else { switch (dbType) { case SqlDbType.BigInt: if (value.GetType() == typeof(Int64)) extendedCode = ExtendedClrTypeCode.Int64; else if (value.GetType() == typeof(SqlInt64)) extendedCode = ExtendedClrTypeCode.SqlInt64; break; case SqlDbType.Binary: case SqlDbType.VarBinary: case SqlDbType.Image: case SqlDbType.Timestamp: if (value.GetType() == typeof(byte[])) extendedCode = ExtendedClrTypeCode.ByteArray; else if (value.GetType() == typeof(SqlBinary)) extendedCode = ExtendedClrTypeCode.SqlBinary; else if (value.GetType() == typeof(SqlBytes)) extendedCode = ExtendedClrTypeCode.SqlBytes; else if (value.GetType() == typeof(StreamDataFeed)) extendedCode = ExtendedClrTypeCode.Stream; break; case SqlDbType.Bit: if (value.GetType() == typeof(bool)) extendedCode = ExtendedClrTypeCode.Boolean; else if (value.GetType() == typeof(SqlBoolean)) extendedCode = ExtendedClrTypeCode.SqlBoolean; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.VarChar: if (value.GetType() == typeof(string)) extendedCode = ExtendedClrTypeCode.String; if (value.GetType() == typeof(TextDataFeed)) extendedCode = ExtendedClrTypeCode.TextReader; else if (value.GetType() == typeof(SqlString)) extendedCode = ExtendedClrTypeCode.SqlString; else if (value.GetType() == typeof(char[])) extendedCode = ExtendedClrTypeCode.CharArray; else if (value.GetType() == typeof(SqlChars)) extendedCode = ExtendedClrTypeCode.SqlChars; else if (value.GetType() == typeof(char)) extendedCode = ExtendedClrTypeCode.Char; break; case SqlDbType.Date: case SqlDbType.DateTime2: case SqlDbType.DateTime: case SqlDbType.SmallDateTime: if (value.GetType() == typeof(DateTime)) extendedCode = ExtendedClrTypeCode.DateTime; else if (value.GetType() == typeof(SqlDateTime)) extendedCode = ExtendedClrTypeCode.SqlDateTime; break; case SqlDbType.Decimal: if (value.GetType() == typeof(Decimal)) extendedCode = ExtendedClrTypeCode.Decimal; else if (value.GetType() == typeof(SqlDecimal)) extendedCode = ExtendedClrTypeCode.SqlDecimal; break; case SqlDbType.Real: if (value.GetType() == typeof(Single)) extendedCode = ExtendedClrTypeCode.Single; else if (value.GetType() == typeof(SqlSingle)) extendedCode = ExtendedClrTypeCode.SqlSingle; break; case SqlDbType.Int: if (value.GetType() == typeof(Int32)) extendedCode = ExtendedClrTypeCode.Int32; else if (value.GetType() == typeof(SqlInt32)) extendedCode = ExtendedClrTypeCode.SqlInt32; break; case SqlDbType.Money: case SqlDbType.SmallMoney: if (value.GetType() == typeof(SqlMoney)) extendedCode = ExtendedClrTypeCode.SqlMoney; else if (value.GetType() == typeof(Decimal)) extendedCode = ExtendedClrTypeCode.Decimal; break; case SqlDbType.Float: if (value.GetType() == typeof(SqlDouble)) extendedCode = ExtendedClrTypeCode.SqlDouble; else if (value.GetType() == typeof(Double)) extendedCode = ExtendedClrTypeCode.Double; break; case SqlDbType.UniqueIdentifier: if (value.GetType() == typeof(SqlGuid)) extendedCode = ExtendedClrTypeCode.SqlGuid; else if (value.GetType() == typeof(Guid)) extendedCode = ExtendedClrTypeCode.Guid; break; case SqlDbType.SmallInt: if (value.GetType() == typeof(Int16)) extendedCode = ExtendedClrTypeCode.Int16; else if (value.GetType() == typeof(SqlInt16)) extendedCode = ExtendedClrTypeCode.SqlInt16; break; case SqlDbType.TinyInt: if (value.GetType() == typeof(Byte)) extendedCode = ExtendedClrTypeCode.Byte; else if (value.GetType() == typeof(SqlByte)) extendedCode = ExtendedClrTypeCode.SqlByte; break; case SqlDbType.Variant: // SqlDbType doesn't help us here, call general-purpose function extendedCode = DetermineExtendedTypeCode(value); // Some types aren't allowed for Variants but are for the general-purpose function. // Match behavior of other types and return invalid in these cases. if (ExtendedClrTypeCode.SqlXml == extendedCode) { extendedCode = ExtendedClrTypeCode.Invalid; } break; case SqlDbType.Udt: throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); case SqlDbType.Time: if (value.GetType() == typeof(TimeSpan)) extendedCode = ExtendedClrTypeCode.TimeSpan; break; case SqlDbType.DateTimeOffset: if (value.GetType() == typeof(DateTimeOffset)) extendedCode = ExtendedClrTypeCode.DateTimeOffset; break; case SqlDbType.Xml: if (value.GetType() == typeof(SqlXml)) extendedCode = ExtendedClrTypeCode.SqlXml; if (value.GetType() == typeof(XmlDataFeed)) extendedCode = ExtendedClrTypeCode.XmlReader; else if (value.GetType() == typeof(System.String)) extendedCode = ExtendedClrTypeCode.String; break; case SqlDbType.Structured: if (isMultiValued) { if (value is IEnumerable<SqlDataRecord>) { extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord; } else if (value is DbDataReader) { extendedCode = ExtendedClrTypeCode.DbDataReader; } } break; default: // Leave as invalid break; } } return extendedCode; } // Method to map from Type to ExtendedTypeCode internal static ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType) { ExtendedClrTypeCode resultCode; return s_typeToExtendedTypeCodeMap.TryGetValue(clrType, out resultCode) ? resultCode : ExtendedClrTypeCode.Invalid; } // Returns the ExtendedClrTypeCode that describes the given value internal static ExtendedClrTypeCode DetermineExtendedTypeCode(object value) { return value != null ? DetermineExtendedTypeCodeFromType(value.GetType()) : ExtendedClrTypeCode.Empty; } // returns a sqldbtype for the given type code internal static SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode) { Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!"); return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1]; } // Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to // infer types should use InferSqlDbTypeFromType_Katmai. internal static SqlDbType InferSqlDbTypeFromType(Type type) { ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type); SqlDbType returnType; if (ExtendedClrTypeCode.Invalid == typeCode) { returnType = InvalidSqlDbType; // Return invalid type so caller can generate specific error } else { returnType = InferSqlDbTypeFromTypeCode(typeCode); } return returnType; } // Inference rules changed for Katmai-or-later-only cases. Only features that are guaranteed to be // running against Katmai and don't have backward compat issues should call this code path. // example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2 // when mapping System.DateTime from DateTable or DbDataReader. DATETIME2 is better because // of greater range that can handle all DateTime values. internal static SqlDbType InferSqlDbTypeFromType_Katmai(Type type) { SqlDbType returnType = InferSqlDbTypeFromType(type); if (SqlDbType.DateTime == returnType) { returnType = SqlDbType.DateTime2; } return returnType; } internal static SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData source) { if (SqlDbType.Xml == source.SqlDbType) { return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.TypeSpecificNamePart1, source.TypeSpecificNamePart2, source.TypeSpecificNamePart3, true ); } return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, null); } // Convert SqlMetaData instance to an SmiExtendedMetaData instance. internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source) { // now map everything across to the extended metadata object string typeSpecificNamePart1 = null; string typeSpecificNamePart2 = null; string typeSpecificNamePart3 = null; if (SqlDbType.Xml == source.SqlDbType) { typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase; typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema; typeSpecificNamePart3 = source.XmlSchemaCollectionName; } else if (SqlDbType.Udt == source.SqlDbType) { throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); } return new SmiExtendedMetaData(source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.Name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3); } // compare SmiMetaData to SqlMetaData and determine if they are compatible. internal static bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd) { return firstMd.SqlDbType == secondMd.SqlDbType && firstMd.MaxLength == secondMd.MaxLength && firstMd.Precision == secondMd.Precision && firstMd.Scale == secondMd.Scale && firstMd.CompareOptions == secondMd.CompareOptions && firstMd.LocaleId == secondMd.LocaleId && firstMd.SqlDbType != SqlDbType.Structured && // SqlMetaData doesn't support Structured types !firstMd.IsMultiValued; // SqlMetaData doesn't have a "multivalued" option } // This is a modified version of SmiMetaDataFromSchemaTableRow above // Since CoreCLR doesn't have GetSchema, we need to infer the MetaData from the CLR Type alone internal static SmiExtendedMetaData SmiMetaDataFromType(string colName, Type colType) { // Determine correct SqlDbType. SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType); if (InvalidSqlDbType == colDbType) { // Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise we error out. if (typeof(object) == colType) { colDbType = SqlDbType.VarBinary; } else { throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } } // Determine metadata modifier values per type (maxlength, precision, scale, etc) long maxLength = 0; byte precision = 0; byte scale = 0; switch (colDbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.NText: case SqlDbType.Real: case SqlDbType.UniqueIdentifier: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Text: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: // These types require no metadata modifiers break; case SqlDbType.Binary: case SqlDbType.VarBinary: // source isn't specifying a size, so assume the Maximum if (SqlDbType.Binary == colDbType) { maxLength = SmiMetaData.MaxBinaryLength; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.Char: case SqlDbType.VarChar: // source isn't specifying a size, so assume the Maximum if (SqlDbType.Char == colDbType) { maxLength = SmiMetaData.MaxANSICharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.NChar: case SqlDbType.NVarChar: // source isn't specifying a size, so assume the Maximum if (SqlDbType.NChar == colDbType) { maxLength = SmiMetaData.MaxUnicodeCharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.Decimal: // Decimal requires precision and scale precision = SmiMetaData.DefaultDecimal.Precision; scale = SmiMetaData.DefaultDecimal.Scale; break; case SqlDbType.Time: case SqlDbType.DateTime2: case SqlDbType.DateTimeOffset: // requires scale scale = SmiMetaData.DefaultTime.Scale; break; case SqlDbType.Udt: case SqlDbType.Structured: default: // These types are not supported from SchemaTable throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } return new SmiExtendedMetaData( colDbType, maxLength, precision, scale, CultureInfo.CurrentCulture.LCID, SmiMetaData.GetDefaultForType(colDbType).CompareOptions, false, // no support for multi-valued columns in a TVP yet null, // no support for structured columns yet null, colName, null, null, null); } } }
#region Copyright (c) Roni Schuetz - All Rights Reserved // * --------------------------------------------------------------------- * // * Roni Schuetz * // * Copyright (c) 2008 All Rights reserved * // * * // * Shared Cache high-performance, distributed caching and * // * replicated caching system, generic in nature, but intended to * // * speeding up dynamic web and / or win applications by alleviating * // * database load. * // * * // * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) * // * * // * This library is free software; you can redistribute it and/or * // * modify it under the terms of the GNU Lesser General Public License * // * as published by the Free Software Foundation; either version 2.1 * // * of the License, or (at your option) any later version. * // * * // * This library is distributed in the hope that it will be useful, * // * but WITHOUT ANY WARRANTY; without even the implied warranty of * // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * // * Lesser General Public License for more details. * // * * // * You should have received a copy of the GNU Lesser General Public * // * License along with this library; if not, write to the Free * // * Software Foundation, Inc., 59 Temple Place, Suite 330, * // * Boston, MA 02111-1307 USA * // * * // * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. * // * --------------------------------------------------------------------- * #endregion // ************************************************************************* // // Name: TcpSocketConnectionPool.cs // // Created: 10-02-2008 SharedCache.com, rschuetz // Modified: 10-02-2008 SharedCache.com, rschuetz : Creation // Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE // ************************************************************************* using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace SharedCache.WinServiceCommon.Sockets { /// <summary> /// Represents a pool of connections for a specific server node. /// <example> /// Server: 192.168.0.1 Port: 48888 /// </example> /// </summary> internal class TcpSocketConnectionPool { private static object bulkObject = new object(); #region Property: Host private string host; /// <summary> /// Gets/sets the Host /// </summary> public string Host { [System.Diagnostics.DebuggerStepThrough] get { return this.host; } [System.Diagnostics.DebuggerStepThrough] set { this.host = value; } } #endregion #region Property: Port private int port; /// <summary> /// Gets/sets the Port /// </summary> public int Port { [System.Diagnostics.DebuggerStepThrough] get { return this.port; } [System.Diagnostics.DebuggerStepThrough] set { this.port = value; } } #endregion /// <summary>Queue of available socket connections.</summary> private Queue<SharedCacheTcpClient> availableSockets = new Queue<SharedCacheTcpClient>(); /// <summary>The maximum size of the connection pool.</summary> internal int PoolSize { get; set; } /// <summary> /// Identify if this pool is available or not /// </summary> public bool PoolAvailable { get; private set; } internal void Disable() { this.PoolAvailable = false; } internal void Enable() { this.PoolAvailable = true; } /// <summary> /// Validates this instance. /// </summary> internal void Validate() { #region Access Log #if TRACE { Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log if (this.PoolAvailable) { #region validate all open connections when they used last time for (int i = 0; i < this.availableSockets.Count; i++) { SharedCacheTcpClient client = null; lock (bulkObject) { client = this.availableSockets.Dequeue(); } TimeSpan sp = DateTime.Now.Subtract(client.LastUsed); // Console.WriteLine(@"last used: {0}m {1}s {2}ms", sp.Minutes, sp.Seconds, sp.Milliseconds); if (sp.Minutes >= 2) { client.Dispose(); } else if (client != null && !client.Connected) { // this will close the socket in case we have to much open sockets. this.PutSocket(client); } else if (client != null) { lock (bulkObject) { this.availableSockets.Enqueue(client); } } } #endregion } else { #region try to enable pool in case its disabled if (CacheUtil.Ping(this.Host)) { this.Enable(); #region Logging string msg = "Client could reconnect to host {0} and it enables this node."; #if TRACE Console.WriteLine(msg, this.Host); #endif #if DEBUG Console.WriteLine(msg, this.Host); #endif Handler.LogHandler.Fatal(string.Format(msg, this.Host)); #endregion } else { #region Logging string msg = "Client could NOT reconnect to host {0} and keeps this node disabled"; #if TRACE Console.WriteLine(msg,this.Host); #endif #if DEBUG Console.WriteLine(msg, this.Host); #endif Handler.LogHandler.Fatal(string.Format(msg, this.Host)); #endregion } #endregion } } /// <summary> /// Get an open socket from the connection pool. /// </summary> /// <returns>Socket returned from the pool or new socket /// opened.</returns> public SharedCacheTcpClient GetSocket() { #region Access Log #if TRACE { Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log SharedCacheTcpClient socket = null; bool stillCheckingSockets = false; lock (bulkObject) { if (this.availableSockets.Count > 0) { socket = this.availableSockets.Dequeue(); stillCheckingSockets = true; } } while (stillCheckingSockets) { if (socket.Connected) { TimeSpan sp = DateTime.Now.Subtract(socket.LastUsed); //TODO: read data from config file: SocketPoolTimeout if (sp.Minutes >= 2) { socket.Close(); return this.OpenSocket(); } else return socket; } else { if (socket != null) { // MAYBE we should consider to reconnect it instead to close it? socket.Close(); } } stillCheckingSockets = false; lock (bulkObject) { if (this.availableSockets.Count > 0) { socket = this.availableSockets.Dequeue(); stillCheckingSockets = true; } } } return this.OpenSocket(); } /// <summary> /// Return the given socket back to the socket pool. /// </summary> /// <param name="socket">Socket connection to return.</param> public void PutSocket(SharedCacheTcpClient socket) { #region Access Log #if TRACE { Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log //TODO: Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolMinAvailableSize // if (this.availableSockets.Count < Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolMinAvailableSize) if (this.availableSockets.Count <= this.PoolSize) // if (this.availableSockets.Count < TcpSocketConnectionPool.POOL_SIZE) { if (socket != null) { if (socket.Connected) { // Set the socket back to blocking and enqueue socket.SetBlockingMode(true); socket.LastUsed = DateTime.Now; lock (bulkObject) { this.availableSockets.Enqueue(socket); } } else { socket.Close(); } } } else { // Number of sockets is above the pool size, so just close it. socket.Close(); } } /// <summary> /// Open a new socket connection. /// </summary> /// <returns>Newly opened socket connection.</returns> private SharedCacheTcpClient OpenSocket() { #region Access Log #if TRACE { Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;"); } #endif #endregion Access Log return new SharedCacheTcpClient(this.host, this.port); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Postcard.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using HSoft.ClientManager.WCFService.Areas.HelpPage.ModelDescriptions; using HSoft.ClientManager.WCFService.Areas.HelpPage.Models; namespace HSoft.ClientManager.WCFService.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.IO; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { /// <summary> /// Static class containing the WinHttp global callback and associated routines. /// </summary> internal static class WinHttpRequestCallback { public static Interop.WinHttp.WINHTTP_STATUS_CALLBACK StaticCallbackDelegate = new Interop.WinHttp.WINHTTP_STATUS_CALLBACK(WinHttpCallback); public static void WinHttpCallback( IntPtr handle, IntPtr context, uint internetStatus, IntPtr statusInformation, uint statusInformationLength) { if (NetEventSource.IsEnabled) WinHttpTraceHelper.TraceCallbackStatus(null, handle, context, internetStatus); if (Environment.HasShutdownStarted) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Environment.HasShutdownStarted returned True"); return; } if (context == IntPtr.Zero) { return; } WinHttpRequestState state = WinHttpRequestState.FromIntPtr(context); Debug.Assert(state != null, "WinHttpCallback must have a non-null state object"); RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength); } private static void RequestCallback( IntPtr handle, WinHttpRequestState state, uint internetStatus, IntPtr statusInformation, uint statusInformationLength) { try { switch (internetStatus) { case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: OnRequestHandleClosing(state); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: OnRequestSendRequestComplete(state); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: Debug.Assert(statusInformationLength == sizeof(int)); int bytesAvailable = Marshal.ReadInt32(statusInformation); OnRequestDataAvailable(state, bytesAvailable); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE: OnRequestReadComplete(state, statusInformationLength); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: OnRequestWriteComplete(state); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: OnRequestReceiveResponseHeadersComplete(state); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT: string redirectUriString = Marshal.PtrToStringUni(statusInformation); var redirectUri = new Uri(redirectUriString); OnRequestRedirect(state, redirectUri); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: OnRequestSendingRequest(state); return; case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: Debug.Assert( statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(), "RequestCallback: statusInformationLength=" + statusInformationLength + " must be sizeof(WINHTTP_ASYNC_RESULT)=" + Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>()); var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(statusInformation); OnRequestError(state, asyncResult); return; default: return; } } catch (Exception ex) { state.SavedException = ex; if (state.RequestHandle != null) { // Since we got a fatal error processing the request callback, // we need to close the WinHttp request handle in order to // abort the currently executing WinHttp async operation. // // We must always call Dispose() against the SafeWinHttpHandle // wrapper and never close directly the raw WinHttp handle. // The SafeWinHttpHandle wrapper is thread-safe and guarantees // calling the underlying WinHttpCloseHandle() function only once. state.RequestHandle.Dispose(); } } } private static void OnRequestHandleClosing(WinHttpRequestState state) { Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null"); // This is the last notification callback that WinHTTP will send. Therefore, we can // now explicitly dispose the state object which will free its corresponding GCHandle. // This will then allow the state object to be garbage collected. state.Dispose(); } private static void OnRequestSendRequestComplete(WinHttpRequestState state) { Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null"); Debug.Assert(state.LifecycleAwaitable != null, "OnRequestSendRequestComplete: LifecycleAwaitable is null"); state.LifecycleAwaitable.SetResult(1); } private static void OnRequestDataAvailable(WinHttpRequestState state, int bytesAvailable) { Debug.Assert(state != null, "OnRequestDataAvailable: state is null"); state.LifecycleAwaitable.SetResult(bytesAvailable); } private static void OnRequestReadComplete(WinHttpRequestState state, uint bytesRead) { Debug.Assert(state != null, "OnRequestReadComplete: state is null"); // If we read to the end of the stream and we're using 'Content-Length' semantics on the response body, // then verify we read at least the number of bytes required. if (bytesRead == 0 && state.ExpectedBytesToRead.HasValue && state.CurrentBytesRead < state.ExpectedBytesToRead.Value) { state.LifecycleAwaitable.SetException(new IOException(string.Format( SR.net_http_io_read_incomplete, state.ExpectedBytesToRead.Value, state.CurrentBytesRead))); } else { state.CurrentBytesRead += (long)bytesRead; state.LifecycleAwaitable.SetResult((int)bytesRead); } } private static void OnRequestWriteComplete(WinHttpRequestState state) { Debug.Assert(state != null, "OnRequestWriteComplete: state is null"); Debug.Assert(state.TcsInternalWriteDataToRequestStream != null, "TcsInternalWriteDataToRequestStream is null"); Debug.Assert(!state.TcsInternalWriteDataToRequestStream.Task.IsCompleted, "TcsInternalWriteDataToRequestStream.Task is completed"); state.TcsInternalWriteDataToRequestStream.TrySetResult(true); } private static void OnRequestReceiveResponseHeadersComplete(WinHttpRequestState state) { Debug.Assert(state != null, "OnRequestReceiveResponseHeadersComplete: state is null"); Debug.Assert(state.LifecycleAwaitable != null, "LifecycleAwaitable is null"); state.LifecycleAwaitable.SetResult(1); } private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri) { Debug.Assert(state != null, "OnRequestRedirect: state is null"); Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null"); // If we're manually handling cookies, we need to reset them based on the new URI. if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { // Add any cookies that may have arrived with redirect response. WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state); // Reset cookie request headers based on redirectUri. WinHttpCookieContainerAdapter.ResetCookieRequestHeaders(state, redirectUri); } state.RequestMessage.RequestUri = redirectUri; // Redirection to a new uri may require a new connection through a potentially different proxy. // If so, we will need to respond to additional 407 proxy auth demands and re-attach any // proxy credentials. The ProcessResponse() method looks at the state.LastStatusCode // before attaching proxy credentials and marking the HTTP request to be re-submitted. // So we need to reset the LastStatusCode remembered. Otherwise, it will see additional 407 // responses as an indication that proxy auth failed and won't retry the HTTP request. if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired) { state.LastStatusCode = 0; } // For security reasons, we drop the server credential if it is a // NetworkCredential. But we allow credentials in a CredentialCache // since they are specifically tied to URI's. if (!(state.ServerCredentials is CredentialCache)) { state.ServerCredentials = null; } // Similarly, we need to clear any Auth headers that were added to the request manually or // through the default headers. ResetAuthRequestHeaders(state); } private static void OnRequestSendingRequest(WinHttpRequestState state) { Debug.Assert(state != null, "OnRequestSendingRequest: state is null"); Debug.Assert(state.RequestHandle != null, "OnRequestSendingRequest: state.RequestHandle is null"); if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https) { // Not SSL/TLS. return; } // Grab the channel binding token (CBT) information from the request handle and put it into // the TransportContext object. state.TransportContext.SetChannelBinding(state.RequestHandle); if (state.ServerCertificateValidationCallback != null) { IntPtr certHandle = IntPtr.Zero; uint certHandleSize = (uint)IntPtr.Size; if (!Interop.WinHttp.WinHttpQueryOption( state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_SERVER_CERT_CONTEXT, ref certHandle, ref certHandleSize)) { int lastError = Marshal.GetLastWin32Error(); if (NetEventSource.IsEnabled) NetEventSource.Error(state, $"Error getting WINHTTP_OPTION_SERVER_CERT_CONTEXT, {lastError}"); if (lastError == Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE) { // Not yet an SSL/TLS connection. This occurs while connecting thru a proxy where the // CONNECT verb hasn't yet been processed due to the proxy requiring authentication. // We need to ignore this notification. Another notification will be sent once the final // connection thru the proxy is completed. return; } throw WinHttpException.CreateExceptionUsingError(lastError, "WINHTTP_CALLBACK_STATUS_SENDING_REQUEST/WinHttpQueryOption"); } // Get any additional certificates sent from the remote server during the TLS/SSL handshake. X509Certificate2Collection remoteCertificateStore = UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(certHandle); // Create a managed wrapper around the certificate handle. Since this results in duplicating // the handle, we will close the original handle after creating the wrapper. var serverCertificate = new X509Certificate2(certHandle); Interop.Crypt32.CertFreeCertificateContext(certHandle); X509Chain chain = null; SslPolicyErrors sslPolicyErrors; bool result = false; try { WinHttpCertificateHelper.BuildChain( serverCertificate, remoteCertificateStore, state.RequestMessage.RequestUri.Host, state.CheckCertificateRevocationList, out chain, out sslPolicyErrors); result = state.ServerCertificateValidationCallback( state.RequestMessage, serverCertificate, chain, sslPolicyErrors); } catch (Exception ex) { throw WinHttpException.CreateExceptionUsingError( (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, "X509Chain.Build", ex); } finally { if (chain != null) { chain.Dispose(); } serverCertificate.Dispose(); } if (!result) { throw WinHttpException.CreateExceptionUsingError( (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, "ServerCertificateValidationCallback"); } } } private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult) { Debug.Assert(state != null, "OnRequestError: state is null"); if (NetEventSource.IsEnabled) WinHttpTraceHelper.TraceAsyncError(state, asyncResult); Exception innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)asyncResult.dwError), "WINHTTP_CALLBACK_STATUS_REQUEST_ERROR"); switch (unchecked((uint)asyncResult.dwResult.ToInt32())) { case Interop.WinHttp.API_SEND_REQUEST: state.LifecycleAwaitable.SetException(innerException); break; case Interop.WinHttp.API_RECEIVE_RESPONSE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST) { state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) { // WinHttp will automatically drop any client SSL certificates that we // have pre-set into the request handle including the NULL certificate // (which means we have no certs to send). For security reasons, we don't // allow the certificate to be re-applied. But we need to tell WinHttp // explicitly that we don't have any certificate to send. Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null"); WinHttpHandler.SetNoClientCertificate(state.RequestHandle); state.RetryRequest = true; state.LifecycleAwaitable.SetResult(0); } else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { state.LifecycleAwaitable.SetCanceled(state.CancellationToken); } else { state.LifecycleAwaitable.SetException(innerException); } break; case Interop.WinHttp.API_QUERY_DATA_AVAILABLE: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's ReadAsync() call into the TrySetCanceled(). if (NetEventSource.IsEnabled) NetEventSource.Error(state, "QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED"); state.LifecycleAwaitable.SetCanceled(); } else { state.LifecycleAwaitable.SetException( new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_READ_DATA: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's ReadAsync() call into the TrySetCanceled(). if (NetEventSource.IsEnabled) NetEventSource.Error(state, "API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); state.LifecycleAwaitable.SetCanceled(); } else { state.LifecycleAwaitable.SetException(new IOException(SR.net_http_io_read, innerException)); } break; case Interop.WinHttp.API_WRITE_DATA: if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED) { // TODO: Issue #2165. We need to pass in the cancellation token from the // user's WriteAsync() call into the TrySetCanceled(). if (NetEventSource.IsEnabled) NetEventSource.Error(state, "API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED"); state.TcsInternalWriteDataToRequestStream.TrySetCanceled(); } else { state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, innerException)); } break; default: Debug.Fail( "OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.", "Error code: " + asyncResult.dwError + " (" + innerException.Message + ")"); break; } } private static void ResetAuthRequestHeaders(WinHttpRequestState state) { const string AuthHeaderNameWithColon = "Authorization:"; SafeWinHttpHandle requestHandle = state.RequestHandle; // Clear auth headers. if (!Interop.WinHttp.WinHttpAddRequestHeaders( requestHandle, AuthHeaderNameWithColon, (uint)AuthHeaderNameWithColon.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_REPLACE)) { int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { throw WinHttpException.CreateExceptionUsingError(lastError, "WINHTTP_CALLBACK_STATUS_REDIRECT/WinHttpAddRequestHeaders"); } } } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using OpenADK.Library.Impl; using log4net; namespace OpenADK.Library { /// <summary> The base class for all exception classes defined by the Adk.</summary> /// <remarks> /// AdkExceptions have the following characteristics: /// <list type="bullet"> /// <item> /// <term>An exception may contain one or more child exceptions. All Adk /// methods that operate on multiple zones or topics take a fail-late /// approach where the method continues processing even when an error /// occurs. Only after all zones and topics have been enumerated is a /// final exception thrown. It may contain multiple child exceptions /// collected during the processing</term> /// </item> /// <item><term>The caller can obtain a reference to the Zone in which the exception /// occurred.</term></item> /// </list> /// <para>Author: Eric Peterson</para> /// <para>Version: Adk 1.0</para> /// </remarks> [Serializable] public class AdkException : Exception { /// <summary> When this flag is enabled, the Adk will retain the message associated /// with the exception rather than removing it from the agent's queue, if /// possible. /// </summary> /// <seealso cref="Retry"> /// </seealso> private const int FLG_RETRY = 0x00000001; /// <summary> The Zone associated with this exception. Because the Zone interface does /// not support RMI, this is a transient data member. Rather than calling /// <c>getZone</c> to retrieve the zone associated with an AdkException, /// RMI-based clients should use the <c>getZoneId</c> method /// instead. /// </summary> [NonSerialized()] private IZone fZone; /// <summary> The ID of the zone associated with this exception</summary> private string fZoneId; /// <summary> The nested child exceptions</summary> private List<Exception> fChildren; /// <summary> Optional exception flags that may influence how the Adk handles this /// exception when it is caught within the class framework /// </summary> private int fFlags; /// <summary> Constructs an exception with a detailed message that occurs in the /// context of a zone /// </summary> /// <param name="msg">A message describing the exception /// </param> /// <param name="zone">The zone associated with the exception /// </param> public AdkException(string msg, IZone zone) : base(msg) { fZone = zone; fZoneId = zone == null ? null : zone.ZoneId; } /// <summary> /// Constructs an exception with zone information and the exception that caused this exception to be raised /// </summary> /// <param name="msg"></param> /// <param name="zone"></param> /// <param name="innerException"></param> public AdkException(string msg, IZone zone, Exception innerException) : base(msg, innerException) { fZone = zone; fZoneId = zone == null ? null : zone.ZoneId; } /// <summary> /// The .Net Serialization constructor /// </summary> /// <param name="info"></param> /// <param name="context"></param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] protected AdkException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> Gets the zone associated with this exception.</summary> /// <remarks> /// <note type="note">The Adk's <c>IZone</c> interface does not support remoting. /// Therefore, this method will return a <c>null</c> value when called /// by an remoting client on a marshalled AdkException object. Remoting clients /// should instead use the <c>ZoneId</c> method to learn the ID of /// the zone passed to the constructor.</note> /// </remarks> /// <returns> The Zone associated with the exception</returns> /// <seealso cref="ZoneId"/> public virtual IZone Zone { get { return fZone; } } /// <summary> Gets the ID of the zone associated with this exception.</summary> /// <returns> the ID of the Zone passed to the constructor</returns> /// <seealso cref="Zone"> /// </seealso> public virtual string ZoneId { get { return fZoneId; } } /// <summary> Gets the child exceptions, if any</summary> public virtual Exception [] Children { get { if( fChildren == null ) { return new Exception[0]; } return fChildren.ToArray(); } } /// <summary> Determines if the Adk should attempt to retry the operation associated /// with this exception. /// </summary> /// <value>True if the exception is flagged for retry (the default is /// false). The method that catches the exception should attempt to /// retry the operation in progress. /// </value> public virtual bool Retry { get { return (fFlags & FLG_RETRY) != 0; } set { if ( value ) { fFlags |= FLG_RETRY; } else { fFlags &= ~ FLG_RETRY; } } } /// <summary>Gets all child SifExceptions, if any</summary> /// <remarks> /// This API does not return all child exceptions. It only returns /// those that can be cast to a SIFException. To get an array of all /// exceptions, use the <see cref="AdkException.Children"/> property /// </remarks> /// <value> An array of SIFExceptions</value> public virtual SifException [] SIFExceptions { get { if( fChildren == null ) { return null; } List<SifException> seList = new List<SifException>(); foreach( Exception ex in fChildren ) { if( ex is SifException ) { seList.Add( (SifException) ex ); } } return seList.ToArray(); } } /// <summary> Determines if this exception has nested child exceptions</summary> public virtual bool HasChildren() { return fChildren != null; } /// <summary> Adds a child exception</summary> public virtual void Add( Exception thr ) { if ( fChildren == null ) { fChildren = new List<Exception>(); } fChildren.Add( thr ); } /// <summary> Determines if this exception contains any SifException children. /// SifException encapsulates SIF errors returned to the agent in SIF_Ack /// messages. /// /// </summary> /// <returns> true if this exception has at least one nested SifException /// </returns> public virtual bool HasSifExceptions() { if ( fChildren != null ) { foreach( Exception ex in fChildren ) { if ( ex is SifException ) { return true; } } } return false; } /// <summary> Determines if this exception contains at least one nested SifException /// with the specified error category. /// </summary> /// <param name="category">The error category to search for /// </param> /// <returns> true if this exception has nested SIFExceptions and at least one /// of those has the specified error category. /// </returns> public virtual bool HasSifError( SifErrorCategoryCode category ) { if ( this is SifException ) { return ((SifException) this).HasErrorCategory( category ); } return _recurseError( this, category ); } /// <summary> Determines if this exception contains at least one nested SifException /// with the specified error category and code. /// </summary> /// <param name="category">The error category to search for /// </param> /// <param name="code">The error code to search for /// </param> /// <returns> true if this exception has nested SIFExceptions and at least one /// of those has the specified error category and code /// </returns> public virtual bool HasSifError( SifErrorCategoryCode category, int code ) { if ( this is SifException ) { return ((SifException) this).HasError( category, code ); } return _recurseError( this, category, code ); } private bool _recurseError( AdkException parent, SifErrorCategoryCode category, int code ) { if ( parent.fChildren != null ) { Exception ch = null; for ( int i = 0; i < fChildren.Count; i++ ) { ch = (Exception) fChildren[i]; if ( ch is SifException ) { if ( ((SifException) ch).HasError( category, code ) ) { return true; } } else if ( ch is AdkException ) { if ( _recurseError( (AdkException) ch, category, code ) ) { return true; } } } } return false; } private bool _recurseError( AdkException parent, SifErrorCategoryCode category ) { if ( parent.fChildren != null ) { Exception ch = null; for ( int i = 0; i < fChildren.Count; i++ ) { ch = (Exception) fChildren[i]; if ( ch is SifException ) { if ( ((SifException) ch).HasErrorCategory( category ) ) { return true; } } else if ( ch is AdkException ) { if ( _recurseError( (AdkException) ch, category ) ) { return true; } } } } return false; } /// <summary> Returns a string representation of this exception and all child /// exceptions formatted for printing to System.out. Each exception is /// on its own line. /// </summary> public override string ToString() { return ToString( 0, true ); } /// <summary> Returns a string representation of this exception and all child /// exceptions formatted for printing to System.out. Each exception is /// on its own line. /// </summary> /// <param name="indent">The amount of indentation to apply to the string</param> /// <param name="includeChildren">True if all children should be returned</param> public virtual string ToString( int indent, bool includeChildren ) { StringBuilder b = new StringBuilder(); for ( int i = 0; i < indent; i++ ) { b.Append( " " ); } // Print detailed message if any if ( indent != 0 ) { b.Append( "Zone " + (fZone == null ? "(Unknown)" : fZone.ZoneId) + ": " ); } b.Append( Message ); // Print nested exceptions if any if ( fChildren != null && includeChildren ) { b.Append( ":" ); b.Append( "\r\n" ); int cnt = fChildren.Count; for ( int i = 0; i < cnt; i++ ) { Exception innerX = (Exception) fChildren[i]; if ( innerX is AdkException ) { b.Append( ((AdkException) innerX).ToString( indent + 1, true ) ); } else { StringBuilder msg = new StringBuilder(); for ( int k = 0; k < (indent + 1); k++ ) { msg.Append( " " ); } msg.Append( innerX.ToString() ); b.Append( msg.ToString() ); } b.Append( "\r\n" ); } } return b.ToString(); } /// <summary> Write this exception and all of its nested exceptions to the logging framework. For /// any exception that is not associated with a zone, the supplied default /// Category will be used. Otherwise the Category of the zone is used. /// </summary> public virtual void Log( ILog def ) { Log( def, 0 ); } /// <summary> /// Write this exception and all of its nested exception to the logging framework /// </summary> /// <param name="def">The log to write to</param> /// <param name="indent">The amoung of indentation to apply</param> public virtual void Log( ILog def, int indent ) { ILog target = fZone == null ? def : ((ZoneImpl) fZone).Log; if( target == null ) { return; } target.Error( ToString( indent, false ) ); if ( fChildren != null ) { int cnt = fChildren.Count; for ( int i = 0; i < cnt; i++ ) { Exception innerX = (Exception) fChildren[i]; if ( innerX is AdkException ) { ((AdkException) innerX).Log( def, indent + 1 ); } else { StringBuilder msg = new StringBuilder(); for ( int k = 0; k < (indent + 1); k++ ) { msg.Append( " " ); } msg.Append( innerX.ToString() ); target.Error( msg, this ); } } } } } }
using System; using NGUI.Internal; using UnityEngine; [ExecuteInEditMode, AddComponentMenu("NGUI/Interaction/Scroll Bar")] // ReSharper disable once CheckNamespace public class UIScrollBar : MonoBehaviour { [HideInInspector, SerializeField] private UISprite mBG; private Camera mCam; [SerializeField, HideInInspector] private Direction mDir; [SerializeField, HideInInspector] private UISprite mFG; [SerializeField, HideInInspector] private bool mInverted; private bool mIsDirty; private Vector2 mScreenPos = Vector2.zero; [HideInInspector, SerializeField] private float mScroll; [SerializeField, HideInInspector] private float mSize = 1f; private Transform mTrans; public OnScrollBarChange onChange; public OnDragFinished onDragFinished; private void CenterOnPos(Vector2 localPos) { if (this.mBG != null && this.mFG != null) { Bounds bounds = NGUIMath.CalculateRelativeInnerBounds(this.cachedTransform, this.mBG); Bounds bounds2 = NGUIMath.CalculateRelativeInnerBounds(this.cachedTransform, this.mFG); if (this.mDir == Direction.Horizontal) { float num = bounds.size.x - bounds2.size.x; float num2 = num * 0.5f; float num3 = bounds.center.x - num2; float num4 = num <= 0f ? 0f : (localPos.x - num3) / num; this.scrollValue = !this.mInverted ? num4 : 1f - num4; } else { float num5 = bounds.size.y - bounds2.size.y; float num6 = num5 * 0.5f; float num7 = bounds.center.y - num6; float num8 = num5 <= 0f ? 0f : 1f - (localPos.y - num7) / num5; this.scrollValue = !this.mInverted ? num8 : 1f - num8; } } } public void ForceUpdate() { this.mIsDirty = false; if (this.mBG != null && this.mFG != null) { this.mSize = Mathf.Clamp01(this.mSize); this.mScroll = Mathf.Clamp01(this.mScroll); Vector4 border = this.mBG.border; Vector4 vector2 = this.mFG.border; Vector2 vector3 = new Vector2(Mathf.Max(0f, this.mBG.cachedTransform.localScale.x - border.x - border.z), Mathf.Max(0f, this.mBG.cachedTransform.localScale.y - border.y - border.w)); float num = !this.mInverted ? this.mScroll : 1f - this.mScroll; if (this.mDir == Direction.Horizontal) { Vector2 vector6 = new Vector2(vector3.x * this.mSize, vector3.y); this.mFG.pivot = UIWidget.Pivot.Left; this.mBG.pivot = UIWidget.Pivot.Left; this.mBG.cachedTransform.localPosition = Vector3.zero; this.mFG.cachedTransform.localPosition = new Vector3(border.x - vector2.x + (vector3.x - vector6.x) * num, 0f, 0f); this.mFG.cachedTransform.localScale = new Vector3(vector6.x + vector2.x + vector2.z, vector6.y + vector2.y + vector2.w, 1f); if (num < 0.999f && num > 0.001f) { this.mFG.MakePixelPerfect(); } } else { Vector2 vector7 = new Vector2(vector3.x, vector3.y * this.mSize); this.mFG.pivot = UIWidget.Pivot.Top; this.mBG.pivot = UIWidget.Pivot.Top; this.mBG.cachedTransform.localPosition = Vector3.zero; this.mFG.cachedTransform.localPosition = new Vector3(0f, -border.y + vector2.y - (vector3.y - vector7.y) * num, 0f); this.mFG.cachedTransform.localScale = new Vector3(vector7.x + vector2.x + vector2.z, vector7.y + vector2.y + vector2.w, 1f); if (num < 0.999f && num > 0.001f) { this.mFG.MakePixelPerfect(); } } } } private void OnDragBackground(GameObject go, Vector2 delta) { this.mCam = UICamera.currentCamera; this.Reposition(UICamera.lastTouchPosition); } private void OnDragForeground(GameObject go, Vector2 delta) { this.mCam = UICamera.currentCamera; this.Reposition(this.mScreenPos + UICamera.currentTouch.totalDelta); } private void OnPressBackground(GameObject go, bool isPressed) { this.mCam = UICamera.currentCamera; this.Reposition(UICamera.lastTouchPosition); if (!isPressed && this.onDragFinished != null) { this.onDragFinished(); } } private void OnPressForeground(GameObject go, bool isPressed) { if (isPressed) { this.mCam = UICamera.currentCamera; Bounds bounds = NGUIMath.CalculateAbsoluteWidgetBounds(this.mFG.cachedTransform); this.mScreenPos = this.mCam.WorldToScreenPoint(bounds.center); } else if (this.onDragFinished != null) { this.onDragFinished(); } } private void Reposition(Vector2 screenPos) { float num; Transform cachedTransform = this.cachedTransform; Plane plane = new Plane(cachedTransform.rotation * Vector3.back, cachedTransform.position); Ray ray = this.cachedCamera.ScreenPointToRay(screenPos); if (plane.Raycast(ray, out num)) { this.CenterOnPos(cachedTransform.InverseTransformPoint(ray.GetPoint(num))); } } private void Start() { if (this.background != null && this.background.collider != null) { UIEventListener listener = UIEventListener.Get(this.background.gameObject); listener.onPress = (UIEventListener.BoolDelegate) Delegate.Combine(listener.onPress, new UIEventListener.BoolDelegate(this.OnPressBackground)); listener.onDrag = (UIEventListener.VectorDelegate) Delegate.Combine(listener.onDrag, new UIEventListener.VectorDelegate(this.OnDragBackground)); } if (this.foreground != null && this.foreground.collider != null) { UIEventListener listener2 = UIEventListener.Get(this.foreground.gameObject); listener2.onPress = (UIEventListener.BoolDelegate) Delegate.Combine(listener2.onPress, new UIEventListener.BoolDelegate(this.OnPressForeground)); listener2.onDrag = (UIEventListener.VectorDelegate) Delegate.Combine(listener2.onDrag, new UIEventListener.VectorDelegate(this.OnDragForeground)); } this.ForceUpdate(); } private void Update() { if (this.mIsDirty) { this.ForceUpdate(); } } public float alpha { get { if (this.mFG != null) { return this.mFG.alpha; } if (this.mBG != null) { return this.mBG.alpha; } return 0f; } set { if (this.mFG != null) { this.mFG.alpha = value; NGUITools.SetActiveSelf(this.mFG.gameObject, this.mFG.alpha > 0.001f); } if (this.mBG != null) { this.mBG.alpha = value; NGUITools.SetActiveSelf(this.mBG.gameObject, this.mBG.alpha > 0.001f); } } } public UISprite background { get { return this.mBG; } set { if (this.mBG != value) { this.mBG = value; this.mIsDirty = true; } } } public float barSize { get { return this.mSize; } set { float num = Mathf.Clamp01(value); if (this.mSize != num) { this.mSize = num; this.mIsDirty = true; if (this.onChange != null) { this.onChange(this); } } } } public Camera cachedCamera { get { if (this.mCam == null) { this.mCam = NGUITools.FindCameraForLayer(gameObject.layer); } return this.mCam; } } public Transform cachedTransform { get { if (this.mTrans == null) { this.mTrans = transform; } return this.mTrans; } } public Direction direction { get { return this.mDir; } set { if (this.mDir != value) { this.mDir = value; this.mIsDirty = true; if (this.mBG != null) { Transform cachedTransform = this.mBG.cachedTransform; Vector3 localScale = cachedTransform.localScale; if (this.mDir == Direction.Vertical && localScale.x > localScale.y || this.mDir == Direction.Horizontal && localScale.x < localScale.y) { float x = localScale.x; localScale.x = localScale.y; localScale.y = x; cachedTransform.localScale = localScale; this.ForceUpdate(); if (this.mBG.collider != null) { NGUITools.AddWidgetCollider(this.mBG.gameObject); } if (this.mFG.collider != null) { NGUITools.AddWidgetCollider(this.mFG.gameObject); } } } } } } public UISprite foreground { get { return this.mFG; } set { if (this.mFG != value) { this.mFG = value; this.mIsDirty = true; } } } public bool inverted { get { return this.mInverted; } set { if (this.mInverted != value) { this.mInverted = value; this.mIsDirty = true; } } } public float scrollValue { get { return this.mScroll; } set { float num = Mathf.Clamp01(value); if (this.mScroll != num) { this.mScroll = num; this.mIsDirty = true; if (this.onChange != null) { this.onChange(this); } } } } public enum Direction { Horizontal, Vertical } public delegate void OnDragFinished(); public delegate void OnScrollBarChange(UIScrollBar sb); }
using System; using System.Collections.Generic; using System.Linq; namespace TestFirst.Net { /// <summary> /// Collect a number of <see cref="IInserter"/>'s together to represent a set of relationships. /// <para> /// Note: Suggested usage is to subclass this to create your own model and hide all these methods from users. This way you /// can ensure your model is limited and controlled and documented /// </para> /// <para> /// Note:think of this as simply a glorified dictionary with convenient inserter lookup and register logic (which it really is). Various /// methods operate to locate the inserter of interest and mutates it /// </para> /// TODO:should this be renamed to InserterModel? is really a collection of inserters to represent a model in the db /// </summary> public class GroupedInserters : IInserter { private const int DefaultIndex = 0; private readonly IDictionary<string, IInserter> m_insertersByKey = new Dictionary<string, IInserter>(); // can't gaurantee order in above and some inserters may require others to be run first private readonly IList<IInserter> m_insertersInOrderAdded = new List<IInserter>(); /// <summary> /// Holds the next available index we can use for the given inserter type. Allows us to automatically increment /// keys when adding an inserter for which the user has not provided a key /// </summary> private readonly IDictionary<Type, int> m_nextAvailableIndexByInserterType = new Dictionary<Type, int>(); /// <summary> /// Initializes a new instance of the <see cref="GroupedInserters"/> class. /// Encourage specific subclasses to group operations instead of each caller adding their own inserters /// willy nilly /// </summary> protected GroupedInserters() { } /// <summary> /// Return the inserter of the given type or null if it doesn't exist /// </summary> /// <returns>The inserter</returns> /// <typeparam name="T">The type of inserter</typeparam> public T Get<T>() where T : IInserter, ICloneable { return Get<T>(DefaultIndex); } public T Get<T>(Enum key) where T : IInserter, ICloneable { return With<T>(key); } public T Get<T>(int index) where T : IInserter, ICloneable { return With<T>(index); } public T GetOrAdd<T>() where T : IInserter, ICloneable, new() { return WithOrAdd<T>(DefaultIndex); } public T GetOrAdd<T>(Func<T> factory) where T : IInserter, ICloneable { return WithOrAdd(DefaultIndex, factory); } public IEnumerable<T> GetAll<T>() where T : IInserter, ICloneable { return WithAll<T>(); } public IList<T> GetWhere<T>(Func<T, bool> condition) where T : IInserter, ICloneable { return new List<T>(GetAll<T>().Where(condition)); } /// <summary> /// Return all the inserters added. Useful if you need to perform any dependency resolution (most likely via property /// injection) /// </summary> /// <returns>The list of inserters</returns> public IEnumerable<IInserter> GetInserters() { return new List<IInserter>(m_insertersByKey.Values); } public virtual void Insert() { foreach (var inserter in GetInsertersInInsertionOrder()) { inserter.Insert(); } } public virtual GroupedInserters Clone() { return Clone(new GroupedInserters()); } public T Clone<T>(T newSubClassInstance) where T : GroupedInserters { var clonedInserters = new Dictionary<string, IInserter>(); // clone inserters first before assigning, in case clone throws an error foreach (var entry in m_insertersByKey) { var inserter = entry.Value; clonedInserters.Add(entry.Key, (IInserter)((ICloneable)inserter)); } // should now be a safe operation to copy cloned inserters across foreach (var entry in clonedInserters) { newSubClassInstance.m_insertersByKey[entry.Key] = entry.Value; } return newSubClassInstance; } /// <summary> /// Adds a new inserter of type T. /// If one already exists, adds another with the next available index. /// </summary> /// <typeparam name="T">The type of object being inserted</typeparam> /// <returns>The added objet</returns> protected T Add<T>() where T : IInserter, ICloneable, new() { int autoIndex = GetNextAvailableIndexForType<T>(); return Add(new T(), autoIndex); } /// <summary> /// Use to add multiple inserters with known IDs. /// </summary> /// <typeparam name="T">The type of object being added</typeparam> /// <param name="index">The index of the item being added</param> /// <returns>The added object</returns> protected T Add<T>(int index) where T : IInserter, ICloneable, new() { return Add(new T(), index); } protected T Add<T>(T inserter) where T : IInserter, ICloneable { return Add(inserter, DefaultIndex); } protected T AddAutoIndex<T>() where T : IInserter, ICloneable, new() { return AddAutoIndex(new T()); } protected T AddAutoIndex<T>(T inserter) where T : IInserter, ICloneable { var autoIndex = GetNextAvailableIndexForType<T>(); return Add(inserter, autoIndex); } protected T Add<T>(T inserter, int index) where T : IInserter, ICloneable { string internalKey = ToKey(inserter.GetType(), index); // todo: catch exception and suggest AddAnother() InternalAddInserterByKey(internalKey, inserter); IncrementNextAvailableIndexForType<T>(index); return inserter; } protected T Add<T>(Enum key) where T : IInserter, ICloneable, new() { return Add(new T(), key); } protected T Add<T>(T inserter, Enum key) where T : IInserter, ICloneable { string internalKey = ToKey(inserter.GetType(), key); InternalAddInserterByKey(internalKey, inserter); return inserter; } protected T Add<T>(string userKey) where T : IInserter, ICloneable, new() { return Add(new T(), userKey); } protected T Add<T>(T inserter, string userKey) where T : IInserter, ICloneable { string internalKey = ToKey(inserter.GetType(), userKey); InternalAddInserterByKey(internalKey, inserter); return inserter; } protected void With<T>(Action<T> action) where T : IInserter, ICloneable { var inserters = WithAll<T>().ToList(); if (inserters.Count != 1) { throw new TestFirstException("Expected 1 inserter of type " + typeof(T).FullName + " but found " + inserters.Count); } action.Invoke(inserters.FirstOrDefault()); } /// <summary> /// Applies action to all inserters of type T, in no specific order. /// Returns list of matched inserters, or empty list. /// </summary> /// <param name="action">The action to apply to all inserters of given type</param> /// <typeparam name="T">The inserter type</typeparam> protected void WithAll<T>(Action<T> action) where T : IInserter, ICloneable { WithAll<T>().ToList().ForEach(action.Invoke); } protected void RemoveAll<T>(Func<T, bool> condition) where T : IInserter, ICloneable { var inserters = GetAll<T>().ToList(); foreach (var inserter in inserters) { if (condition(inserter)) { Remove(inserter); } } } protected void Remove(IInserter inserter) { foreach (var entry in m_insertersByKey.Where(kvp => kvp.Value == inserter).ToList()) { m_insertersByKey.Remove(entry); } m_insertersInOrderAdded.Remove(inserter); } /// <summary> /// Override this if you wish to perform custom reordering of inserters. May be useful if you add inserters on the fly /// and these are required to be run before previously added inserters /// </summary> /// <returns>The list of inserters in insertion order</returns> protected virtual IEnumerable<IInserter> GetInsertersInInsertionOrder() { return m_insertersInOrderAdded; } private static string ToKey(Type t, Enum key) { return t.FullName + ":" + key.GetType().Name + ":" + key; } private static string ToKey(Type t, int index) { return t.FullName + ":" + index; } private static string ToKey(Type t, string userSuppliedKey) { return t.FullName + ":<user-key>:" + userSuppliedKey; } private void InternalAddInserterByKey<T>(string internalKey, T inserter) where T : IInserter, ICloneable { try { m_insertersByKey.Add(internalKey, inserter); m_insertersInOrderAdded.Add(inserter); } catch (ArgumentException e) { throw new ArgumentException(string.Format("Error adding inserter {0} with key '{1}'. Already have keys [{2}]", inserter, internalKey, string.Join(",\n", m_insertersByKey.Keys)), e); } } /// <summary> /// Get all inserters of type T, in no specific order, or empty list. /// </summary> /// <typeparam name="T">The inserter type</typeparam> /// <returns>List of inserters</returns> private IEnumerable<T> WithAll<T>() where T : IInserter, ICloneable { return m_insertersByKey.Values.Where(inserter => inserter is T).Cast<T>(); } /// <summary> /// Return the inserter of the given type, with the given key, if it exists, else throw an exception /// </summary>e /// <typeparam name="T">the inserter type</typeparam> /// <param name="key">the sub key</param> /// <returns>the configured instance of the given type</returns> private T With<T>(Enum key) where T : IInserter, ICloneable { IInserter inserter; var internalKey = ToKey(typeof(T), key); if (!m_insertersByKey.TryGetValue(internalKey, out inserter)) { var pairs = m_insertersByKey.Select(pair => pair.Key + "=" + pair.Value.GetType().FullName); var availableKeysAndTypes = string.Join(",", pairs); throw new InvalidOperationException(string.Format("no inserter of type '{0}' with key {1}. Have [{2}]", typeof(T).FullName, key, availableKeysAndTypes)); } return (T)inserter; } /// <summary> /// Return the inserter of the given type, with the given index, if it exists, else throw an exception /// </summary> /// <typeparam name="T">the inserter type</typeparam> /// <param name="index">the sub index</param> /// <returns>the configured instance of the given type</returns> private T With<T>(int index) where T : IInserter, ICloneable { IInserter inserter; string internalKey = ToKey(typeof(T), index); if (!m_insertersByKey.TryGetValue(internalKey, out inserter)) { var pairs = m_insertersByKey.Select(pair => pair.Key + "=" + pair.Value.GetType().FullName); var availableKeysAndTypes = string.Join(",", pairs); throw new InvalidOperationException(string.Format("no inserter of type '{0}' with index {1}. Have [{2}]", typeof(T).FullName, index, availableKeysAndTypes)); } return (T)inserter; } private T WithOrAdd<T>(int index) where T : IInserter, ICloneable, new() { return WithOrAdd(index, () => new T()); } private T WithOrAdd<T>(int index, Func<T> factory) where T : IInserter, ICloneable { IInserter inserter; string internalKey = ToKey(typeof(T), index); if (!m_insertersByKey.TryGetValue(internalKey, out inserter)) { // lets add it inserter = Add(factory.Invoke(), index); } return (T)inserter; } private void IncrementNextAvailableIndexForType<T>(int insertedIndex) { // be careful that we don't decrement, as user might be inserting in a random order int nextIndex = GetNextAvailableIndexForType<T>(); if (insertedIndex >= nextIndex) { m_nextAvailableIndexByInserterType[typeof(T)] = insertedIndex + 1; } } private int GetNextAvailableIndexForType<T>() { int result; return m_nextAvailableIndexByInserterType.TryGetValue(typeof(T), out result) ? result : DefaultIndex; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using RentalNinja.Models; namespace RentalNinja.Migrations { [ContextType(typeof(ApplicationDbContext))] partial class CreateIdentitySchema { public override string Id { get { return "00000000000000_CreateIdentitySchema"; } } public override string ProductVersion { get { return "7.0.0-beta5"; } } public override void BuildTargetModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId") .Annotation("OriginalValueIndex", 0); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("RentalNinja.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 1); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 2); b.Property<string>("Email") .Annotation("OriginalValueIndex", 3); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("RentalNinja.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("RentalNinja.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("RentalNinja.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
//------------------------------------------------------------------------------ // <copyright file="StreamedReader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; internal sealed class StreamedReader : TransferReaderWriterBase { /// <summary> /// Source stream to be read from. /// It's a user input stream or a FileStream with the user input FilePath in source location. /// </summary> private Stream inputStream; /// <summary> /// Value to indicate whether the input stream is a file stream owned by this reader or input by user. /// If it's a file stream owned by this reader, we should close it when reading is finished. /// </summary> private bool ownsStream; /// <summary> /// Transfer job instance. /// </summary> private TransferJob transferJob; /// <summary> /// Countdown event to track the download status. /// Its count should be the same with count of chunks to be read. /// </summary> private CountdownEvent countdownEvent; /// <summary> /// Transfer window in check point. /// </summary> private Queue<long> lastTransferWindow; private volatile State state; private volatile bool hasWork; /// <summary> /// Stream to read from source and calculate md5 hash of source. /// </summary> private MD5HashStream md5HashStream; public StreamedReader( TransferScheduler scheduler, SyncTransferController controller, CancellationToken cancellationToken) : base(scheduler, controller, cancellationToken) { this.transferJob = this.SharedTransferData.TransferJob; this.hasWork = true; } private enum State { OpenInputStream, ReadStream, Error, Finished } public override bool IsFinished { get { return this.state == State.Error || this.state == State.Finished; } } public override bool HasWork { get { return this.hasWork; } } public override async Task DoWorkInternalAsync() { switch (this.state) { case State.OpenInputStream: await this.OpenInputStreamAsync(); break; case State.ReadStream: await this.ReadStreamAsync(); break; case State.Error: case State.Finished: break; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { this.CloseOwnStream(); if (null != this.md5HashStream) { this.md5HashStream.Dispose(); this.md5HashStream = null; } if (null != this.countdownEvent) { this.countdownEvent.Dispose(); } } } private async Task OpenInputStreamAsync() { Debug.Assert( State.OpenInputStream == this.state, "OpenInputStreamAsync called, but state is not OpenInputStream."); this.hasWork = false; await Task.Run(() => { this.NotifyStarting(); this.Controller.CheckCancellation(); if (this.transferJob.Source.Type == TransferLocationType.Stream) { StreamLocation streamLocation = this.transferJob.Source as StreamLocation; this.inputStream = streamLocation.Stream; this.ownsStream = false; if (!this.inputStream.CanRead) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportReadException, "inputStream")); } if (!this.inputStream.CanSeek) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportSeekException, "inputStream")); } } else { FileLocation fileLocation = this.transferJob.Source as FileLocation; Debug.Assert( null != fileLocation, "Initializing StreamedReader instance, but source is neither a stream nor a file"); try { // Attempt to open the file first so that we throw an exception before getting into the async work this.inputStream = new FileStream( fileLocation.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); this.ownsStream = true; } catch (Exception ex) { if ((ex is NotSupportedException) || (ex is IOException) || (ex is UnauthorizedAccessException) || (ex is SecurityException) || (ex is ArgumentException && !(ex is ArgumentNullException))) { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToOpenFileException, fileLocation.FilePath, ex.Message); throw new TransferException( TransferErrorCode.OpenFileFailed, exceptionMessage, ex); } else { throw; } } } }); this.SharedTransferData.TotalLength = this.inputStream.Length; int count = (int)Math.Ceiling((double)(this.SharedTransferData.TotalLength - this.transferJob.CheckPoint.EntryTransferOffset) / this.Scheduler.TransferOptions.BlockSize); if (null != this.transferJob.CheckPoint.TransferWindow) { count += this.transferJob.CheckPoint.TransferWindow.Count; } this.lastTransferWindow = new Queue<long>(this.transferJob.CheckPoint.TransferWindow); this.md5HashStream = new MD5HashStream( this.inputStream, this.transferJob.CheckPoint.EntryTransferOffset, true); this.PreProcessed = true; // This reader will come into 'Finish' state after all chunks are read and MD5 calculation completes. // So initialize the CountDownEvent to count (number of chunks to read) + 1 (md5 calculation). this.countdownEvent = new CountdownEvent(count + 1); if (0 != count) { // Change the state to 'ReadStream' before awaiting MD5 calculation task to not block the reader. this.state = State.ReadStream; this.hasWork = true; } if (!this.md5HashStream.FinishedSeparateMd5Calculator) { await Task.Run(() => { this.md5HashStream.CalculateMd5(this.Scheduler.MemoryManager, this.Controller.CheckCancellation); }); } this.SetChunkFinish(); } private async Task ReadStreamAsync() { Debug.Assert( this.state == State.ReadStream || this.state == State.Error, "ReadChunks called, but state isn't ReadStream or Error"); this.hasWork = false; byte[] memoryBuffer = this.Scheduler.MemoryManager.RequireBuffer(); if (null != memoryBuffer) { long startOffset = 0; if (0 != this.lastTransferWindow.Count) { startOffset = this.lastTransferWindow.Dequeue(); } else { bool canRead = false; lock (this.transferJob.CheckPoint.TransferWindowLock) { if (this.transferJob.CheckPoint.TransferWindow.Count < Constants.MaxCountInTransferWindow) { startOffset = this.transferJob.CheckPoint.EntryTransferOffset; if (this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength) { this.transferJob.CheckPoint.TransferWindow.Add(startOffset); this.transferJob.CheckPoint.EntryTransferOffset = Math.Min( this.transferJob.CheckPoint.EntryTransferOffset + this.Scheduler.TransferOptions.BlockSize, this.SharedTransferData.TotalLength); canRead = true; } } } if (!canRead) { this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer); this.hasWork = true; return; } } if ((startOffset > this.SharedTransferData.TotalLength) || (startOffset < 0)) { this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer); throw new InvalidOperationException(Resources.RestartableInfoCorruptedException); } ReadDataState asyncState = new ReadDataState { MemoryBuffer = memoryBuffer, BytesRead = 0, StartOffset = startOffset, Length = (int)Math.Min(this.Scheduler.TransferOptions.BlockSize, this.SharedTransferData.TotalLength - startOffset), MemoryManager = this.Scheduler.MemoryManager, }; using (asyncState) { await this.ReadChunkAsync(asyncState); } } this.SetHasWork(); } private async Task ReadChunkAsync(ReadDataState asyncState) { Debug.Assert(null != asyncState, "asyncState object expected"); Debug.Assert( this.state == State.ReadStream || this.state == State.Error, "ReadChunkAsync called, but state isn't Upload or Error"); int readBytes = await this.md5HashStream.ReadAsync( asyncState.StartOffset + asyncState.BytesRead, asyncState.MemoryBuffer, asyncState.BytesRead, asyncState.Length - asyncState.BytesRead, this.CancellationToken); // If a parallel operation caused the controller to be placed in // error state exit early to avoid unnecessary I/O. // Note that this check needs to be after the EndRead operation // above to avoid leaking resources. if (this.state == State.Error) { return; } asyncState.BytesRead += readBytes; if (asyncState.BytesRead < asyncState.Length) { await this.ReadChunkAsync(asyncState); } else { this.Controller.CheckCancellation(); if (!this.md5HashStream.MD5HashTransformBlock(asyncState.StartOffset, asyncState.MemoryBuffer, 0, asyncState.Length)) { // Error info has been set in Calculate MD5 action, just return return; } TransferData transferData = new TransferData(this.Scheduler.MemoryManager) { StartOffset = asyncState.StartOffset, Length = asyncState.Length, MemoryBuffer = asyncState.MemoryBuffer }; asyncState.MemoryBuffer = null; this.SharedTransferData.AvailableData.TryAdd(transferData.StartOffset, transferData); this.SetChunkFinish(); } } private void SetHasWork() { if (this.HasWork) { return; } // Check if we have blocks available to download. if ((null != this.lastTransferWindow && this.lastTransferWindow.Any()) || this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength) { this.hasWork = true; return; } } private void SetChunkFinish() { if (this.countdownEvent.Signal()) { this.state = State.Finished; this.CloseOwnStream(); if (!this.md5HashStream.SucceededSeparateMd5Calculator) { return; } var md5 = this.md5HashStream.MD5HashTransformFinalBlock(); this.SharedTransferData.Attributes = new Attributes() { ContentMD5 = md5, OverWriteAll = false }; } } private void CloseOwnStream() { if (this.ownsStream) { if (null != this.inputStream) { #if DOTNET5_4 this.inputStream.Dispose(); #else this.inputStream.Close(); #endif this.inputStream = null; } } } } }
// // PlayerEngine.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2006-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using Hyena; using Banshee.Base; using Banshee.Streaming; using Banshee.Collection; using Banshee.ServiceStack; namespace Banshee.MediaEngine { public abstract class PlayerEngine : IDisposable { public const int VolumeDelta = 10; public const int SkipDelta = 10; public event PlayerEventHandler EventChanged; private TrackInfo current_track; private TrackInfo pending_track; private PlayerState current_state = PlayerState.NotReady; private PlayerState last_state = PlayerState.NotReady; // will be changed to PlayerState.Idle after going to PlayerState.Ready private PlayerState idle_state = PlayerState.NotReady; protected abstract void OpenUri (SafeUri uri, bool maybeVideo); internal protected virtual bool DelayedInitialize { get { return false; } } public bool IsInitialized { get; internal set; } internal protected virtual void Initialize () { } public void Reset () { current_track = null; OnStateChanged (idle_state); } public virtual void Close (bool fullShutdown) { if (fullShutdown) { Reset (); } else { OnStateChanged (idle_state); } } public virtual void Dispose () { Close (true); } public void Open (SafeUri uri) { HandleOpen (new UnknownTrackInfo (uri)); } public void Open (TrackInfo track) { HandleOpen (track); } public void SetNextTrack (SafeUri uri) { SetNextTrack (new UnknownTrackInfo (uri)); } public void SetNextTrack (TrackInfo track) { HandleNextTrack (track); } private void HandleNextTrack (TrackInfo track) { pending_track = track; if (current_state != PlayerState.Playing) { // Pre-buffering the next track only makes sense when we're currently playing // Instead, just open. if (track != null && track.Uri != null) { HandleOpen (track); Play (); } return; } try { // Setting the next track doesn't change the player state. SetNextTrackUri (track == null ? null : track.Uri, track == null || track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo); } catch (Exception e) { Log.Exception ("Failed to pre-buffer next track", e); } } private void HandleOpen (TrackInfo track) { var uri = track.Uri; if (current_state != PlayerState.Idle && current_state != PlayerState.NotReady && current_state != PlayerState.Contacting) { Close (false); } try { current_track = track; OnStateChanged (PlayerState.Loading); OpenUri (uri, track.HasAttribute (TrackMediaAttributes.VideoStream) || track is UnknownTrackInfo); } catch (Exception e) { Close (true); OnEventChanged (new PlayerEventErrorArgs (e.Message)); } } public abstract void Play (); public abstract void Pause (); public abstract void Seek (uint position, bool accurate_seek); public void Seek (uint position) { Seek (position, false); } public virtual void SetNextTrackUri (SafeUri uri, bool maybeVideo) { // Opening files on SetNextTrack is a sane default behaviour. // This only wants to be overridden if the PlayerEngine sends out RequestNextTrack signals before EoS OpenUri (uri, maybeVideo); } public virtual void VideoExpose (IntPtr displayContext, bool direct) { throw new NotImplementedException ("Engine must implement VideoExpose since this method only gets called when SupportsVideo is true"); } public virtual void VideoWindowRealize (IntPtr displayContext) { throw new NotImplementedException ("Engine must implement VideoWindowRealize since this method only gets called when SupportsVideo is true"); } public virtual IntPtr [] GetBaseElements () { return null; } protected virtual void OnStateChanged (PlayerState state) { if (current_state == state) { return; } if (idle_state == PlayerState.NotReady && state != PlayerState.Ready) { Hyena.Log.Warning ("Engine must transition to the ready state before other states can be entered", false); return; } else if (idle_state == PlayerState.NotReady && state == PlayerState.Ready) { idle_state = PlayerState.Idle; } last_state = current_state; current_state = state; Log.DebugFormat ("Player state change: {0} -> {1}", last_state, current_state); OnEventChanged (new PlayerEventStateChangeArgs (last_state, current_state)); // Going to the Ready state automatically transitions to the Idle state // The Ready state is advertised so one-time startup processes can easily // happen outside of the engine itself if (state == PlayerState.Ready) { OnStateChanged (PlayerState.Idle); } } protected void OnEventChanged (PlayerEvent evnt) { OnEventChanged (new PlayerEventArgs (evnt)); } protected virtual void OnEventChanged (PlayerEventArgs args) { if (args.Event == PlayerEvent.StartOfStream && pending_track != null) { Log.DebugFormat ("OnEventChanged called with StartOfStream. Replacing current_track with pending_track: \"{0}\"", pending_track.DisplayTrackTitle); current_track = pending_track; pending_track = null; } if (ThreadAssist.InMainThread) { RaiseEventChanged (args); } else { ThreadAssist.ProxyToMain (delegate { RaiseEventChanged (args); }); } } private void RaiseEventChanged (PlayerEventArgs args) { PlayerEventHandler handler = EventChanged; if (handler != null) { handler (args); } } private uint track_info_updated_timeout = 0; protected void OnTagFound (StreamTag tag) { if (tag.Equals (StreamTag.Zero) || current_track == null || (current_track.Uri != null && current_track.Uri.IsFile)) { return; } StreamTagger.TrackInfoMerge (current_track, tag); if (track_info_updated_timeout <= 0) { track_info_updated_timeout = Application.RunTimeout (250, OnTrackInfoUpdated); } } private bool OnTrackInfoUpdated () { TrackInfoUpdated (); track_info_updated_timeout = 0; return false; } public void TrackInfoUpdated () { OnEventChanged (PlayerEvent.TrackInfoUpdated); } public abstract string GetSubtitleDescription (int index); public TrackInfo CurrentTrack { get { return current_track; } } public SafeUri CurrentUri { get { return current_track == null ? null : current_track.Uri; } } public PlayerState CurrentState { get { return current_state; } } public PlayerState LastState { get { return last_state; } } public abstract ushort Volume { get; set; } public virtual bool CanSeek { get { return true; } } public abstract uint Position { get; set; } public abstract uint Length { get; } public abstract IEnumerable SourceCapabilities { get; } public abstract IEnumerable ExplicitDecoderCapabilities { get; } public abstract string Id { get; } public abstract string Name { get; } public abstract bool SupportsEqualizer { get; } public abstract VideoDisplayContextType VideoDisplayContextType { get; } public virtual IntPtr VideoDisplayContext { set { } get { return IntPtr.Zero; } } public abstract int SubtitleCount { get; } public abstract int SubtitleIndex { set; } public abstract SafeUri SubtitleUri { set; get; } public abstract bool InDvdMenu { get; } public abstract void NotifyMouseMove (double x, double y); public abstract void NotifyMouseButtonPressed (int button, double x, double y); public abstract void NotifyMouseButtonReleased (int button, double x, double y); public abstract void NavigateToLeftMenu (); public abstract void NavigateToRightMenu (); public abstract void NavigateToUpMenu (); public abstract void NavigateToDownMenu (); public abstract void NavigateToMenu (); public abstract void ActivateCurrentMenu (); public abstract void GoToNextChapter (); public abstract void GoToPreviousChapter (); } }
// 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.Buffers; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial; namespace Internal.Cryptography { internal static partial class PkcsHelpers { private static readonly byte[] s_pSpecifiedDefaultParameters = { 0x04, 0x00 }; #if !netcoreapp && !netcoreapp30 && !netstandard21 // Compatibility API. internal static void AppendData(this IncrementalHash hasher, ReadOnlySpan<byte> data) { hasher.AppendData(data.ToArray()); } #endif internal static HashAlgorithmName GetDigestAlgorithm(Oid oid) { Debug.Assert(oid != null); return GetDigestAlgorithm(oid.Value); } internal static HashAlgorithmName GetDigestAlgorithm(string oidValue, bool forVerification = false) { switch (oidValue) { case Oids.Md5: case Oids.RsaPkcs1Md5 when forVerification: return HashAlgorithmName.MD5; case Oids.Sha1: case Oids.RsaPkcs1Sha1 when forVerification: return HashAlgorithmName.SHA1; case Oids.Sha256: case Oids.RsaPkcs1Sha256 when forVerification: return HashAlgorithmName.SHA256; case Oids.Sha384: case Oids.RsaPkcs1Sha384 when forVerification: return HashAlgorithmName.SHA384; case Oids.Sha512: case Oids.RsaPkcs1Sha512 when forVerification: return HashAlgorithmName.SHA512; default: throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, oidValue); } } internal static string GetOidFromHashAlgorithm(HashAlgorithmName algName) { if (algName == HashAlgorithmName.MD5) return Oids.Md5; if (algName == HashAlgorithmName.SHA1) return Oids.Sha1; if (algName == HashAlgorithmName.SHA256) return Oids.Sha256; if (algName == HashAlgorithmName.SHA384) return Oids.Sha384; if (algName == HashAlgorithmName.SHA512) return Oids.Sha512; throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algName.Name); } /// <summary> /// This is not just a convenience wrapper for Array.Resize(). In DEBUG builds, it forces the array to move in memory even if no resize is needed. This should be used by /// helper methods that do anything of the form "call a native api once to get the estimated size, call it again to get the data and return the data in a byte[] array." /// Sometimes, that data consist of a native data structure containing pointers to other parts of the block. Using such a helper to retrieve such a block results in an intermittent /// AV. By using this helper, you make that AV repro every time. /// </summary> public static byte[] Resize(this byte[] a, int size) { Array.Resize(ref a, size); #if DEBUG a = a.CloneByteArray(); #endif return a; } public static void RemoveAt<T>(ref T[] arr, int idx) { Debug.Assert(arr != null); Debug.Assert(idx >= 0); Debug.Assert(idx < arr.Length); if (arr.Length == 1) { arr = Array.Empty<T>(); return; } T[] tmp = new T[arr.Length - 1]; if (idx != 0) { Array.Copy(arr, 0, tmp, 0, idx); } if (idx < tmp.Length) { Array.Copy(arr, idx + 1, tmp, idx, tmp.Length - idx); } arr = tmp; } public static AttributeAsn[] NormalizeAttributeSet( AttributeAsn[] setItems, Action<byte[]> encodedValueProcessor=null) { byte[] normalizedValue; using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.PushSetOf(); foreach (AttributeAsn item in setItems) { item.Encode(writer); } writer.PopSetOf(); normalizedValue = writer.Encode(); if (encodedValueProcessor != null) { encodedValueProcessor(normalizedValue); } } AsnReader reader = new AsnReader(normalizedValue, AsnEncodingRules.DER); AsnReader setReader = reader.ReadSetOf(); AttributeAsn[] decodedSet = new AttributeAsn[setItems.Length]; int i = 0; while (setReader.HasData) { AttributeAsn.Decode(setReader, out AttributeAsn item); decodedSet[i] = item; i++; } return decodedSet; } internal static byte[] EncodeContentInfo( ReadOnlyMemory<byte> content, string contentType, AsnEncodingRules ruleSet = AsnEncodingRules.DER) { ContentInfoAsn contentInfo = new ContentInfoAsn { ContentType = contentType, Content = content, }; using (AsnWriter writer = new AsnWriter(ruleSet)) { contentInfo.Encode(writer); return writer.Encode(); } } public static CmsRecipientCollection DeepCopy(this CmsRecipientCollection recipients) { CmsRecipientCollection recipientsCopy = new CmsRecipientCollection(); foreach (CmsRecipient recipient in recipients) { X509Certificate2 originalCert = recipient.Certificate; X509Certificate2 certCopy = new X509Certificate2(originalCert.Handle); CmsRecipient recipientCopy; if (recipient.RSAEncryptionPadding is null) { recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy); } else { recipientCopy = new CmsRecipient(recipient.RecipientIdentifierType, certCopy, recipient.RSAEncryptionPadding); } recipientsCopy.Add(recipientCopy); GC.KeepAlive(originalCert); } return recipientsCopy; } public static byte[] UnicodeToOctetString(this string s) { byte[] octets = new byte[2 * (s.Length + 1)]; Encoding.Unicode.GetBytes(s, 0, s.Length, octets, 0); return octets; } public static string OctetStringToUnicode(this byte[] octets) { if (octets.Length < 2) return string.Empty; // Desktop compat: 0-length byte array maps to string.empty. 1-length byte array gets passed to Marshal.PtrToStringUni() with who knows what outcome. string s = Encoding.Unicode.GetString(octets, 0, octets.Length - 2); return s; } public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly) { using (X509Store store = new X509Store(storeName, storeLocation)) { OpenFlags flags = OpenFlags.ReadOnly | OpenFlags.IncludeArchived; if (openExistingOnly) flags |= OpenFlags.OpenExistingOnly; store.Open(flags); X509Certificate2Collection certificates = store.Certificates; return certificates; } } /// <summary> /// Desktop compat: We do not complain about multiple matches. Just take the first one and ignore the rest. /// </summary> public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier) { // // Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly. // Therefore, we trust that the string-ized byte array (serial or ski) in it is correct and canonicalized. // SubjectIdentifierType recipientIdentifierType = recipientIdentifier.Type; switch (recipientIdentifierType) { case SubjectIdentifierType.IssuerAndSerialNumber: { X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value); byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes(); string issuer = issuerSerial.IssuerName; foreach (X509Certificate2 candidate in certs) { byte[] candidateSerialNumber = candidate.GetSerialNumber(); if (AreByteArraysEqual(candidateSerialNumber, serialNumber) && candidate.Issuer == issuer) return candidate; } } break; case SubjectIdentifierType.SubjectKeyIdentifier: { string skiString = (string)(recipientIdentifier.Value); byte[] ski = skiString.ToSkiBytes(); foreach (X509Certificate2 cert in certs) { byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(cert); if (AreByteArraysEqual(ski, candidateSki)) return cert; } } break; default: // RecipientInfo's can only be created by this package so if this an invalid type, it's the package's fault. Debug.Fail($"Invalid recipientIdentifier type: {recipientIdentifierType}"); throw new CryptographicException(); } return null; } internal static bool AreByteArraysEqual(byte[] ba1, byte[] ba2) { if (ba1.Length != ba2.Length) return false; for (int i = 0; i < ba1.Length; i++) { if (ba1[i] != ba2[i]) return false; } return true; } /// <summary> /// Asserts on bad or non-canonicalized input. Input must come from trusted sources. /// /// Subject Key Identifier is string-ized as an upper case hex string. This format is part of the public api behavior and cannot be changed. /// </summary> internal static byte[] ToSkiBytes(this string skiString) { return skiString.UpperHexStringToByteArray(); } public static string ToSkiString(this byte[] skiBytes) { return ToUpperHexString(skiBytes); } public static string ToBigEndianHex(this ReadOnlySpan<byte> bytes) { return ToUpperHexString(bytes); } /// <summary> /// Asserts on bad or non-canonicalized input. Input must come from trusted sources. /// /// Serial number is string-ized as a reversed upper case hex string. This format is part of the public api behavior and cannot be changed. /// </summary> internal static byte[] ToSerialBytes(this string serialString) { byte[] ba = serialString.UpperHexStringToByteArray(); Array.Reverse(ba); return ba; } public static string ToSerialString(this byte[] serialBytes) { serialBytes = serialBytes.CloneByteArray(); Array.Reverse(serialBytes); return ToUpperHexString(serialBytes); } #if netcoreapp || netcoreapp30 || netstandard21 private static unsafe string ToUpperHexString(ReadOnlySpan<byte> ba) { fixed (byte* baPtr = ba) { return string.Create(ba.Length * 2, (new IntPtr(baPtr), ba.Length), (span, args) => { const string HexValues = "0123456789ABCDEF"; int p = 0; foreach (byte b in new ReadOnlySpan<byte>((byte*)args.Item1, args.Item2)) { span[p++] = HexValues[b >> 4]; span[p++] = HexValues[b & 0xF]; } }); } } #else private static string ToUpperHexString(ReadOnlySpan<byte> ba) { StringBuilder sb = new StringBuilder(ba.Length * 2); for (int i = 0; i < ba.Length; i++) { sb.Append(ba[i].ToString("X2")); } return sb.ToString(); } #endif /// <summary> /// Asserts on bad input. Input must come from trusted sources. /// </summary> private static byte[] UpperHexStringToByteArray(this string normalizedString) { Debug.Assert((normalizedString.Length & 0x1) == 0); byte[] ba = new byte[normalizedString.Length / 2]; for (int i = 0; i < ba.Length; i++) { char c = normalizedString[i * 2]; byte b = (byte)(UpperHexCharToNybble(c) << 4); c = normalizedString[i * 2 + 1]; b |= UpperHexCharToNybble(c); ba[i] = b; } return ba; } /// <summary> /// Asserts on bad input. Input must come from trusted sources. /// </summary> private static byte UpperHexCharToNybble(char c) { if (c >= '0' && c <= '9') return (byte)(c - '0'); if (c >= 'A' && c <= 'F') return (byte)(c - 'A' + 10); Debug.Fail($"Invalid hex character: {c}"); throw new CryptographicException(); // This just keeps the compiler happy. We don't expect to reach this. } /// <summary> /// Useful helper for "upgrading" well-known CMS attributes to type-specific objects such as Pkcs9DocumentName, Pkcs9DocumentDescription, etc. /// </summary> public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, byte[] encodedAttribute) { Pkcs9AttributeObject attributeObject = new Pkcs9AttributeObject(oid, encodedAttribute); switch (oid.Value) { case Oids.DocumentName: attributeObject = Upgrade<Pkcs9DocumentName>(attributeObject); break; case Oids.DocumentDescription: attributeObject = Upgrade<Pkcs9DocumentDescription>(attributeObject); break; case Oids.SigningTime: attributeObject = Upgrade<Pkcs9SigningTime>(attributeObject); break; case Oids.ContentType: attributeObject = Upgrade<Pkcs9ContentType>(attributeObject); break; case Oids.MessageDigest: attributeObject = Upgrade<Pkcs9MessageDigest>(attributeObject); break; #if netcoreapp || netcoreapp30 || netstandard21 case Oids.LocalKeyId: attributeObject = Upgrade<Pkcs9LocalKeyId>(attributeObject); break; #endif default: break; } return attributeObject; } private static T Upgrade<T>(Pkcs9AttributeObject basicAttribute) where T : Pkcs9AttributeObject, new() { T enhancedAttribute = new T(); enhancedAttribute.CopyFrom(basicAttribute); return enhancedAttribute; } internal static byte[] OneShot(this ICryptoTransform transform, byte[] data) { return OneShot(transform, data, 0, data.Length); } internal static byte[] OneShot(this ICryptoTransform transform, byte[] data, int offset, int length) { if (transform.CanTransformMultipleBlocks) { return transform.TransformFinalBlock(data, offset, length); } using (MemoryStream memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write)) { cryptoStream.Write(data, offset, length); } return memoryStream.ToArray(); } } public static ReadOnlyMemory<byte> DecodeOctetString(ReadOnlyMemory<byte> encodedOctetString) { AsnReader reader = new AsnReader(encodedOctetString, AsnEncodingRules.BER); if (reader.PeekEncodedValue().Length != encodedOctetString.Length) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } if (reader.TryReadPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> primitiveContents)) { return primitiveContents; } byte[] tooBig = new byte[encodedOctetString.Length]; if (reader.TryCopyOctetStringBytes(tooBig, out int bytesWritten)) { return tooBig.AsMemory(0, bytesWritten); } Debug.Fail("TryCopyOctetStringBytes failed with an over-allocated array"); throw new CryptographicException(); } public static bool TryGetRsaOaepEncryptionPadding( ReadOnlyMemory<byte>? parameters, out RSAEncryptionPadding rsaEncryptionPadding, out Exception exception) { exception = null; rsaEncryptionPadding = null; if (parameters == null || parameters.Value.IsEmpty) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return false; } try { OaepParamsAsn oaepParameters = OaepParamsAsn.Decode(parameters.Value, AsnEncodingRules.DER); if (oaepParameters.MaskGenFunc.Algorithm.Value != Oids.Mgf1 || oaepParameters.MaskGenFunc.Parameters == null || oaepParameters.PSourceFunc.Algorithm.Value != Oids.PSpecified ) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return false; } AlgorithmIdentifierAsn mgf1AlgorithmIdentifier = AlgorithmIdentifierAsn.Decode(oaepParameters.MaskGenFunc.Parameters.Value, AsnEncodingRules.DER); if (mgf1AlgorithmIdentifier.Algorithm.Value != oaepParameters.HashFunc.Algorithm.Value) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return false; } if (oaepParameters.PSourceFunc.Parameters != null && !oaepParameters.PSourceFunc.Parameters.Value.Span.SequenceEqual(s_pSpecifiedDefaultParameters)) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return false; } switch (oaepParameters.HashFunc.Algorithm.Value) { case Oids.Sha1: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA1; return true; case Oids.Sha256: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA256; return true; case Oids.Sha384: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA384; return true; case Oids.Sha512: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA512; return true; default: exception = new CryptographicException( SR.Cryptography_Cms_UnknownAlgorithm, oaepParameters.HashFunc.Algorithm.Value); return false; } } catch (CryptographicException e) { exception = e; return false; } } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. 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. */ using System; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Internal; using Sharpen; namespace Couchbase.Lite { /// <summary>A Couchbase Lite Document Attachment.</summary> /// <remarks>A Couchbase Lite Document Attachment.</remarks> public sealed class Attachment { /// <summary>The owning document revision.</summary> /// <remarks>The owning document revision.</remarks> private Revision revision; /// <summary>Whether or not this attachment is gzipped</summary> private bool gzipped; /// <summary>The owning document.</summary> /// <remarks>The owning document.</remarks> private Document document; /// <summary>The filename.</summary> /// <remarks>The filename.</remarks> private string name; /// <summary>The CouchbaseLite metadata about the attachment, that lives in the document. /// </summary> /// <remarks>The CouchbaseLite metadata about the attachment, that lives in the document. /// </remarks> private IDictionary<string, object> metadata; /// <summary>The body data.</summary> /// <remarks>The body data.</remarks> private InputStream body; /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Attachment(InputStream contentStream, string contentType) { this.body = contentStream; metadata = new Dictionary<string, object>(); metadata.Put("content_type", contentType); metadata.Put("follows", true); this.gzipped = false; } /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Attachment(Revision revision, string name, IDictionary<string, object> metadata ) { this.revision = revision; this.name = name; this.metadata = metadata; this.gzipped = false; } /// <summary>Get the owning document revision.</summary> /// <remarks>Get the owning document revision.</remarks> [InterfaceAudience.Public] public Revision GetRevision() { return revision; } /// <summary>Get the owning document.</summary> /// <remarks>Get the owning document.</remarks> [InterfaceAudience.Public] public Document GetDocument() { return revision.GetDocument(); } /// <summary>Get the filename.</summary> /// <remarks>Get the filename.</remarks> [InterfaceAudience.Public] public string GetName() { return name; } /// <summary>Get the MIME type of the contents.</summary> /// <remarks>Get the MIME type of the contents.</remarks> [InterfaceAudience.Public] public string GetContentType() { return (string)metadata.Get("content_type"); } /// <summary>Get the content (aka 'body') data.</summary> /// <remarks>Get the content (aka 'body') data.</remarks> /// <exception cref="CouchbaseLiteException">CouchbaseLiteException</exception> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public InputStream GetContent() { if (body != null) { return body; } else { Database db = revision.GetDatabase(); Couchbase.Lite.Attachment attachment = db.GetAttachmentForSequence(revision.GetSequence (), this.name); body = attachment.GetContent(); return body; } } /// <summary>Get the length in bytes of the contents.</summary> /// <remarks>Get the length in bytes of the contents.</remarks> [InterfaceAudience.Public] public long GetLength() { Number length = (Number)metadata.Get("length"); if (length != null) { return length; } else { return 0; } } /// <summary>The CouchbaseLite metadata about the attachment, that lives in the document. /// </summary> /// <remarks>The CouchbaseLite metadata about the attachment, that lives in the document. /// </remarks> [InterfaceAudience.Public] public IDictionary<string, object> GetMetadata() { return Sharpen.Collections.UnmodifiableMap(metadata); } [InterfaceAudience.Private] internal void SetName(string name) { this.name = name; } [InterfaceAudience.Private] internal void SetRevision(Revision revision) { this.revision = revision; } [InterfaceAudience.Private] internal InputStream GetBodyIfNew() { return body; } /// <summary> /// Goes through an _attachments dictionary and replaces any values that are Attachment objects /// with proper JSON metadata dicts. /// </summary> /// <remarks> /// Goes through an _attachments dictionary and replaces any values that are Attachment objects /// with proper JSON metadata dicts. It registers the attachment bodies with the blob store and sets /// the metadata 'digest' and 'follows' properties accordingly. /// </remarks> [InterfaceAudience.Private] internal static IDictionary<string, object> InstallAttachmentBodies(IDictionary<string , object> attachments, Database database) { IDictionary<string, object> updatedAttachments = new Dictionary<string, object>(); foreach (string name in attachments.Keys) { object value = attachments.Get(name); if (value is Couchbase.Lite.Attachment) { Couchbase.Lite.Attachment attachment = (Couchbase.Lite.Attachment)value; IDictionary<string, object> metadataMutable = new Dictionary<string, object>(); metadataMutable.PutAll(attachment.GetMetadata()); InputStream body = attachment.GetBodyIfNew(); if (body != null) { // Copy attachment body into the database's blob store: BlobStoreWriter writer = BlobStoreWriterForBody(body, database); metadataMutable.Put("length", (long)writer.GetLength()); metadataMutable.Put("digest", writer.MD5DigestString()); metadataMutable.Put("follows", true); database.RememberAttachmentWriter(writer); } updatedAttachments.Put(name, metadataMutable); } else { if (value is AttachmentInternal) { throw new ArgumentException("AttachmentInternal objects not expected here. Could indicate a bug" ); } else { if (value != null) { updatedAttachments.Put(name, value); } } } } return updatedAttachments; } [InterfaceAudience.Private] internal static BlobStoreWriter BlobStoreWriterForBody(InputStream body, Database database) { BlobStoreWriter writer = database.GetAttachmentWriter(); writer.Read(body); writer.Finish(); return writer; } /// <exclude></exclude> [InterfaceAudience.Private] public bool GetGZipped() { return gzipped; } /// <exclude></exclude> [InterfaceAudience.Private] public void SetGZipped(bool gzipped) { this.gzipped = gzipped; } } }
// 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 new CryptographicException(hr); } } } 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 new CryptographicException(Marshal.GetHRForLastWin32Error()); if (dwSigners == 0) throw new CryptographicException(ErrorCode.CRYPT_E_SIGNER_NOT_FOUND); // 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 new CryptographicException(Marshal.GetHRForLastWin32Error()); byte[] cmsgSignerBytes = new byte[cbData]; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, cmsgSignerBytes, ref cbData)) throw new CryptographicException(Marshal.GetHRForLastWin32Error()); 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 new CryptographicException(Marshal.GetHRForLastWin32Error()); 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 new CryptographicException(Marshal.GetHRForLastWin32Error()); } } 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 new CryptographicException(ErrorCode.ERROR_INVALID_PARAMETER); } 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; 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; } }
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Xml.Linq; using System.Threading.Tasks; using Microsoft.Research.Peloponnese; using Microsoft.Research.Peloponnese.NotHttpClient; namespace Microsoft.Research.Dryad.ProcessService { internal class ConfigDependency : Microsoft.Research.Peloponnese.Shared.AssemblyDependencyAttribute { public ConfigDependency() : base("Microsoft.Research.Dryad.ProcessService.exe.config", false) { } } class Service { static private Guid jobGuid; static private string parentAddress; static private string groupName; static private string identifier; static private string hostName; static private string rackName; static bool GetEnvironmentDetails(ILogger logger) { parentAddress = Environment.GetEnvironmentVariable(Constants.EnvManagerServerUri); if (parentAddress == null) { jobGuid = Guid.NewGuid(); groupName = "group"; identifier = "identifier"; return true; } string guidString = Environment.GetEnvironmentVariable(Constants.EnvManagerJobGuid); groupName = Environment.GetEnvironmentVariable(Constants.EnvProcessGroup); identifier = Environment.GetEnvironmentVariable(Constants.EnvProcessIdentifier); hostName = Environment.GetEnvironmentVariable(Constants.EnvProcessHostName); if (guidString == null || groupName == null || identifier == null || hostName == null) { logger.Log("environment variables not present"); return false; } try { jobGuid = Guid.Parse(guidString); } catch (Exception) { logger.Log("bad guid string " + guidString); return false; } rackName = Environment.GetEnvironmentVariable(Constants.EnvProcessRackName); if (rackName == null) { rackName = "DefaultRack"; } return true; } static bool RendezvousWithParent(string processUri, string fileUri, string directory, ILogger logger) { if (parentAddress == null) { // we weren't started from Peloponnese so do nothing return true; } NotHttpClient httpClient = new NotHttpClient(false, 1, 10000, logger); string status; try { var processDetails = new XElement("ProcessUri"); processDetails.Value = processUri; var fileDetails = new XElement("FileUri"); fileDetails.Value = fileUri; var dirDetails = new XElement("LocalDirectory"); dirDetails.Value = directory; var details = new XElement("ProcessDetails"); details.SetAttributeValue("hostname", hostName); details.SetAttributeValue("rackname", rackName); details.Add(processDetails); details.Add(fileDetails); details.Add(dirDetails); status = details.ToString(); } catch (Exception e) { logger.Log("malformed xml: " + e.ToString()); return false; } string registration = String.Format("{0}register?guid={1}&group={2}&identifier={3}", parentAddress, jobGuid.ToString(), groupName, identifier); IHttpRequest request = httpClient.CreateRequest(registration); request.Timeout = 30 * 1000; // if it doesn't respond in 30 seconds we'll throw an exception and quit request.Method = "POST"; try { using (Stream upload = request.GetRequestStream()) { using (StreamWriter sw = new StreamWriter(upload)) { sw.Write(status); } } using (IHttpResponse response = request.GetResponse()) { logger.Log("Server registration succeeded"); return true; } } catch (NotHttpException e) { // if this failed, there's nothing much more we can do logger.Log("Command put failed message " + e.Message + " status " + e.Response.StatusCode + " " + e.Response.StatusDescription); } catch (Exception e) { logger.Log("Command put failed message " + e.Message); } return false; } static void Main(string[] args) { ILogger logger = new SimpleLogger("processservice.log"); logger.Log("startup", "-------- Starting Dryad Process Service --------"); var directory = Directory.GetCurrentDirectory(); if (!GetEnvironmentDetails(logger)) { logger.Log("Failed to read environment variables"); logger.Stop(); return; } XDocument config; try { string configFile = args[0]; logger.Log("Opening config file " + configFile); config = XDocument.Load(configFile); logger.Log("Opened config file " + configFile); } catch (Exception e) { logger.Log("Failed to read config file: " + e.ToString()); logger.Stop(); return; } using (var processService = new ProcessService(logger)) { string processUri; string fileUri; logger.Log("starting process service"); if (processService.Start(config, groupName, identifier, out processUri, out fileUri)) { logger.Log("done starting process service"); if (!RendezvousWithParent(processUri, fileUri, directory, logger)) { processService.ShutDown(); } } else { logger.Log("process service start failed"); } logger.Log("waiting for process service to exit"); processService.WaitForExit(); logger.Log("process service has exited"); } logger.Log("-------- Stopping Dryad Process Service --------"); logger.Stop(); } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Collections; using System.Collections.Generic; /* The AssetBundle Manager provides a High-Level API for working with AssetBundles. The AssetBundle Manager will take care of loading AssetBundles and their associated Asset Dependencies. Initialize() Initializes the AssetBundle manifest object. LoadAssetAsync() Loads a given asset from a given AssetBundle and handles all the dependencies. LoadLevelAsync() Loads a given scene from a given AssetBundle and handles all the dependencies. LoadDependencies() Loads all the dependent AssetBundles for a given AssetBundle. BaseDownloadingURL Sets the base downloading url which is used for automatic downloading dependencies. SimulateAssetBundleInEditor Sets Simulation Mode in the Editor. Variants Sets the active variant. RemapVariantName() Resolves the correct AssetBundle according to the active variant. */ namespace AssetBundles { /// <summary> /// Loaded assetBundle contains the references count which can be used to /// unload dependent assetBundles automatically. /// </summary> public class LoadedAssetBundle { public AssetBundle m_AssetBundle; public int m_ReferencedCount; internal event Action unload; internal void OnUnload() { m_AssetBundle.Unload(false); if (unload != null) unload(); } public LoadedAssetBundle(AssetBundle assetBundle) { m_AssetBundle = assetBundle; m_ReferencedCount = 1; } } /// <summary> /// Class takes care of loading assetBundle and its dependencies /// automatically, loading variants automatically. /// </summary> public class AssetBundleManager : MonoBehaviour { public enum LogMode { All, JustErrors }; public enum LogType { Info, Warning, Error }; static LogMode m_LogMode = LogMode.All; static string m_BaseDownloadingURL = ""; static string[] m_ActiveVariants = {}; static AssetBundleManifest m_AssetBundleManifest = null; #if UNITY_EDITOR static int m_SimulateAssetBundleInEditor = -1; const string kSimulateAssetBundles = "SimulateAssetBundles"; #endif static Dictionary<string, LoadedAssetBundle> m_LoadedAssetBundles = new Dictionary<string, LoadedAssetBundle>(); static Dictionary<string, string> m_DownloadingErrors = new Dictionary<string, string>(); static List<string> m_DownloadingBundles = new List<string>(); static List<AssetBundleLoadOperation> m_InProgressOperations = new List<AssetBundleLoadOperation>(); static Dictionary<string, string[]> m_Dependencies = new Dictionary<string, string[]>(); public static LogMode logMode { get { return m_LogMode; } set { m_LogMode = value; } } /// <summary> /// The base downloading url which is used to generate the full /// downloading url with the assetBundle names. /// </summary> public static string BaseDownloadingURL { get { return m_BaseDownloadingURL; } set { m_BaseDownloadingURL = value; } } public delegate string OverrideBaseDownloadingURLDelegate(string bundleName); /// <summary> /// Implements per-bundle base downloading URL override. /// The subscribers must return null values for unknown bundle names; /// </summary> public static event OverrideBaseDownloadingURLDelegate overrideBaseDownloadingURL; /// <summary> /// Variants which is used to define the active variants. /// </summary> public static string[] ActiveVariants { get { return m_ActiveVariants; } set { m_ActiveVariants = value; } } /// <summary> /// AssetBundleManifest object which can be used to load the dependecies /// and check suitable assetBundle variants. /// </summary> public static AssetBundleManifest AssetBundleManifestObject { set {m_AssetBundleManifest = value; } } private static void Log(LogType logType, string text) { if (logType == LogType.Error) Debug.LogError("[AssetBundleManager] " + text); else if (m_LogMode == LogMode.All && logType == LogType.Warning) Debug.LogWarning("[AssetBundleManager] " + text); else if (m_LogMode == LogMode.All) Debug.Log("[AssetBundleManager] " + text); } #if UNITY_EDITOR /// <summary> /// Flag to indicate if we want to simulate assetBundles in Editor without building them actually. /// </summary> public static bool SimulateAssetBundleInEditor { get { if (m_SimulateAssetBundleInEditor == -1) m_SimulateAssetBundleInEditor = EditorPrefs.GetBool(kSimulateAssetBundles, true) ? 1 : 0; return m_SimulateAssetBundleInEditor != 0; } set { int newValue = value ? 1 : 0; if (newValue != m_SimulateAssetBundleInEditor) { m_SimulateAssetBundleInEditor = newValue; EditorPrefs.SetBool(kSimulateAssetBundles, value); } } } #endif private static string GetStreamingAssetsPath() { if (Application.isEditor) return "file://" + System.Environment.CurrentDirectory.Replace("\\", "/"); // Use the build output folder directly. else if (Application.isWebPlayer) return System.IO.Path.GetDirectoryName(Application.absoluteURL).Replace("\\", "/") + "/StreamingAssets"; else if (Application.isMobilePlatform || Application.isConsolePlatform) return Application.streamingAssetsPath; else // For standalone player. return "file://" + Application.streamingAssetsPath; } /// <summary> /// Sets base downloading URL to a directory relative to the streaming assets directory. /// Asset bundles are loaded from a local directory. /// </summary> public static void SetSourceAssetBundleDirectory(string relativePath) { BaseDownloadingURL = GetStreamingAssetsPath() + relativePath; } /// <summary> /// Sets base downloading URL to a web URL. The directory pointed to by this URL /// on the web-server should have the same structure as the AssetBundles directory /// in the demo project root. /// </summary> /// <example>For example, AssetBundles/iOS/xyz-scene must map to /// absolutePath/iOS/xyz-scene. /// <example> public static void SetSourceAssetBundleURL(string absolutePath) { if (!absolutePath.EndsWith("/")) { absolutePath += "/"; } BaseDownloadingURL = absolutePath + Utility.GetPlatformName() + "/"; } /// <summary> /// Sets base downloading URL to a local development server URL. /// </summary> public static void SetDevelopmentAssetBundleServer() { #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to setup a download URL if (SimulateAssetBundleInEditor) return; #endif TextAsset urlFile = Resources.Load("AssetBundleServerURL") as TextAsset; string url = (urlFile != null) ? urlFile.text.Trim() : null; Debug.Log(url+ "../AssetBundles"); if (url == null || url.Length == 0) { Log(LogType.Error, "Development Server URL could not be found."); } else { AssetBundleManager.SetSourceAssetBundleURL(url); } } /// <summary> /// Retrieves an asset bundle that has previously been requested via LoadAssetBundle. /// Returns null if the asset bundle or one of its dependencies have not been downloaded yet. /// </summary> static public LoadedAssetBundle GetLoadedAssetBundle(string assetBundleName, out string error) { if (m_DownloadingErrors.TryGetValue(assetBundleName, out error)) return null; LoadedAssetBundle bundle = null; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); if (bundle == null) return null; // No dependencies are recorded, only the bundle itself is required. string[] dependencies = null; if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies)) return bundle; // Make sure all dependencies are loaded foreach (var dependency in dependencies) { if (m_DownloadingErrors.TryGetValue(dependency, out error)) return null; // Wait all the dependent assetBundles being loaded. LoadedAssetBundle dependentBundle; m_LoadedAssetBundles.TryGetValue(dependency, out dependentBundle); if (dependentBundle == null) return null; } return bundle; } /// <summary> /// Returns true if certain asset bundle has been downloaded without checking /// whether the dependencies have been loaded. /// </summary> static public bool IsAssetBundleDownloaded(string assetBundleName) { return m_LoadedAssetBundles.ContainsKey(assetBundleName); } /// <summary> /// Initializes asset bundle namager and starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> static public AssetBundleLoadManifestOperation Initialize() { return Initialize(Utility.GetPlatformName()); } /// <summary> /// Initializes asset bundle namager and starts download of manifest asset bundle. /// Returns the manifest asset bundle downolad operation object. /// </summary> static public AssetBundleLoadManifestOperation Initialize(string manifestAssetBundleName) { #if UNITY_EDITOR Log(LogType.Info, "Simulation Mode: " + (SimulateAssetBundleInEditor ? "Enabled" : "Disabled")); #endif var go = new GameObject("AssetBundleManager", typeof(AssetBundleManager)); DontDestroyOnLoad(go); #if UNITY_EDITOR // If we're in Editor simulation mode, we don't need the manifest assetBundle. if (SimulateAssetBundleInEditor) return null; #endif LoadAssetBundle(manifestAssetBundleName, true); var operation = new AssetBundleLoadManifestOperation(manifestAssetBundleName, "AssetBundleManifest", typeof(AssetBundleManifest)); m_InProgressOperations.Add(operation); return operation; } // Temporarily work around a il2cpp bug static protected void LoadAssetBundle(string assetBundleName) { LoadAssetBundle(assetBundleName, false); } // Starts the download of the asset bundle identified by the given name, and asset bundles // that this asset bundle depends on. static protected void LoadAssetBundle(string assetBundleName, bool isLoadingAssetBundleManifest) { Log(LogType.Info, "Loading Asset Bundle " + (isLoadingAssetBundleManifest ? "Manifest: " : ": ") + assetBundleName); #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to really load the assetBundle and its dependencies. if (SimulateAssetBundleInEditor) return; #endif if (!isLoadingAssetBundleManifest) { if (m_AssetBundleManifest == null) { Log(LogType.Error, "Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()"); return; } } // Check if the assetBundle has already been processed. bool isAlreadyProcessed = LoadAssetBundleInternal(assetBundleName, isLoadingAssetBundleManifest); // Load dependencies. if (!isAlreadyProcessed && !isLoadingAssetBundleManifest) LoadDependencies(assetBundleName); } // Returns base downloading URL for the given asset bundle. // This URL may be overridden on per-bundle basis via overrideBaseDownloadingURL event. protected static string GetAssetBundleBaseDownloadingURL(string bundleName) { if (overrideBaseDownloadingURL != null) { foreach (OverrideBaseDownloadingURLDelegate method in overrideBaseDownloadingURL.GetInvocationList()) { string res = method(bundleName); if (res != null) return res; } } return m_BaseDownloadingURL; } // Checks who is responsible for determination of the correct asset bundle variant // that should be loaded on this platform. // // On most platforms, this is done by the AssetBundleManager itself. However, on // certain platforms (iOS at the moment) it's possible that an external asset bundle // variant resolution mechanism is used. In these cases, we use base asset bundle // name (without the variant tag) as the bundle identifier. The platform-specific // code is responsible for correctly loading the bundle. static protected bool UsesExternalBundleVariantResolutionMechanism(string baseAssetBundleName) { #if ENABLE_IOS_APP_SLICING var url = GetAssetBundleBaseDownloadingURL(baseAssetBundleName); if (url.ToLower().StartsWith("res://") || url.ToLower().StartsWith("odr://")) return true; #endif return false; } // Remaps the asset bundle name to the best fitting asset bundle variant. static protected string RemapVariantName(string assetBundleName) { string[] bundlesWithVariant = m_AssetBundleManifest.GetAllAssetBundlesWithVariant(); // Get base bundle name string baseName = assetBundleName.Split('.')[0]; if (UsesExternalBundleVariantResolutionMechanism(baseName)) return baseName; int bestFit = int.MaxValue; int bestFitIndex = -1; // Loop all the assetBundles with variant to find the best fit variant assetBundle. for (int i = 0; i < bundlesWithVariant.Length; i++) { string[] curSplit = bundlesWithVariant[i].Split('.'); string curBaseName = curSplit[0]; string curVariant = curSplit[1]; if (curBaseName != baseName) continue; int found = System.Array.IndexOf(m_ActiveVariants, curVariant); // If there is no active variant found. We still want to use the first if (found == -1) found = int.MaxValue - 1; if (found < bestFit) { bestFit = found; bestFitIndex = i; } } if (bestFit == int.MaxValue - 1) { Log(LogType.Warning, "Ambigious asset bundle variant chosen because there was no matching active variant: " + bundlesWithVariant[bestFitIndex]); } if (bestFitIndex != -1) { return bundlesWithVariant[bestFitIndex]; } else { return assetBundleName; } } // Sets up download operation for the given asset bundle if it's not downloaded already. static protected bool LoadAssetBundleInternal(string assetBundleName, bool isLoadingAssetBundleManifest) { // Already loaded. LoadedAssetBundle bundle = null; m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle); if (bundle != null) { bundle.m_ReferencedCount++; return true; } // @TODO: Do we need to consider the referenced count of WWWs? // In the demo, we never have duplicate WWWs as we wait LoadAssetAsync()/LoadLevelAsync() to be finished before calling another LoadAssetAsync()/LoadLevelAsync(). // But in the real case, users can call LoadAssetAsync()/LoadLevelAsync() several times then wait them to be finished which might have duplicate WWWs. if (m_DownloadingBundles.Contains(assetBundleName)) return true; string bundleBaseDownloadingURL = GetAssetBundleBaseDownloadingURL(assetBundleName); if (bundleBaseDownloadingURL.ToLower().StartsWith("odr://")) { #if ENABLE_IOS_ON_DEMAND_RESOURCES Log(LogType.Info, "Requesting bundle " + assetBundleName + " through ODR"); m_InProgressOperations.Add(new AssetBundleDownloadFromODROperation(assetBundleName)); #else new ApplicationException("Can't load bundle " + assetBundleName + " through ODR: this Unity version or build target doesn't support it."); #endif } else if (bundleBaseDownloadingURL.ToLower().StartsWith("res://")) { #if ENABLE_IOS_APP_SLICING Log(LogType.Info, "Requesting bundle " + assetBundleName + " through asset catalog"); m_InProgressOperations.Add(new AssetBundleOpenFromAssetCatalogOperation(assetBundleName)); #else new ApplicationException("Can't load bundle " + assetBundleName + " through asset catalog: this Unity version or build target doesn't support it."); #endif } else { WWW download = null; if (!bundleBaseDownloadingURL.EndsWith("/")) { bundleBaseDownloadingURL += "/"; } string url = bundleBaseDownloadingURL + assetBundleName; // For manifest assetbundle, always download it as we don't have hash for it. if (isLoadingAssetBundleManifest) download = new WWW(url); else download = WWW.LoadFromCacheOrDownload(url, m_AssetBundleManifest.GetAssetBundleHash(assetBundleName), 0); m_InProgressOperations.Add(new AssetBundleDownloadFromWebOperation(assetBundleName, download)); } m_DownloadingBundles.Add(assetBundleName); return false; } // Where we get all the dependencies and load them all. static protected void LoadDependencies(string assetBundleName) { if (m_AssetBundleManifest == null) { Log(LogType.Error, "Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()"); return; } // Get dependecies from the AssetBundleManifest object.. string[] dependencies = m_AssetBundleManifest.GetAllDependencies(assetBundleName); if (dependencies.Length == 0) return; for (int i = 0; i < dependencies.Length; i++) dependencies[i] = RemapVariantName(dependencies[i]); // Record and load all dependencies. m_Dependencies.Add(assetBundleName, dependencies); for (int i = 0; i < dependencies.Length; i++) LoadAssetBundleInternal(dependencies[i], false); } /// <summary> /// Unloads assetbundle and its dependencies. /// </summary> static public void UnloadAssetBundle(string assetBundleName) { #if UNITY_EDITOR // If we're in Editor simulation mode, we don't have to load the manifest assetBundle. if (SimulateAssetBundleInEditor) return; #endif assetBundleName = RemapVariantName(assetBundleName); UnloadAssetBundleInternal(assetBundleName); UnloadDependencies(assetBundleName); } static protected void UnloadDependencies(string assetBundleName) { string[] dependencies = null; if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies)) return; // Loop dependencies. foreach (var dependency in dependencies) { UnloadAssetBundleInternal(dependency); } m_Dependencies.Remove(assetBundleName); } static protected void UnloadAssetBundleInternal(string assetBundleName) { string error; LoadedAssetBundle bundle = GetLoadedAssetBundle(assetBundleName, out error); if (bundle == null) return; if (--bundle.m_ReferencedCount == 0) { bundle.OnUnload(); m_LoadedAssetBundles.Remove(assetBundleName); Log(LogType.Info, assetBundleName + " has been unloaded successfully"); } } void Update() { // Update all in progress operations for (int i = 0; i < m_InProgressOperations.Count;) { var operation = m_InProgressOperations[i]; if (operation.Update()) { i++; } else { m_InProgressOperations.RemoveAt(i); ProcessFinishedOperation(operation); } } } void ProcessFinishedOperation(AssetBundleLoadOperation operation) { AssetBundleDownloadOperation download = operation as AssetBundleDownloadOperation; if (download == null) return; if (download.error == null) m_LoadedAssetBundles.Add(download.assetBundleName, download.assetBundle); else { string msg = string.Format("Failed downloading bundle {0} from {1}: {2}", download.assetBundleName, download.GetSourceURL(), download.error); m_DownloadingErrors.Add(download.assetBundleName, msg); } m_DownloadingBundles.Remove(download.assetBundleName); } /// <summary> /// Starts a load operation for an asset from the given asset bundle. /// </summary> static public AssetBundleLoadAssetOperation LoadAssetAsync(string assetBundleName, string assetName, System.Type type) { Log(LogType.Info, "Loading " + assetName + " from " + assetBundleName + " bundle"); AssetBundleLoadAssetOperation operation = null; #if UNITY_EDITOR if (SimulateAssetBundleInEditor) { string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, assetName); if (assetPaths.Length == 0) { Log(LogType.Error, "There is no asset with name \"" + assetName + "\" in " + assetBundleName); return null; } // @TODO: Now we only get the main object from the first asset. Should consider type also. UnityEngine.Object target = AssetDatabase.LoadMainAssetAtPath(assetPaths[0]); operation = new AssetBundleLoadAssetOperationSimulation(target); } else #endif { assetBundleName = RemapVariantName(assetBundleName); LoadAssetBundle(assetBundleName); operation = new AssetBundleLoadAssetOperationFull(assetBundleName, assetName, type); m_InProgressOperations.Add(operation); } return operation; } /// <summary> /// Starts a load operation for a level from the given asset bundle. /// </summary> static public AssetBundleLoadOperation LoadLevelAsync(string assetBundleName, string levelName, bool isAdditive) { Log(LogType.Info, "Loading " + levelName + " from " + assetBundleName + " bundle"); AssetBundleLoadOperation operation = null; #if UNITY_EDITOR if (SimulateAssetBundleInEditor) { operation = new AssetBundleLoadLevelSimulationOperation(assetBundleName, levelName, isAdditive); } else #endif { assetBundleName = RemapVariantName(assetBundleName); LoadAssetBundle(assetBundleName); operation = new AssetBundleLoadLevelOperation(assetBundleName, levelName, isAdditive); m_InProgressOperations.Add(operation); } return operation; } } // End of AssetBundleManager. }
#region Header // // Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Autodesk.Revit.DB; namespace RevitLookup.Snoop.Forms { /// <summary> /// Summary description for Object form. /// </summary> public class ParamEnumSnoop : System.Windows.Forms.Form { protected System.Windows.Forms.Button m_bnOK; protected System.Windows.Forms.TreeView m_tvObjs; protected System.Windows.Forms.ContextMenu m_cntxMenuObjId; protected System.Windows.Forms.MenuItem m_mnuItemBrowseReflection; protected System.Windows.Forms.ListView m_lvData; protected System.Windows.Forms.ColumnHeader m_lvCol_label; protected System.Windows.Forms.ColumnHeader m_lvCol_value; protected Snoop.Collectors.CollectorObj m_snoopCollector = new Snoop.Collectors.CollectorObj(); protected System.Object m_curObj; private Hashtable m_enumMap; private ContextMenuStrip listViewContextMenuStrip; private System.Windows.Forms.MenuItem m_mnuItemCopy; private ToolStripMenuItem copyToolStripMenuItem; private ToolStrip toolStrip1; private ToolStripButton toolStripButton1; private ToolStripButton toolStripButton2; private PrintDialog m_printDialog; private System.Drawing.Printing.PrintDocument m_printDocument; private PrintPreviewDialog m_printPreviewDialog; private IContainer components; private Int32[] m_maxWidths; private ToolStripButton toolStripButton3; private Int32 m_currentPrintItem = 0; public ParamEnumSnoop (Hashtable enumMap) { m_enumMap = enumMap; // this constructor is for derived classes to call InitializeComponent(); m_tvObjs.BeginUpdate(); AddParametersToTree(); m_tvObjs.ExpandAll(); m_tvObjs.EndUpdate(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> protected void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ParamEnumSnoop)); this.m_tvObjs = new System.Windows.Forms.TreeView(); this.m_cntxMenuObjId = new System.Windows.Forms.ContextMenu(); this.m_mnuItemCopy = new System.Windows.Forms.MenuItem(); this.m_mnuItemBrowseReflection = new System.Windows.Forms.MenuItem(); this.m_bnOK = new System.Windows.Forms.Button(); this.m_lvData = new System.Windows.Forms.ListView(); this.m_lvCol_label = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.m_lvCol_value = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.listViewContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.m_printDialog = new System.Windows.Forms.PrintDialog(); this.m_printDocument = new System.Drawing.Printing.PrintDocument(); this.m_printPreviewDialog = new System.Windows.Forms.PrintPreviewDialog(); this.listViewContextMenuStrip.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // m_tvObjs // this.m_tvObjs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.m_tvObjs.ContextMenu = this.m_cntxMenuObjId; this.m_tvObjs.HideSelection = false; this.m_tvObjs.Location = new System.Drawing.Point(11, 38); this.m_tvObjs.Name = "m_tvObjs"; this.m_tvObjs.Size = new System.Drawing.Size(248, 415); this.m_tvObjs.TabIndex = 0; this.m_tvObjs.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeNodeSelected); this.m_tvObjs.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.TreeNodeSelected); // // m_cntxMenuObjId // this.m_cntxMenuObjId.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.m_mnuItemCopy, this.m_mnuItemBrowseReflection}); // // m_mnuItemCopy // this.m_mnuItemCopy.Index = 0; this.m_mnuItemCopy.Text = "Copy"; this.m_mnuItemCopy.Click += new System.EventHandler(this.ContextMenuClick_Copy); // // m_mnuItemBrowseReflection // this.m_mnuItemBrowseReflection.Index = 1; this.m_mnuItemBrowseReflection.Text = "Browse Using Reflection..."; this.m_mnuItemBrowseReflection.Click += new System.EventHandler(this.ContextMenuClick_BrowseReflection); // // m_bnOK // this.m_bnOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.m_bnOK.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.m_bnOK.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnOK.Location = new System.Drawing.Point(364, 459); this.m_bnOK.Name = "m_bnOK"; this.m_bnOK.Size = new System.Drawing.Size(75, 23); this.m_bnOK.TabIndex = 2; this.m_bnOK.Text = "OK"; // // m_lvData // this.m_lvData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_lvData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.m_lvCol_label, this.m_lvCol_value}); this.m_lvData.ContextMenuStrip = this.listViewContextMenuStrip; this.m_lvData.FullRowSelect = true; this.m_lvData.GridLines = true; this.m_lvData.Location = new System.Drawing.Point(284, 38); this.m_lvData.Name = "m_lvData"; this.m_lvData.Size = new System.Drawing.Size(504, 415); this.m_lvData.TabIndex = 3; this.m_lvData.UseCompatibleStateImageBehavior = false; this.m_lvData.View = System.Windows.Forms.View.Details; this.m_lvData.Click += new System.EventHandler(this.DataItemSelected); this.m_lvData.DoubleClick += new System.EventHandler(this.DataItemSelected); // // m_lvCol_label // this.m_lvCol_label.Text = "Field"; this.m_lvCol_label.Width = 200; // // m_lvCol_value // this.m_lvCol_value.Text = "Value"; this.m_lvCol_value.Width = 300; // // listViewContextMenuStrip // this.listViewContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.copyToolStripMenuItem}); this.listViewContextMenuStrip.Name = "listViewContextMenuStrip"; this.listViewContextMenuStrip.Size = new System.Drawing.Size(103, 26); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = global::RevitLookup.Properties.Resources.Copy; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(102, 22); this.copyToolStripMenuItem.Text = "Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.CopyToolStripMenuItem_Click); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1, this.toolStripButton2, this.toolStripButton3}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(800, 25); this.toolStrip1.TabIndex = 5; this.toolStrip1.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = global::RevitLookup.Properties.Resources.Print; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "Print"; this.toolStripButton1.Click += new System.EventHandler(this.PrintMenuItem_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = global::RevitLookup.Properties.Resources.Preview; this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.Text = "Print Preview"; this.toolStripButton2.Click += new System.EventHandler(this.PrintPreviewMenuItem_Click); // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = global::RevitLookup.Properties.Resources.Copy; this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Size = new System.Drawing.Size(23, 22); this.toolStripButton3.Text = "Copy To Clipboard"; this.toolStripButton3.Click += new System.EventHandler(this.ContextMenuClick_Copy); // // m_printDialog // this.m_printDialog.Document = this.m_printDocument; this.m_printDialog.UseEXDialog = true; // // m_printDocument // this.m_printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.PrintDocument_PrintPage); // // m_printPreviewDialog // this.m_printPreviewDialog.AutoScrollMargin = new System.Drawing.Size(0, 0); this.m_printPreviewDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0); this.m_printPreviewDialog.ClientSize = new System.Drawing.Size(400, 300); this.m_printPreviewDialog.Document = this.m_printDocument; this.m_printPreviewDialog.Enabled = true; this.m_printPreviewDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("m_printPreviewDialog.Icon"))); this.m_printPreviewDialog.Name = "m_printPreviewDialog"; this.m_printPreviewDialog.Visible = false; // // ParamEnumSnoop // this.AcceptButton = this.m_bnOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.m_bnOK; this.ClientSize = new System.Drawing.Size(800, 489); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.m_bnOK); this.Controls.Add(this.m_tvObjs); this.Controls.Add(this.m_lvData); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(650, 200); this.Name = "ParamEnumSnoop"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Snoop Built-In Parameters"; this.listViewContextMenuStrip.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion protected void AddParametersToTree() { m_tvObjs.Sorted = true; foreach (DictionaryEntry de in m_enumMap) { Parameter tmpObj = (Parameter)de.Value; TreeNode tmpNode = new TreeNode(de.Key.ToString()); tmpNode.Tag = de.Value; m_tvObjs.Nodes.Add(tmpNode); } } #region Events /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void TreeNodeSelected(object sender, System.Windows.Forms.TreeViewEventArgs e) { m_curObj = e.Node.Tag; // collect the data about this object m_snoopCollector.Collect(m_curObj); // display it Snoop.Utils.Display(m_lvData, m_snoopCollector); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void TreeNodeSelected (object sender, System.Windows.Forms.TreeNodeMouseClickEventArgs e) { m_curObj = e.Node.Tag; // collect the data about this object m_snoopCollector.Collect(m_curObj); // display it Snoop.Utils.Display(m_lvData, m_snoopCollector); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DataItemSelected(object sender, System.EventArgs e) { Snoop.Utils.DataItemSelected(m_lvData); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ContextMenuClick_Copy (object sender, System.EventArgs e) { if (m_tvObjs.SelectedNode != null) { Utils.CopyToClipboard(m_lvData); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ContextMenuClick_BrowseReflection(object sender, System.EventArgs e) { Snoop.Utils.BrowseReflection(m_curObj); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CopyToolStripMenuItem_Click (object sender, EventArgs e) { if (m_lvData.SelectedItems.Count > 0) { Utils.CopyToClipboard(m_lvData.SelectedItems[0], false); } else { Clipboard.Clear(); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintMenuItem_Click (object sender, EventArgs e) { Utils.UpdatePrintSettings(m_printDocument, m_tvObjs, m_lvData, ref m_maxWidths); Utils.PrintMenuItemClick(m_printDialog, m_tvObjs); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintPreviewMenuItem_Click (object sender, EventArgs e) { Utils.UpdatePrintSettings(m_printDocument, m_tvObjs, m_lvData, ref m_maxWidths); Utils.PrintPreviewMenuItemClick(m_printPreviewDialog, m_tvObjs); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PrintDocument_PrintPage (object sender, System.Drawing.Printing.PrintPageEventArgs e) { m_currentPrintItem = Utils.Print(m_tvObjs.SelectedNode.Text, m_lvData, e, m_maxWidths[0], m_maxWidths[1], m_currentPrintItem); } #endregion } }
/* Copyright 2006 - 2010 Intel 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.IO; using System.Net; using System.Text; using System.Data; using System.Drawing; using System.Threading; using System.Reflection; using System.Net.Sockets; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using System.Runtime.Serialization; using OpenSource.UPnP; namespace UPnPValidator.BasicTests { /// <summary> /// Tests service event subscription, un-subscription and subscription renewal. /// </summary> [Serializable()] public class UPnPTestInvokeValid : BasicTestGroup { // Generic Test Variables bool WARN_MASTER,WARN_VALID,WARN_ALLOWED,WARN_RANGE; bool FAIL_MASTER,FAIL_VALID,FAIL_ALLOWED,FAIL_RANGE; // Specific Test Variables [NonSerialized()] private ManualResetEvent MRE; public UPnPTestInvokeValid() { Category = "Control"; GroupName = "Invocation Test Suite"; Description = "Action invocation test suite. Includes invoking each action of each service on the target device with valid and invalid values, checking for returned error codes, response time and many other factors."; AddTest("Valid Values",""); AddTest("Allowed Values",""); AddTest("Range",""); Reset(); } public override void Reset() { base.Reset(); if (MRE == null) MRE = new ManualResetEvent(false); } public override void Start(UPnPDevice device) { Reset(); UPnPService[] _S = device.GetServices("urn:"); TotalTime = 0; int CurrentTime = 0; foreach(UPnPService s in _S) { TotalTime += s.Actions.Count*30; } foreach(UPnPService s in _S) { UPnPServiceWatcher W = new UPnPServiceWatcher(s,null,new UPnPServiceWatcher.SniffPacketHandler(SniffPacketSink)); foreach(UPnPAction A in s.Actions) { StartCountDown(CurrentTime,TotalTime); BasicControlTest_ACTION(s,A); AbortCountDown(); CurrentTime += 30; } } if(WARN_VALID && !FAIL_VALID) { Results.Add("Invocations: Valid Values - Had undesirable behavior"); SetState("Valid Values", UPnPTestStates.Warn); } else { if(FAIL_VALID) { Results.Add("Invocations: Valid Values - Failed"); SetState("Valid Values",UPnPTestStates.Failed); } else { Results.Add("Invocations: Valid Values - Passed"); SetState("Valid Values",UPnPTestStates.Pass); } } CurrentTime = 0; foreach(UPnPService s in _S) { UPnPServiceWatcher W = new UPnPServiceWatcher(s,null,new UPnPServiceWatcher.SniffPacketHandler(SniffPacketSink)); foreach(UPnPAction A in s.Actions) { StartCountDown(CurrentTime,TotalTime); BasicControlTest_ACTION_BadAllowedValues(s,A); AbortCountDown(); CurrentTime += 30; } } if(WARN_ALLOWED && !FAIL_ALLOWED) { Results.Add("Invocations: Allowed Values - Had undesirable behavior"); SetState("Allowed Values",UPnPTestStates.Warn); } else { if(FAIL_ALLOWED) { Results.Add("Invocations: Allowed Values - Failed"); SetState("Allowed Values",UPnPTestStates.Failed); } else { Results.Add("Invocations: Allowed Values - Passed"); SetState("Allowed Values",UPnPTestStates.Pass); } } CurrentTime = 0; foreach(UPnPService s in _S) { UPnPServiceWatcher W = new UPnPServiceWatcher(s,null,new UPnPServiceWatcher.SniffPacketHandler(SniffPacketSink)); foreach(UPnPAction A in s.Actions) { StartCountDown(CurrentTime,TotalTime); BasicControlTest_ACTION_BadRange(s,A); AbortCountDown(); CurrentTime += 30; } } if(WARN_RANGE && !FAIL_RANGE) { Results.Add("Invocations: Range - Had undesirable behavior"); SetState("Range",UPnPTestStates.Warn); } else { if(FAIL_RANGE) { Results.Add("Invocations: Range - Failed"); SetState("Range",UPnPTestStates.Failed); } else { Results.Add("Invocations: Range - Passed"); SetState("Range",UPnPTestStates.Pass); } } WARN_MASTER = WARN_VALID||WARN_ALLOWED||WARN_RANGE; FAIL_MASTER = FAIL_VALID||FAIL_ALLOWED||FAIL_RANGE; if(WARN_MASTER && !FAIL_MASTER) { state = UPnPTestStates.Warn; } else { if(FAIL_MASTER) { state = UPnPTestStates.Failed; } else { state = UPnPTestStates.Pass; } } SetProgress(100); } private void SniffPacketSink(UPnPServiceWatcher sender, HTTPMessage MSG) { AddPacket(MSG); } private bool BasicControlTest_ACTION(UPnPService s, UPnPAction A) { ArrayList ArgList = BasicControlTest_BuildActionArgs(A); try { s.InvokeSync(A.Name,(UPnPArgument[])ArgList.ToArray(typeof(UPnPArgument))); AddEvent(LogImportance.Remark,"Valid Values","Invoke: " + A.Name + " << OK >>"); } catch(UPnPInvokeException ex) { if(ex.UPNP.ErrorCode==401 || ex.UPNP.ErrorCode==402) { // Oh really? WARN_VALID = true; AddEvent(LogImportance.High,"Valid Values", " Invoke: " + A.Name); AddEvent(LogImportance.High,"Valid Values", " Cannot return Error Code " + ex.UPNP.ErrorCode.ToString()); foreach(UPnPArgument _arg in ex.Arguments) { AddEvent(LogImportance.High,"Valid Values", " " + _arg.Name + ": " + UPnPService.SerializeObjectInstance(_arg.DataValue)); } } else { // Fine, I suppose AddEvent(LogImportance.Remark,"Valid Values", "Invoke: " + A.Name + " << " + ex.UPNP.ErrorCode + " " + ex.UPNP.ErrorDescription + " OK >>"); } } return true; } private bool BasicControlTest_ACTION_BadRange(UPnPService s, UPnPAction A) { (new UPnPDebugObject(s)).SetProperty("ValidationMode",false); ArrayList ArgList = null; foreach(UPnPArgument arg in A.ArgumentList) { if(arg.IsReturnValue==false && arg.Direction=="in") { if(arg.RelatedStateVar.Maximum!=null || arg.RelatedStateVar.Minimum!=null) { ArgList = BasicControlTest_BuildActionArgs(A); for(int i=0;i<ArgList.Count;++i) { if(((UPnPArgument)ArgList[i]).Name==arg.Name) { if(arg.RelatedStateVar.Minimum!=null) { FieldInfo mi = arg.RelatedStateVar.GetNetType().GetField("MinValue"); if(mi.GetValue(null).ToString()!=arg.RelatedStateVar.Minimum.ToString()) { ((UPnPArgument)ArgList[i]).DataValue = mi.GetValue(null); AddEvent(LogImportance.Remark,"Range","Invoke <<" + arg.Name + " value too small>> " + A.Name); try { s.InvokeSync(A.Name,(UPnPArgument[])ArgList.ToArray(typeof(UPnPArgument))); WARN_RANGE = true; AddEvent(LogImportance.High,"Range"," Device failed to validate argument"); } catch(UPnPInvokeException ex) { if(ex.UPNP!=null) { if(ex.UPNP.ErrorCode<501) { AddEvent(LogImportance.Remark,"Range"," Device SUCCESSFULLY validated argument"); } else { WARN_RANGE = true; AddEvent(LogImportance.High,"Range"," Device returned code: " + ex.UPNP.ErrorCode.ToString() + " but failed to validate argument"); } } else { FAIL_RANGE = true; AddEvent(LogImportance.Critical,"Range"," Device returned non SOAP-Encoded Error"); } } } } if(arg.RelatedStateVar.Maximum!=null) { FieldInfo mi = arg.RelatedStateVar.GetNetType().GetField("MaxValue"); if(mi.GetValue(null).ToString()!=arg.RelatedStateVar.Maximum.ToString()) { ((UPnPArgument)ArgList[i]).DataValue = mi.GetValue(null); AddEvent(LogImportance.Remark,"Range","Invoke <<" + arg.Name + " value too big>> " + A.Name); try { s.InvokeSync(A.Name,(UPnPArgument[])ArgList.ToArray(typeof(UPnPArgument))); WARN_RANGE = true; AddEvent(LogImportance.High,"Range"," Device failed to validate argument"); } catch(UPnPInvokeException ex) { if(ex.UPNP!=null) { if(ex.UPNP.ErrorCode<501) { AddEvent(LogImportance.Remark,"Range"," Device SUCCESSFULLY validated argument"); } else { WARN_RANGE = true; AddEvent(LogImportance.High,"Range"," Device returned code: " + ex.UPNP.ErrorCode.ToString() + " but failed to validate argument"); } } else { FAIL_RANGE = true; AddEvent(LogImportance.Critical,"Range"," Device returned non SOAP-Encoded Error"); } } } } } } } } } (new UPnPDebugObject(s)).SetProperty("ValidationMode",true); return true; } private ArrayList BasicControlTest_BuildActionArgs(UPnPAction A) { ArrayList ArgList = new ArrayList(); foreach(UPnPArgument arg in A.ArgumentList) { if(arg.IsReturnValue==false) { UPnPArgument NArg; // if(arg.RelatedStateVar.GetNetType().FullName=="System.String") // { // NArg = new UPnPArgument(arg.Name,"Sample String"); // } // else // { NArg = new UPnPArgument(arg.Name,UPnPService.CreateObjectInstance(arg.RelatedStateVar.GetNetType(),null)); // } if(arg.RelatedStateVar.AllowedStringValues!=null) NArg.DataValue = arg.RelatedStateVar.AllowedStringValues[0]; if(arg.RelatedStateVar.Minimum!=null) NArg.DataValue = arg.RelatedStateVar.Minimum; if(arg.RelatedStateVar.Maximum!=null) NArg.DataValue = arg.RelatedStateVar.Maximum; ArgList.Add(NArg); } } return(ArgList); } private bool BasicControlTest_ACTION_BadAllowedValues(UPnPService s, UPnPAction A) { (new UPnPDebugObject(s)).SetProperty("ValidationMode",false); ArrayList ArgList = null; foreach(UPnPArgument arg in A.ArgumentList) { if(arg.IsReturnValue==false && arg.Direction=="in") { if(arg.RelatedStateVar.AllowedStringValues!=null) { ArgList = BasicControlTest_BuildActionArgs(A); for(int i=0;i<ArgList.Count;++i) { if(((UPnPArgument)ArgList[i]).Name==arg.Name) { string val = "!@#$"; bool OK = true; do { OK = true; for(int j=0;j<arg.RelatedStateVar.AllowedStringValues.Length;++j) { if(val==arg.RelatedStateVar.AllowedStringValues[j]) { OK = false; break; } } if(OK==false) val += val; }while (OK==false); ((UPnPArgument)ArgList[i]).DataValue = val; AddEvent(LogImportance.Remark,"Allowed Values","Invoke <<Bad " + arg.Name + ">> " + A.Name); try { s.InvokeSync(A.Name,(UPnPArgument[])ArgList.ToArray(typeof(UPnPArgument))); WARN_ALLOWED = true; AddEvent(LogImportance.High,"Allowed Values"," Device failed to validate argument"); } catch(UPnPInvokeException ex) { if(ex.UPNP!=null) { if(ex.UPNP.ErrorCode<501) { AddEvent(LogImportance.Remark,"Allowed Values"," Device SUCCESSFULLY validated argument"); } else { WARN_ALLOWED = true; AddEvent(LogImportance.Remark,"Allowed Values"," Device returned code: " + ex.UPNP.ErrorCode.ToString() + " but failed to validate argument"); } } else { FAIL_ALLOWED = true; AddEvent(LogImportance.Critical,"Allowed Values"," Device returned non SOAP-Encoded Error"); } } } } } } } (new UPnPDebugObject(s)).SetProperty("ValidationMode",true); return true; } private void AddHTTPMessage(HTTPMessage msg) { AddPacket(msg); } } }
// 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. //--------------------------------------------------------------------------- // // Description: // // File service for the input source files in a build task. // // The service does something like below: // // return stream for a given source file, // get last modification time in memory or disk. // // or get the link metadata part of a source file. // // It returns above information no matter the task is hosted // inside VS or not. // //--------------------------------------------------------------------------- using System; using System.IO; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks.Windows; using System.Diagnostics; using System.Text; using System.Security.Cryptography; namespace MS.Internal { // // Declaration of interface ITaskFileService // internal interface ITaskFileService { // // Get content stream for a given source file // Stream GetContent(string srcFile); // // Get MD5 Check Sum for a given source file // byte[] GetChecksum(string srcFile, Guid hashGuid); // // Get the last modificatin time for a given file. // DateTime GetLastChangeTime(string srcFile); // // Checks to see if file exists // bool Exists(string fileName); // // Deletes the specified file // void Delete(string fileName); // // Save content stream for the given destination file // void WriteFile(byte[] contentArray, string destinationFile); // // Save content stream for the given generated code file. // This function decides which extension to use for the file // and whether to put it into memory or merely write it to // disk based on whether it is a real build or an intellisense // build operation. It also takes care of deleting the corresponding // unused generated file (i.e. if real build then it deletes // the intellisense file otherwise it deletes the non-intellisense // file. // NOTE: UTF8 BOM should not be added to the contentArray. This // method adds BOM before writing file to disk. // void WriteGeneratedCodeFile(byte[] contentArray, string destinationFileBaseName, string generatedExtension, string intellisenseGeneratedExtension, string languageSourceExtension); // // Determines if this is a real build operation or an // intellisense build operation // bool IsRealBuild {get;} // // Determines if this is running in VS or MsBuild // bool IsRunningInVS { get; } } // // TaskFileService class // // This class can be used by different build tasks to get source file // service, the instance is created by those build tasks when task's // Execute( ) method is called. // internal class TaskFileService : MarshalByRefObject, ITaskFileService { // // Ctor // public TaskFileService(Task buildTask) { _buildTask = buildTask; _hostFileManager = null; _isRealBuild = null; } #region ITaskFileService // // Get content stream for a given source file, the content could // come from memory or disk based on the build host environment. // // It is the caller's responsibility to close the stream. // public Stream GetContent(string srcFile) { Stream fileStream = null; if (String.IsNullOrEmpty(srcFile)) { throw new ArgumentNullException(nameof(srcFile)); } if (HostFileManager != null) { // // Build Host environment has a FileManager, use it to get // file content from edit buffer in memory. GetFileContents // removes the BOM before returning the string. // string strFileContent = HostFileManager.GetFileContents(srcFile); // IVsMsBuildTaskFileManager.GetFileContents should never return null. // GetBytes might throw when input is null, but that should be fine. // // For xaml file, UTF8 is the standard encoding // UTF8Encoding utf8Encoding = new UTF8Encoding(); byte[] baFileContent = utf8Encoding.GetBytes(strFileContent); fileStream = new MemoryStream(baFileContent); } else { fileStream = File.OpenRead(srcFile); } return fileStream; } public byte[] GetChecksum(string fileName, Guid hashGuid) { byte[] hashData=null; if (HostFileManager != null) { object docData = HostFileManager.GetFileDocData(fileName); IPersistFileCheckSum fileChecksummer = docData as IPersistFileCheckSum; if (fileChecksummer != null) { byte[] tempBytes = new byte[1024]; int actualSize; fileChecksummer.CalculateCheckSum(hashGuid, tempBytes.Length, tempBytes, out actualSize); hashData = new byte[actualSize]; for (int i = 0; i < actualSize; i++) { hashData[i] = tempBytes[i]; } } } if (hashData == null) { HashAlgorithm hashAlgorithm; if (hashGuid == s_hashSHA256Guid) { hashAlgorithm = SHA256.Create(); } else if (hashGuid == s_hashSHA1Guid) { hashAlgorithm = SHA1.Create(); } else if (hashGuid == s_hashMD5Guid) { hashAlgorithm = MD5.Create(); } else { hashAlgorithm = null; } if (hashAlgorithm != null) { using (Stream fileStream = File.OpenRead(fileName)) { hashData = hashAlgorithm.ComputeHash(fileStream); } } } return hashData; } // // Get the last modificatin time for a given file. // public DateTime GetLastChangeTime(string srcFile) { DateTime lastChangeDT = new DateTime(0); if (String.IsNullOrEmpty(srcFile)) { throw new ArgumentNullException(nameof(srcFile)); } if (IsFileInHostManager(srcFile)) { long fileTime = HostFileManager.GetFileLastChangeTime(srcFile); lastChangeDT = DateTime.FromFileTime(fileTime); } else { lastChangeDT = File.GetLastWriteTime(srcFile); } return lastChangeDT; } // // Checks to see if file exists // public bool Exists(string fileName) { bool fileExists = false; if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } if (HostFileManager != null) { fileExists = HostFileManager.Exists(fileName, IsRealBuild); } else { fileExists = File.Exists(fileName); } return fileExists; } // // Deletes the specified file // public void Delete(string fileName) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } if (IsFileInHostManager(fileName)) { HostFileManager.Delete(fileName); } else { File.Delete(fileName); } } // // Save content stream for the given destination file // UTF8 BOM should not be added to the contentArray. This // method adds BOM before writing file to disk. // public void WriteFile(byte[] contentArray, string destinationFile) { if (String.IsNullOrEmpty(destinationFile)) { throw new ArgumentNullException(nameof(destinationFile)); } if (contentArray == null) { throw new ArgumentNullException(nameof(contentArray)); } UTF8Encoding utf8Encoding = new UTF8Encoding(); string contentStr = utf8Encoding.GetString(contentArray); if (IsFileInHostManager(destinationFile)) { // PutGeneratedFileContents adds BOM to the file when saving // to memory or disk. HostFileManager.PutGeneratedFileContents(destinationFile, contentStr); } else { // Add BOM for UTF8Encoding since the input contentArray is not supposed to // have it already. using (StreamWriter sw = new StreamWriter(destinationFile, false, new UTF8Encoding(true))) { sw.WriteLine(contentStr); } } } // Save content stream for the given generated code file. // This function decides which extension to use for the file // and whether to put it into memory or merely write it to // disk based on whether it is a real build or an intellisense // build operation. It also takes care of deleting the corresponding // unused generated file (i.e. if real build then it deletes // the intellisense file otherwise it deletes the non-intellisense // file. // NOTE: UTF8 BOM should not be added to the contentArray. This // method adds BOM before writing file to disk. // public void WriteGeneratedCodeFile(byte[] contentArray, string destinationFileBaseName, string generatedExtension, string intellisenseGeneratedExtension, string languageSourceExtension) { if (String.IsNullOrEmpty(destinationFileBaseName)) { throw new ArgumentNullException(nameof(destinationFileBaseName)); } if (contentArray == null) { throw new ArgumentNullException(nameof(contentArray)); } string buildFile = destinationFileBaseName + generatedExtension + languageSourceExtension; string intelFile = destinationFileBaseName + intellisenseGeneratedExtension + languageSourceExtension; string destinationFile = IsRealBuild ? buildFile : intelFile; UTF8Encoding utf8Encoding = new UTF8Encoding(); string contentStr = utf8Encoding.GetString(contentArray); // Add BOM for UTF8Encoding since the input contentArray is not supposed to // have it already. using (StreamWriter sw = new StreamWriter(destinationFile, false, new UTF8Encoding(true))) { sw.WriteLine(contentStr); } if (IsRealBuild && IsRunningInVS) { File.Copy(buildFile, intelFile, /*overwrite*/ true); } } // // Tells if this is an intellisense build or a real build. // Caching the result since this is called a lot of times. // public bool IsRealBuild { get { if (_isRealBuild == null) { bool isRealBuild = true; if (HostFileManager != null) { isRealBuild = HostFileManager.IsRealBuildOperation(); } _isRealBuild = isRealBuild; } return _isRealBuild.Value; } } public bool IsRunningInVS { get { MarkupCompilePass1 pass1; return (HostFileManager != null) || ( (pass1 = _buildTask as MarkupCompilePass1) != null && pass1.IsRunningInVisualStudio); } } #endregion ITaskFileService #region private property // // Get the FileManager implemented by the Host system // private IVsMSBuildTaskFileManager HostFileManager { get { if (_hostFileManager == null) { if (_buildTask != null && _buildTask.HostObject != null) { _hostFileManager = _buildTask.HostObject as IVsMSBuildTaskFileManager; } } return _hostFileManager; } } private bool IsFileInHostManager(string destinationFile) { if (HostFileManager != null && null != HostFileManager.GetFileDocData(destinationFile)) { return true; } return false; } #endregion private property #region private data field private Task _buildTask; private IVsMSBuildTaskFileManager _hostFileManager; private Nullable<bool> _isRealBuild; private static Guid s_hashSHA256Guid = new Guid(0x8829d00f, 0x11b8, 0x4213, 0x87, 0x8b, 0x77, 0x0e, 0x85, 0x97, 0xac, 0x16); private static Guid s_hashSHA1Guid = new Guid(0xff1816ec, 0xaa5e, 0x4d10, 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60); private static Guid s_hashMD5Guid = new Guid(0x406ea660, 0x64cf, 0x4c82, 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99); #endregion private data field } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancersOperations operations. /// </summary> internal partial class LoadBalancersOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancersOperations { /// <summary> /// Initializes a new instance of the LoadBalancersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancersOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace Hjson { internal abstract class BaseReader { string buffer; TextReader r; StringBuilder sb=new StringBuilder(); StringBuilder white=new StringBuilder(); // peek could be removed since we now use a buffer List<int> peek=new List<int>(); bool prevLf; public int Line { get; private set; } public int Column { get; private set; } protected IJsonReader Reader { get; private set; } protected bool HasReader { get { return Reader!=null; } } public bool ReadWsc { get; set; } public BaseReader(TextReader reader, IJsonReader jsonReader) { if (reader==null) throw new ArgumentNullException("reader"); // use a buffer so we can support reset this.Reader=jsonReader; buffer=reader.ReadToEnd(); Reset(); } public void Reset() { Line=1; this.r=new StringReader(buffer); peek.Clear(); white.Length=sb.Length=0; prevLf=false; } public int PeekChar(int idx=0) { if (idx<0) throw new ArgumentOutOfRangeException(); while (idx>=peek.Count) { int c=r.Read(); if (c<0) return c; peek.Add(c); } return peek[idx]; } public virtual int SkipPeekChar() { SkipWhite(); return PeekChar(); } public int ReadChar() { int v; if (peek.Count>0) { // normally peek will only hold not more than one character so this should not matter for performance v=peek[0]; peek.RemoveAt(0); } else v=r.Read(); if (ReadWsc && v!='\r') white.Append((char)v); if (prevLf) { Line++; Column=0; prevLf=false; } if (v=='\n') prevLf=true; Column++; return v; } protected void ResetWhite() { if (ReadWsc) white.Length=0; } protected virtual string GetWhite() { if (!ReadWsc) throw new InvalidOperationException(); return white.ToString(); } public static bool IsWhite(char c) { return c==' ' || c=='\t' || c=='\r' || c=='\n'; } public void SkipWhite() { for (; ; ) { if (IsWhite((char)PeekChar())) ReadChar(); else break; } } // It could return either long or double, depending on the parsed value. public JsonValue ReadNumericLiteral() { int c, leadingZeros=0; double val=0; bool negative=false, testLeading=true; if (PeekChar()=='-') { negative=true; ReadChar(); if (PeekChar()<0) throw ParseError("Invalid JSON numeric literal; extra negation"); } for (int x=0; ; x++) { c=PeekChar(); if (c<'0' || c>'9') break; if (testLeading) { if (c=='0') leadingZeros++; else testLeading = false; } val=val*10+(c-'0'); ReadChar(); } if (testLeading) leadingZeros--; // single 0 is allowed if (leadingZeros>0) throw ParseError("leading multiple zeros are not allowed"); // fraction if (PeekChar()=='.') { int fdigits=0; double frac=0; ReadChar(); if (PeekChar()<0) throw ParseError("Invalid JSON numeric literal; extra dot"); double d=10; for (; ; ) { c=PeekChar(); if (c<'0' || '9'<c) break; ReadChar(); frac+=(c-'0')/d; d*=10; fdigits++; } if (fdigits==0) throw ParseError("Invalid JSON numeric literal; extra dot"); val+=frac; } c=PeekChar(); if (c=='e' || c=='E') { // exponent int exp=0, expSign=1; ReadChar(); if (PeekChar()<0) throw new ArgumentException("Invalid JSON numeric literal; incomplete exponent"); c=PeekChar(); if (c=='-') { ReadChar(); expSign=-1; } else if (c=='+') ReadChar(); if (PeekChar()<0) throw ParseError("Invalid JSON numeric literal; incomplete exponent"); for (; ; ) { c=PeekChar(); if (c<'0' || c>'9') break; exp=exp*10+(c-'0'); ReadChar(); } if (exp!=0) val*=Math.Pow(10, exp*expSign); } if (negative) val*=-1; long lval=(long)val; if (lval==val) return lval; else return val; } public string ReadStringLiteral(Func<string> allowML) { // callers make sure that (exitCh == '"' || exitCh == "'") int exitCh=ReadChar(); sb.Length=0; for (; ; ) { int c=ReadChar(); if (c<0) throw ParseError("JSON string is not closed"); if (c==exitCh) { if (allowML!=null && exitCh=='\'' && PeekChar()=='\'' && sb.Length==0) { // ''' indicates a multiline string ReadChar(); return allowML(); } else return sb.ToString(); } else if (c=='\n' || c=='\r') { throw ParseError("Bad string containing newline"); } else if (c!='\\') { sb.Append((char)c); continue; } // escaped expression c=ReadChar(); if (c<0) throw ParseError("Invalid JSON string literal; incomplete escape sequence"); switch (c) { case '"': case '\'': case '\\': case '/': sb.Append((char)c); break; case 'b': sb.Append('\x8'); break; case 'f': sb.Append('\f'); break; case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case 'u': ushort cp=0; for (int i=0; i<4; i++) { cp <<= 4; if ((c=ReadChar())<0) throw ParseError("Incomplete unicode character escape literal"); if (c>='0' && c<='9') cp+=(ushort)(c-'0'); else if (c>='A' && c<='F') cp+=(ushort)(c-'A'+10); else if (c>='a' && c<='f') cp+=(ushort)(c-'a'+10); else throw ParseError("Bad \\u char "+(char)c); } sb.Append((char)cp); break; default: throw ParseError("Invalid JSON string literal; unexpected escape character"); } } } public void Expect(char expected) { int c; if ((c=ReadChar())!=expected) throw ParseError(String.Format("Expected '{0}', got '{1}'", expected, (char)c)); } public void Expect(string expected) { for (int i=0; i<expected.Length; i++) if (ReadChar()!=expected[i]) throw ParseError(String.Format("Expected '{0}', differed at {1}", expected, i)); } public Exception ParseError(string msg) { return new ArgumentException(String.Format("{0}. At line {1}, column {2}", msg, Line, Column)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ElementAtQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// ElementAt just retrieves an element at a specific index. There is some cross-partition /// coordination to force partitions to stop looking once a partition has found the /// sought-after element. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ElementAtQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { private readonly int _index; // The index that we're looking for. private readonly bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private readonly bool _limitsParallelism = false; // Whether this operator limits parallelism //--------------------------------------------------------------------------------------- // Constructs a new instance of the contains search operator. // // Arguments: // child - the child tree to enumerate. // index - index we are searching for. // internal ElementAtQueryOperator(IEnumerable<TSource> child, int index) : base(child) { Contract.Assert(child != null, "child data source cannot be null"); Contract.Assert(index >= 0, "index can't be less than 0"); _index = index; OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct)) { _prematureMerge = true; _limitsParallelism = childIndexState != OrdinalIndexState.Shuffled; } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open( QuerySettings settings, bool preferStriping) { // We just open the child operator. QueryResults<TSource> childQueryResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { // If the child OOP index is not correct, reindex. int partitionCount = inputStream.PartitionCount; PartitionedStream<TSource, int> intKeyStream; if (_prematureMerge) { intKeyStream = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream(); Contract.Assert(intKeyStream.OrdinalIndexState == OrdinalIndexState.Indexible); } else { intKeyStream = (PartitionedStream<TSource, int>)(object)inputStream; } // Create a shared cancelation variable and then return a possibly wrapped new enumerator. Shared<bool> resultFoundFlag = new Shared<bool>(false); PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>( partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ElementAtQueryOperatorEnumerator(intKeyStream[i], _index, resultFoundFlag, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { Contract.Assert(false, "This method should never be called as fallback to sequential is handled in Aggregate()."); throw new NotSupportedException(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } /// <summary> /// Executes the query, either sequentially or in parallel, depending on the query execution mode and /// whether a premature merge was inserted by this ElementAt operator. /// </summary> /// <param name="result">result</param> /// <param name="withDefaultValue">withDefaultValue</param> /// <returns>whether an element with this index exists</returns> internal bool Aggregate(out TSource result, bool withDefaultValue) { // If we were to insert a premature merge before this ElementAt, and we are executing in conservative mode, run the whole query // sequentially. if (LimitsParallelism && SpecifiedQuerySettings.WithDefaults().ExecutionMode.Value != ParallelExecutionMode.ForceParallelism) { CancellationState cancelState = SpecifiedQuerySettings.CancellationState; if (withDefaultValue) { IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken); IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken); result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAtOrDefault(_index); } else { IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken); IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken); result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAt(_index); } return true; } using (IEnumerator<TSource> e = GetEnumerator(ParallelMergeOptions.FullyBuffered)) { if (e.MoveNext()) { TSource current = e.Current; Contract.Assert(!e.MoveNext(), "expected enumerator to be empty"); result = current; return true; } } result = default(TSource); return false; } //--------------------------------------------------------------------------------------- // This enumerator performs the search for the element at the specified index. // class ElementAtQueryOperatorEnumerator : QueryOperatorEnumerator<TSource, int> { private QueryOperatorEnumerator<TSource, int> _source; // The source data. private int _index; // The index of the element to seek. private Shared<bool> _resultFoundFlag; // Whether to cancel the operation. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new any/all search operator. // internal ElementAtQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, int> source, int index, Shared<bool> resultFoundFlag, CancellationToken cancellationToken) { Contract.Assert(source != null); Contract.Assert(index >= 0); Contract.Assert(resultFoundFlag != null); _source = source; _index = index; _resultFoundFlag = resultFoundFlag; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Enumerates the entire input until the element with the specified is found or another // partition has signaled that it found the element. // internal override bool MoveNext(ref TSource currentElement, ref int currentKey) { // Just walk the enumerator until we've found the element. int i = 0; while (_source.MoveNext(ref currentElement, ref currentKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); if (_resultFoundFlag.Value) { // Another partition found the element. break; } if (currentKey == _index) { // We have found the element. Cancel other searches and return true. _resultFoundFlag.Value = true; return true; } } return false; } protected override void Dispose(bool disposing) { Contract.Assert(_source != null); _source.Dispose(); } } } }
//----------------------------------------------------------------------------- // TouchThumbsticksGame.cs // // Microsoft Advanced Technology Group // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; namespace TouchThumbsticks { /// <summary> /// This sample demonstrates using the touchscreen as a virtual thumbstick control. Each half /// of the screen behaves as a virtual thumbstick. When the player touches the screen, their /// first point of contact defines the center position; then they can drag away from there /// to move the stick. /// </summary> public class TouchThumbsticksGame : Game { #region Game Constants // desired width of backbuffer private const int graphicsWidth = 800; // desired height of backbuffer private const int graphicsHeight = 480; // half of the backbuffer width used for spawning enemies and creating stars private const int graphicsWidthHalf = graphicsWidth / 2; // half of the backbuffer height used for spawning enemies and creating stars private const int graphicsHeightHalf = graphicsHeight / 2; // the width of the in-game world private const int worldWidth = 1000; // the height of the in-game world private const int worldHeight = 1000; // the number of stars in the background private const int numStars = 1000; // the thickness of our graphical world border private const int worldBorderThickness = 4; // double the world border thickness used for positioning the border private const int worldBorderThicknessDouble = worldBorderThickness * 2; #endregion #region Fields // the length of time between spawning enemies private TimeSpan spawnRate = TimeSpan.FromSeconds(2); // color used to draw the world border private Color worldBorderColor = Color.Red; // create a single Random instance for the game private static readonly Random rand = new Random(); // a SpriteBatch for drawing everything private SpriteBatch spriteBatch; // a blank 1x1 texture we use for drawing stars and the world border private Texture2D blank; // a texture used to draw the virtual thumbsticks on the screen private Texture2D thumbstick; // a timer used for spawning enemies private TimeSpan spawnTimer; // a list of all the points for our stars. we use the Z component of the // Vector3 to hold the size of the star. private List<Vector3> stars = new List<Vector3>(); // the player's ship private PlayerShip player; // a list of the active enemies private List<EnemyShip> enemies = new List<EnemyShip>(); #endregion #region Initialization public TouchThumbsticksGame() { new GraphicsDeviceManager(this) { PreferredBackBufferHeight = graphicsHeight, PreferredBackBufferWidth = graphicsWidth, // we only want to be fullscreen on the phone to get rid // of the status bar at the top. #if WINDOWS_PHONE IsFullScreen = true #endif }; Content.RootDirectory = "Content"; TargetElapsedTime = TimeSpan.FromTicks(333333); } protected override void LoadContent() { // create the SpriteBatch for our game spriteBatch = new SpriteBatch(GraphicsDevice); // load in our textures Bullet.Texture = Content.Load<Texture2D>("bullet"); thumbstick = Content.Load<Texture2D>("thumbstick"); // create the player's ship player = new PlayerShip(Content.Load<Texture2D>("player1")); // set the player's world bounds player.WorldWidth = worldWidth; player.WorldHeight = worldHeight; // create our 1x1 blank texture blank = new Texture2D(GraphicsDevice, 1, 1); blank.SetData(new[] { Color.White }); // randomly create all of our stars for (int i = 0; i < numStars; i++) { stars.Add(new Vector3( (float)rand.NextDouble() * (worldWidth + graphicsWidth) - (worldWidth / 2f + graphicsWidthHalf), (float)rand.NextDouble() * (worldWidth + graphicsHeight) - (worldWidth / 2f + graphicsHeightHalf), rand.Next(1, 3))); } } #endregion #region Update protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // update our virtual thumbsticks VirtualThumbsticks.Update(); // countdown until we spawn more enemies spawnTimer -= gameTime.ElapsedGameTime; if (spawnTimer <= TimeSpan.Zero) { // we spawn 1-3 enemies per spawn int numToSpawn = rand.Next(1, 3); for (int i = 0; i < numToSpawn; i++) { // create the enemy EnemyShip enemy = new EnemyShip(Content.Load<Texture2D>("alien")); // target the player's ship enemy.Player = player; // we randomly pick either the left or right side of the screen // to place the enemy if (rand.Next() % 2 == 0) { enemy.Position.X = -worldWidth / 2f - (graphicsWidthHalf + 10); } else { enemy.Position.X = worldWidth / 2f + (graphicsWidthHalf + 10); } // we randomly pick either the top or bottom side of the screen // to place the enemy if (rand.Next() % 2 == 0) { enemy.Position.Y = -worldHeight / 2f - (graphicsHeightHalf + 10); } else { enemy.Position.Y = worldHeight / 2f + (graphicsHeightHalf + 10); } // add the enemy to our list enemies.Add(enemy); } // reset our timer spawnTimer = spawnRate; } // update the player player.Update(gameTime); // update all the enemies foreach (var enemy in enemies) enemy.Update(gameTime); // create a couple lists to hold the bullets and enemies // we need to remove due to collisions List<Bullet> bulletsToRemove = new List<Bullet>(); List<EnemyShip> enemiesToRemove = new List<EnemyShip>(); // figure out what bullets and enemies are colliding foreach (var b in player.Bullets) { foreach (var e in enemies) { // check if the enemy contains the bullet's position if (e.ContainsPoint(b.Position)) { // add the bullet and enemy to the lists to be removed bulletsToRemove.Add(b); enemiesToRemove.Add(e); // break the inner loop so bullets only collide // with one enemy break; } } } // remove all marked bullets and enemies foreach (var b in bulletsToRemove) player.Bullets.Remove(b); foreach (var e in enemiesToRemove) enemies.Remove(e); base.Update(gameTime); } #endregion #region Draw protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // figure out a camera transformation based on the player's position Matrix cameraTransform = Matrix.CreateTranslation( -player.Position.X + graphicsWidthHalf, -player.Position.Y + graphicsHeightHalf, 0f); // begin drawing with SpriteBatch using our camera transformation spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, null, cameraTransform); // draw all the stars foreach (var star in stars) { spriteBatch.Draw(blank, new Rectangle((int)star.X, (int)star.Y, (int)star.Z, (int)star.Z), Color.White); } // draw the world borders DrawWorldBorder(); // draw all of the enemies foreach (var enemy in enemies) enemy.Draw(spriteBatch); // draw the player (which draws the bullets) player.Draw(spriteBatch); spriteBatch.End(); // begin a new batch without the camera transformation for our UI spriteBatch.Begin(); // if the user is touching the screen and the thumbsticks have positions, // draw our thumbstick sprite so the user knows where the centers are if (VirtualThumbsticks.LeftThumbstickCenter.HasValue) { spriteBatch.Draw( thumbstick, VirtualThumbsticks.LeftThumbstickCenter.Value - new Vector2(thumbstick.Width / 2f, thumbstick.Height / 2f), Color.Green); } if (VirtualThumbsticks.RightThumbstickCenter.HasValue) { spriteBatch.Draw( thumbstick, VirtualThumbsticks.RightThumbstickCenter.Value - new Vector2(thumbstick.Width / 2f, thumbstick.Height / 2f), Color.Blue); } spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// Draws four rectangles using the blank texture to represent our world bounds. /// </summary> private void DrawWorldBorder() { Rectangle r = new Rectangle( -worldWidth / 2 - worldBorderThickness, -worldHeight / 2 - worldBorderThickness, worldBorderThickness, worldHeight + worldBorderThicknessDouble); spriteBatch.Draw(blank, r, worldBorderColor); r = new Rectangle( -worldWidth / 2 - worldBorderThickness, -worldHeight / 2 - worldBorderThickness, worldWidth + worldBorderThicknessDouble, worldBorderThickness); spriteBatch.Draw(blank, r, worldBorderColor); r = new Rectangle( worldWidth / 2, -worldHeight / 2 - worldBorderThickness, worldBorderThickness, worldHeight + worldBorderThicknessDouble); spriteBatch.Draw(blank, r, worldBorderColor); r = new Rectangle( -worldWidth / 2 - worldBorderThickness, worldHeight / 2, worldWidth + worldBorderThicknessDouble, worldBorderThickness); spriteBatch.Draw(blank, r, worldBorderColor); } #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. /*============================================================ ** ** ** ** ** Purpose: Provides a fast, AV free, cross-language way of ** accessing unmanaged memory in a random fashion. ** ** ===========================================================*/ using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System.IO { /// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the /// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because /// this gives better throughput; benchmarks showed about 12-15% better. public class UnmanagedMemoryAccessor : IDisposable { private SafeBuffer _buffer = null!; // initialized in helper called by ctor private long _offset; private long _capacity; private FileAccess _access; private bool _isOpen; private bool _canRead; private bool _canWrite; protected UnmanagedMemoryAccessor() { _isOpen = false; } public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity) { Initialize(buffer, offset, capacity, FileAccess.Read); } public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity, FileAccess access) { Initialize(buffer, offset, capacity, access); } protected void Initialize(SafeBuffer buffer, long offset, long capacity, FileAccess access) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.ByteLength < (ulong)(offset + capacity)) { throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException(nameof(access)); } if (_isOpen) { throw new InvalidOperationException(SR.InvalidOperation_CalledTwice); } unsafe { byte* pointer = null; try { buffer.AcquirePointer(ref pointer); if (((byte*)((long)pointer + offset + capacity)) < pointer) { throw new ArgumentException(SR.Argument_UnmanagedMemAccessorWrapAround); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _capacity = capacity; _access = access; _isOpen = true; _canRead = (_access & FileAccess.Read) != 0; _canWrite = (_access & FileAccess.Write) != 0; } public long Capacity => _capacity; public bool CanRead => _isOpen && _canRead; public bool CanWrite => _isOpen && _canWrite; protected virtual void Dispose(bool disposing) { _isOpen = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected bool IsOpen => _isOpen; // ************** Read Methods ****************/ public bool ReadBoolean(long position) => ReadByte(position) != 0; public byte ReadByte(long position) { EnsureSafeToRead(position, sizeof(byte)); byte result; unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = *((byte*)(pointer + _offset + position)); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } public char ReadChar(long position) => unchecked((char)ReadInt16(position)); public short ReadInt16(long position) { EnsureSafeToRead(position, sizeof(short)); short result; unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = Unsafe.ReadUnaligned<short>(pointer + _offset + position); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } public int ReadInt32(long position) { EnsureSafeToRead(position, sizeof(int)); int result; unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = Unsafe.ReadUnaligned<int>(pointer + _offset + position); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } public long ReadInt64(long position) { EnsureSafeToRead(position, sizeof(long)); long result; unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); result = Unsafe.ReadUnaligned<long>(pointer + _offset + position); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } public decimal ReadDecimal(long position) { const int ScaleMask = 0x00FF0000; const int SignMask = unchecked((int)0x80000000); EnsureSafeToRead(position, sizeof(decimal)); int lo, mid, hi, flags; unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); lo = Unsafe.ReadUnaligned<int>(pointer); mid = Unsafe.ReadUnaligned<int>(pointer + 4); hi = Unsafe.ReadUnaligned<int>(pointer + 8); flags = Unsafe.ReadUnaligned<int>(pointer + 12); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } // Check for invalid Decimal values if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))) { throw new ArgumentException(SR.Arg_BadDecimal); // Throw same Exception type as Decimal(int[]) ctor for compat } bool isNegative = (flags & SignMask) != 0; byte scale = (byte)(flags >> 16); return new decimal(lo, mid, hi, isNegative, scale); } public float ReadSingle(long position) => BitConverter.Int32BitsToSingle(ReadInt32(position)); public double ReadDouble(long position) => BitConverter.Int64BitsToDouble(ReadInt64(position)); [CLSCompliant(false)] public sbyte ReadSByte(long position) => unchecked((sbyte)ReadByte(position)); [CLSCompliant(false)] public ushort ReadUInt16(long position) => unchecked((ushort)ReadInt16(position)); [CLSCompliant(false)] public uint ReadUInt32(long position) => unchecked((uint)ReadInt32(position)); [CLSCompliant(false)] public ulong ReadUInt64(long position) => unchecked((ulong)ReadInt64(position)); // Reads a struct of type T from unmanaged memory, into the reference pointed to by ref value. // Note: this method is not safe, since it overwrites the contents of a structure, it can be // used to modify the private members of a struct. // This method is most performant when used with medium to large sized structs // (larger than 8 bytes -- though this is number is JIT and architecture dependent). As // such, it is best to use the ReadXXX methods for small standard types such as ints, longs, // bools, etc. public void Read<T>(long position, out T structure) where T : struct { if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); } if (!_canRead) { throw new NotSupportedException(SR.NotSupported_Reading); } uint sizeOfT = SafeBuffer.SizeOf<T>(); if (position > _capacity - sizeOfT) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } else { throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToRead, typeof(T)), nameof(position)); } } structure = _buffer.Read<T>((ulong)(_offset + position)); } // Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'. // Note: this method is not safe, since it overwrites the contents of structures, it can // be used to modify the private members of a struct. public int ReadArray<T>(long position, T[] array, int offset, int count) where T : struct { if (array == null) { throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); } if (!_canRead) { throw new NotSupportedException(SR.NotSupported_Reading); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } uint sizeOfT = SafeBuffer.AlignedSizeOf<T>(); // only check position and ask for fewer Ts if count is too big if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } int n = count; long spaceLeft = _capacity - position; if (spaceLeft < 0) { n = 0; } else { ulong spaceNeeded = (ulong)(sizeOfT * count); if ((ulong)spaceLeft < spaceNeeded) { n = (int)(spaceLeft / sizeOfT); } } _buffer.ReadArray<T>((ulong)(_offset + position), array, offset, n); return n; } // ************** Write Methods ****************/ public void Write(long position, bool value) => Write(position, (byte)(value ? 1 : 0)); public void Write(long position, byte value) { EnsureSafeToWrite(position, sizeof(byte)); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); *((byte*)(pointer + _offset + position)) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } public void Write(long position, char value) => Write(position, unchecked((short)value)); public void Write(long position, short value) { EnsureSafeToWrite(position, sizeof(short)); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Unsafe.WriteUnaligned<short>(pointer + _offset + position, value); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } public void Write(long position, int value) { EnsureSafeToWrite(position, sizeof(int)); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Unsafe.WriteUnaligned<int>(pointer + _offset + position, value); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } public void Write(long position, long value) { EnsureSafeToWrite(position, sizeof(long)); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); Unsafe.WriteUnaligned<long>(pointer + _offset + position, value); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } public void Write(long position, decimal value) { EnsureSafeToWrite(position, sizeof(decimal)); unsafe { int* valuePtr = (int*)(&value); int flags = *valuePtr; int hi = *(valuePtr + 1); int lo = *(valuePtr + 2); int mid = *(valuePtr + 3); byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); Unsafe.WriteUnaligned<int>(pointer, lo); Unsafe.WriteUnaligned<int>(pointer + 4, mid); Unsafe.WriteUnaligned<int>(pointer + 8, hi); Unsafe.WriteUnaligned<int>(pointer + 12, flags); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } public void Write(long position, float value) => Write(position, BitConverter.SingleToInt32Bits(value)); public void Write(long position, double value) => Write(position, BitConverter.DoubleToInt64Bits(value)); [CLSCompliant(false)] public void Write(long position, sbyte value) => Write(position, unchecked((byte)value)); [CLSCompliant(false)] public void Write(long position, ushort value) => Write(position, unchecked((short)value)); [CLSCompliant(false)] public void Write(long position, uint value) => Write(position, unchecked((int)value)); [CLSCompliant(false)] public void Write(long position, ulong value) => Write(position, unchecked((long)value)); // Writes the struct pointed to by ref value into unmanaged memory. Note that this method // is most performant when used with medium to large sized structs (larger than 8 bytes // though this is number is JIT and architecture dependent). As such, it is best to use // the WriteX methods for small standard types such as ints, longs, bools, etc. public void Write<T>(long position, ref T structure) where T : struct { if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); } if (!_canWrite) { throw new NotSupportedException(SR.NotSupported_Writing); } uint sizeOfT = SafeBuffer.SizeOf<T>(); if (position > _capacity - sizeOfT) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } else { throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, typeof(T)), nameof(position)); } } _buffer.Write<T>((ulong)(_offset + position), structure); } // Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory. public void WriteArray<T>(long position, T[] array, int offset, int count) where T : struct { if (array == null) { throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } if (position >= Capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); } if (!_canWrite) { throw new NotSupportedException(SR.NotSupported_Writing); } _buffer.WriteArray<T>((ulong)(_offset + position), array, offset, count); } private void EnsureSafeToRead(long position, int sizeOfType) { if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); } if (!_canRead) { throw new NotSupportedException(SR.NotSupported_Reading); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } if (position > _capacity - sizeOfType) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } else { throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position)); } } } private void EnsureSafeToWrite(long position, int sizeOfType) { if (!_isOpen) { throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); } if (!_canWrite) { throw new NotSupportedException(SR.NotSupported_Writing); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } if (position > _capacity - sizeOfType) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } else { throw new ArgumentException(SR.Argument_NotEnoughBytesToWrite, nameof(position)); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Resources; using System.Text; using System.Text.RegularExpressions; using DDay.iCal.Serialization.iCalendar; using NUnit.Framework; namespace DDay.iCal.Test { [TestFixture] public class ProgramTest { [Test] public void LoadAndDisplayCalendar() { // The following code loads and displays an iCalendar // with US Holidays for 2006. // IICalendar iCal = iCalendar.LoadFromFile(@"Calendars/Serialization/USHolidays.ics")[0]; Assert.IsNotNull(iCal, "iCalendar did not load. Are you connected to the internet?"); IList<Occurrence> occurrences = iCal.GetOccurrences( new iCalDateTime(2006, 1, 1, "US-Eastern"), new iCalDateTime(2006, 12, 31, "US-Eastern")); foreach (Occurrence o in occurrences) { IEvent evt = o.Source as IEvent; if (evt != null) { // Display the date of the event Console.Write(o.Period.StartTime.Local.Date.ToString("MM/dd/yyyy") + " -\t"); // Display the event summary Console.Write(evt.Summary); // Display the time the event happens (unless it's an all-day event) if (evt.Start.HasTime) { Console.Write(" (" + evt.Start.Local.ToShortTimeString() + " - " + evt.End.Local.ToShortTimeString()); if (evt.Start.TimeZoneObservance != null && evt.Start.TimeZoneObservance.HasValue) Console.Write(" " + evt.Start.TimeZoneObservance.Value.TimeZoneInfo.TimeZoneName); Console.Write(")"); } Console.Write(Environment.NewLine); } } } private DateTime Start; private DateTime End; private TimeSpan TotalTime; private string tzid; [TestFixtureSetUp] public void InitAll() { TotalTime = new TimeSpan(0); tzid = "US-Eastern"; } [TestFixtureTearDown] public void DisposeAll() { Console.WriteLine("Total Processing Time: " + Math.Round(TotalTime.TotalMilliseconds) + "ms"); } [SetUp] public void Init() { Start = DateTime.Now; } [TearDown] public void Dispose() { End = DateTime.Now; TotalTime = TotalTime.Add(End - Start); Console.WriteLine("Time: " + Math.Round(End.Subtract(Start).TotalMilliseconds) + "ms"); } static public void TestCal(IICalendar iCal) { Assert.IsNotNull(iCal, "The iCalendar was not loaded"); if (iCal.Events.Count > 0) Assert.IsTrue(iCal.Events.Count == 1, "Calendar should contain 1 event; however, the iCalendar loaded " + iCal.Events.Count + " events"); else if (iCal.Todos.Count > 0) Assert.IsTrue(iCal.Todos.Count == 1, "Calendar should contain 1 todo; however, the iCalendar loaded " + iCal.Todos.Count + " todos"); } [Test] public void LoadFromFile() { string path = @"Calendars/Serialization/Calendar1.ics"; Assert.IsTrue(File.Exists(path), "File '" + path + "' does not exist."); IICalendar iCal = iCalendar.LoadFromFile(path)[0]; Assert.AreEqual(14, iCal.Events.Count); } // [Test] public void LoadFromUri() { string path = Directory.GetCurrentDirectory(); path = Path.Combine(path, "Calendars/Serialization/Calendar1.ics").Replace(@"\", "/"); path = "file:///" + path; Uri uri = new Uri(path); IICalendar iCal = iCalendar.LoadFromUri(uri)[0]; Assert.AreEqual(14, iCal.Events.Count); } /// <summary> /// Ensures that Period.GetHashCode() does not throw NullReferenceException, even /// if its properties are null. /// </summary> [Test] public void Bug3258032() { Period p = new Period(); p.GetHashCode(); } /// <summary> /// The following test is an aggregate of MonthlyCountByMonthDay3() and MonthlyByDay1() in the /// <see cref="Recurrence"/> class. /// </summary> [Test] public void Merge1() { IICalendar iCal1 = iCalendar.LoadFromFile(@"Calendars/Recurrence/MonthlyCountByMonthDay3.ics")[0]; IICalendar iCal2 = iCalendar.LoadFromFile(@"Calendars/Recurrence/MonthlyByDay1.ics")[0]; // Change the UID of the 2nd event to make sure it's different iCal2.Events[iCal1.Events[0].UID].UID = "1234567890"; iCal1.MergeWith(iCal2); IEvent evt1 = iCal1.Events.First(); IEvent evt2 = iCal1.Events.Skip(1).First(); // Get occurrences for the first event IList<Occurrence> occurrences = evt1.GetOccurrences( new iCalDateTime(1996, 1, 1, tzid), new iCalDateTime(2000, 1, 1, tzid)); iCalDateTime[] DateTimes = new iCalDateTime[] { new iCalDateTime(1997, 9, 10, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 11, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 12, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 13, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 14, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 15, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 10, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 11, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 12, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 13, 9, 0, 0, tzid), }; string[] TimeZones = new string[] { "EDT", "EDT", "EDT", "EDT", "EDT", "EDT", "EST", "EST", "EST", "EST" }; for (int i = 0; i < DateTimes.Length; i++) { IDateTime dt = DateTimes[i]; IDateTime start = occurrences[i].Period.StartTime; Assert.AreEqual(dt, start); Assert.IsTrue(dt.TimeZoneName == TimeZones[i], "Event " + dt + " should occur in the " + TimeZones[i] + " timezone"); } Assert.IsTrue(occurrences.Count == DateTimes.Length, "There should be exactly " + DateTimes.Length + " occurrences; there were " + occurrences.Count); // Get occurrences for the 2nd event occurrences = evt2.GetOccurrences( new iCalDateTime(1996, 1, 1, tzid), new iCalDateTime(1998, 4, 1, tzid)); iCalDateTime[] DateTimes1 = new iCalDateTime[] { new iCalDateTime(1997, 9, 2, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 9, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 16, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 23, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 30, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 4, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 11, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 18, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 25, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 6, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 13, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 20, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 27, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 3, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 10, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 17, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 24, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 31, 9, 0, 0, tzid) }; string[] TimeZones1 = new string[] { "EDT", "EDT", "EDT", "EDT", "EDT", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST" }; for (int i = 0; i < DateTimes1.Length; i++) { IDateTime dt = DateTimes1[i]; IDateTime start = occurrences[i].Period.StartTime; Assert.AreEqual(dt, start); Assert.IsTrue(dt.TimeZoneName == TimeZones1[i], "Event " + dt + " should occur in the " + TimeZones1[i] + " timezone"); } Assert.AreEqual(DateTimes1.Length, occurrences.Count, "There should be exactly " + DateTimes1.Length + " occurrences; there were " + occurrences.Count); } [Test] public void Merge2() { iCalendar iCal = new iCalendar(); IICalendar tmp_cal = iCalendar.LoadFromFile(@"Calendars/Serialization/TimeZone3.ics")[0]; iCal.MergeWith(tmp_cal); tmp_cal = iCalendar.LoadFromFile(@"Calendars/Serialization/TimeZone3.ics")[0]; // Compare the two calendars -- they should match exactly SerializationTest.CompareCalendars(iCal, tmp_cal); } /// <summary> /// The following tests the MergeWith() method of iCalendar to /// ensure that unique component merging happens as expected. /// </summary> [Test] public void Merge3() { IICalendar iCal1 = iCalendar.LoadFromFile(@"Calendars/Recurrence/MonthlyCountByMonthDay3.ics")[0]; IICalendar iCal2 = iCalendar.LoadFromFile(@"Calendars/Recurrence/YearlyByMonth1.ics")[0]; iCal1.MergeWith(iCal2); Assert.AreEqual(1, iCal1.Events.Count); } #if !SILVERLIGHT /// <summary> /// Tests conversion of the system time zone to one compatible with DDay.iCal. /// Also tests the gaining/loss of an hour over time zone boundaries. /// </summary> [Test] public void SystemTimeZone1() { // System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("America/Denver"); Assert.IsNotNull(tzi); iCalendar iCal = new iCalendar(); ITimeZone tz = iCal.AddTimeZone(tzi, new DateTime(2000, 1, 1), false); iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(iCal, @"Calendars/Serialization/SystemTimeZone1.ics"); // Ensure the time zone transition works as expected // (i.e. it takes 1 hour and 1 second to transition from // 2003-10-26 1:59:59 AM to // 2003-10-26 2:00:00 AM) iCalDateTime dt1 = new iCalDateTime(2003, 10, 26, 1, 59, 59, tz.TZID, iCal); iCalDateTime dt2 = new iCalDateTime(2003, 10, 26, 2, 0, 0, tz.TZID, iCal); TimeSpan result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), result); // Ensure another time zone transition works as expected // (i.e. it takes negative 59 minutes and 59 seconds to transition from // 2004-04-04 01:59:59 AM to // 2004-04-04 02:00:00 AM) // NOTE: We have a negative difference between the two values // because we 'spring ahead', and an hour is lost. dt1 = new iCalDateTime(2004, 4, 4, 1, 59, 59, tz.TZID, iCal); dt2 = new iCalDateTime(2004, 4, 4, 2, 0, 0, tz.TZID, iCal); result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(-1) + TimeSpan.FromSeconds(1), result); } /// <summary> /// Ensures the AddTimeZone() method works as expected. /// </summary> [Test] public void SystemTimeZone2() { // System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("America/Denver"); Assert.IsNotNull(tzi); iCalendar iCal = new iCalendar(); ITimeZone tz = iCal.AddTimeZone(tzi, new DateTime(2000, 1, 1), false); Assert.IsNotNull(tz); iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(iCal, @"Calendars/Serialization/SystemTimeZone2.ics"); // Ensure the time zone transition works as expected // (i.e. it takes 1 hour and 1 second to transition from // 2003-10-26 1:59:59 AM to // 2003-10-26 2:00:00 AM) iCalDateTime dt1 = new iCalDateTime(2003, 10, 26, 1, 59, 59, tz.TZID, iCal); iCalDateTime dt2 = new iCalDateTime(2003, 10, 26, 2, 0, 0, tz.TZID, iCal); TimeSpan result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), result); // Ensure another time zone transition works as expected // (i.e. it takes negative 59 minutes and 59 seconds to transition from // 2004-04-04 1:59:59 AM to // 2004-04-04 2:00:00 AM) dt1 = new iCalDateTime(2004, 4, 4, 1, 59, 59, tz.TZID, iCal); dt2 = new iCalDateTime(2004, 4, 4, 2, 0, 0, tz.TZID, iCal); result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(-1) + TimeSpan.FromSeconds(1), result); } [Test] public void SystemTimeZone3() { // Per Jon Udell's test, we should be able to get all // system time zones on the machine and ensure they // are properly translated. var zones = System.TimeZoneInfo.GetSystemTimeZones(); TimeZoneInfo tzinfo; foreach (var zone in zones) { tzinfo = null; #pragma warning disable 0168 try { tzinfo = System.TimeZoneInfo.FindSystemTimeZoneById(zone.Id); } catch (Exception e) { Assert.Fail("Not found: " + zone.StandardName); } #pragma warning disable 0168 if (tzinfo != null) { var ical_tz = DDay.iCal.iCalTimeZone.FromSystemTimeZone(tzinfo); Assert.AreNotEqual(0, ical_tz.TimeZoneInfos.Count, zone.StandardName + ": no time zone information was extracted."); } } } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using C = Mono.Cecil; using Mono.Cecil.Metadata; namespace Mono.Debugger.Soft { public class MethodMirror : Mirror { string name; MethodInfo info; TypeMirror declaring_type; DebugInfo debug_info; C.MethodDefinition meta; CustomAttributeDataMirror[] cattrs; ParameterInfoMirror[] param_info; ParameterInfoMirror ret_param; LocalVariable[] locals; LocalScope[] scopes; IList<Location> locations; MethodBodyMirror body; MethodMirror gmd; TypeMirror[] type_args; internal MethodMirror (VirtualMachine vm, long id) : base (vm, id) { } public string Name { get { if (name == null) name = vm.conn.Method_GetName (id); return name; } } public TypeMirror DeclaringType { get { if (declaring_type == null) declaring_type = vm.GetType (vm.conn.Method_GetDeclaringType (id)); return declaring_type; } } public TypeMirror ReturnType { get { return ReturnParameter.ParameterType; } } // FIXME: public string FullName { get { string type_namespace = DeclaringType.Namespace; string type_name = DeclaringType.Name; StringBuilder sb = new StringBuilder (); sb.Append (ReturnType.Name); sb.Append (' '); if (type_namespace != String.Empty) sb.Append (type_namespace).Append ("."); sb.Append(type_name); sb.Append(":"); sb.Append(Name); sb.Append(" "); sb.Append("("); for (var i = 0; i < param_info.Length; i++) { sb.Append(param_info[i].ParameterType.Name); if (i != param_info.Length - 1) sb.Append(", "); } sb.Append(")"); return sb.ToString (); } } /* * Creating the custom attributes themselves could modify the behavior of the * debuggee, so we return objects similar to the CustomAttributeData objects * used by the reflection-only functionality on .net. * Since protocol version 2.21 */ public CustomAttributeDataMirror[] GetCustomAttributes (bool inherit) { return GetCAttrs (null, inherit); } /* Since protocol version 2.21 */ public CustomAttributeDataMirror[] GetCustomAttributes (TypeMirror attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException ("attributeType"); return GetCAttrs (attributeType, inherit); } CustomAttributeDataMirror[] GetCAttrs (TypeMirror type, bool inherit) { if (cattrs == null && meta != null && !Metadata.HasCustomAttributes) cattrs = new CustomAttributeDataMirror [0]; // FIXME: Handle inherit if (cattrs == null) { CattrInfo[] info = vm.conn.Method_GetCustomAttributes (id, 0, false); cattrs = CustomAttributeDataMirror.Create (vm, info); } var res = new List<CustomAttributeDataMirror> (); foreach (var attr in cattrs) if (type == null || attr.Constructor.DeclaringType == type) res.Add (attr); return res.ToArray (); } MethodInfo GetInfo () { if (info == null) info = vm.conn.Method_GetInfo (id); return info; } public int MetadataToken { get { return GetInfo ().token; } } public MethodAttributes Attributes { get { return (MethodAttributes) GetInfo ().attributes; } } public bool IsPublic { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } } public bool IsPrivate { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } } public bool IsFamily { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } } public bool IsAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } } public bool IsFamilyAndAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } } public bool IsFamilyOrAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } } public bool IsStatic { get { return (Attributes & MethodAttributes.Static) != 0; } } public bool IsFinal { get { return (Attributes & MethodAttributes.Final) != 0; } } public bool IsVirtual { get { return (Attributes & MethodAttributes.Virtual) != 0; } } public bool IsHideBySig { get { return (Attributes & MethodAttributes.HideBySig) != 0; } } public bool IsAbstract { get { return (Attributes & MethodAttributes.Abstract) != 0; } } public bool IsSpecialName { get { return (Attributes & MethodAttributes.SpecialName) != 0; } } public bool IsConstructor { get { int attr = (int)Attributes; return ((attr & (int)MethodAttributes.RTSpecialName) != 0 && (Name == ".ctor")); } } // Since protocol version 2.12 public bool IsGenericMethodDefinition { get { vm.CheckProtocolVersion (2, 12); return GetInfo ().is_gmd; } } // Since protocol version 2.12 public bool IsGenericMethod { get { vm.CheckProtocolVersion (2, 12); return GetInfo ().is_generic_method; } } public MethodImplAttributes GetMethodImplementationFlags() { return (MethodImplAttributes)GetInfo ().iattributes; } public ParameterInfoMirror[] GetParameters () { if (param_info == null) { var pi = vm.conn.Method_GetParamInfo (id); param_info = new ParameterInfoMirror [pi.param_count]; // Return ret_param = new ParameterInfoMirror (this, -1, vm.GetType (pi.ret_type), null, ParameterAttributes.Retval); // FIXME: this // FIXME: Attributes for (int i = 0; i < pi.param_count; ++i) { param_info [i] = new ParameterInfoMirror (this, i, vm.GetType (pi.param_types [i]), pi.param_names [i], 0); } } return param_info; } public ParameterInfoMirror ReturnParameter { get { if (ret_param == null) GetParameters (); return ret_param; } } public LocalScope [] GetScopes () { if (!vm.Version.AtLeast (2, 43)) throw new InvalidOperationException ("Scopes support was implemented in 2.43 version of protocol."); GetLocals (); return scopes; } public LocalVariable[] GetLocals () { if (locals == null) { LocalsInfo li = new LocalsInfo (); try { li = vm.conn.Method_GetLocalsInfo (id); } catch (CommandException) { throw new AbsentInformationException (); } // Add the arguments as well var pi = GetParameters (); locals = new LocalVariable [pi.Length + li.names.Length]; for (int i = 0; i < pi.Length; ++i) locals [i] = new LocalVariable (vm, this, i, pi[i].ParameterType.Id, pi[i].Name, -1, -1, true); for (int i = 0; i < li.names.Length; ++i) locals [i + pi.Length] = new LocalVariable (vm, this, i, li.types [i], li.names [i], li.live_range_start [i], li.live_range_end [i], false); if (vm.Version.AtLeast (2, 43)) { scopes = new LocalScope [li.scopes_start.Length]; for (int i = 0; i < scopes.Length; ++i) scopes [i] = new LocalScope (vm, this, li.scopes_start [i], li.scopes_end [i]); } } return locals; } public LocalVariable GetLocal (string name) { if (name == null) throw new ArgumentNullException ("name"); GetLocals (); LocalVariable res = null; for (int i = 0; i < locals.Length; ++i) { if (locals [i].Name == name) { if (res != null) throw new AmbiguousMatchException ("More that one local has the name '" + name + "'."); res = locals [i]; } } return res; } public MethodBodyMirror GetMethodBody () { if (body == null) { MethodBodyInfo info = vm.conn.Method_GetBody (id); body = new MethodBodyMirror (vm, this, info); } return body; } public MethodMirror GetGenericMethodDefinition () { vm.CheckProtocolVersion (2, 12); if (gmd == null) { if (info.gmd == 0) throw new InvalidOperationException (); gmd = vm.GetMethod (info.gmd); } return gmd; } // Since protocol version 2.15 public TypeMirror[] GetGenericArguments () { vm.CheckProtocolVersion (2, 15); if (type_args == null) type_args = vm.GetTypes (GetInfo ().type_args); return type_args; } // Since protocol version 2.24 public MethodMirror MakeGenericMethod (TypeMirror[] args) { if (args == null) throw new ArgumentNullException ("args"); foreach (var a in args) if (a == null) throw new ArgumentNullException ("args"); if (!IsGenericMethodDefinition) throw new InvalidOperationException ("not a generic method definition"); if (GetGenericArguments ().Length != args.Length) throw new ArgumentException ("Incorrect length"); vm.CheckProtocolVersion (2, 24); long id = -1; try { id = vm.conn.Method_MakeGenericMethod (Id, args.Select (t => t.Id).ToArray ()); } catch (CommandException) { throw new InvalidOperationException (); } return vm.GetMethod (id); } public IList<int> ILOffsets { get { if (debug_info == null) debug_info = vm.conn.Method_GetDebugInfo (id); return Array.AsReadOnly (debug_info.il_offsets); } } public IList<int> LineNumbers { get { if (debug_info == null) debug_info = vm.conn.Method_GetDebugInfo (id); return Array.AsReadOnly (debug_info.line_numbers); } } public string SourceFile { get { if (debug_info == null) debug_info = vm.conn.Method_GetDebugInfo (id); return debug_info.source_files.Length > 0 ? debug_info.source_files [0].source_file : null; } } public IList<Location> Locations { get { if (locations == null) { var il_offsets = ILOffsets; var line_numbers = LineNumbers; IList<Location> res = new Location [ILOffsets.Count]; for (int i = 0; i < il_offsets.Count; ++i) res [i] = new Location (vm, this, -1, il_offsets [i], debug_info.source_files [i].source_file, line_numbers [i], debug_info.column_numbers [i], debug_info.end_line_numbers [i], debug_info.end_column_numbers [i], debug_info.source_files [i].hash); locations = res; } return locations; } } internal int il_offset_to_line_number (int il_offset, out string src_file, out byte[] src_hash, out int column_number, out int end_line_number, out int end_column_number) { if (debug_info == null) debug_info = vm.conn.Method_GetDebugInfo (id); // FIXME: Optimize this src_file = null; src_hash = null; column_number = 0; end_line_number = -1; end_column_number = -1; for (int i = debug_info.il_offsets.Length - 1; i >= 0; --i) { if (debug_info.il_offsets [i] <= il_offset) { src_file = debug_info.source_files [i].source_file; src_hash = debug_info.source_files [i].hash; column_number = debug_info.column_numbers [i]; end_line_number = debug_info.end_line_numbers [i]; end_column_number = debug_info.end_column_numbers [i]; return debug_info.line_numbers [i]; } } return -1; } public Location LocationAtILOffset (int il_offset) { IList<Location> locs = Locations; // FIXME: Optimize this for (int i = locs.Count - 1; i >= 0; --i) { if (locs [i].ILOffset <= il_offset) return locs [i]; } return null; } public C.MethodDefinition Metadata { get { if (meta == null) meta = (C.MethodDefinition)DeclaringType.Assembly.Metadata.MainModule.LookupToken (MetadataToken); return meta; } } // // Evaluate the method on the client using an IL interpreter. // Only supports a subset of IL instructions. Doesn't change // debuggee state. // Returns the result of the evaluation, or null for methods // which return void. // Throws a NotSupportedException if the method body contains // unsupported IL instructions, or if evaluating the method // would change debuggee state. // public Value Evaluate (Value this_val, Value[] args) { var interp = new ILInterpreter (this); return interp.Evaluate (this_val, args); } } }
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using Komires.MataliPhysics; using Komires.MataliRender; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class Camera1Draw1 { Demo demo; PhysicsScene scene; string instanceIndexName; string quadName; DemoKeyboardState oldKeyboardState; bool enableDrawBoundingBoxes; bool enableDrawContactPoints; bool enableDrawSlipingObjects; bool enableDrawImpactFactors; bool enableDrawLights; bool enableWireframe; DrawBuffersEnum[] targets; RenderClearDeferredQuadP renderClear; RenderLightDirectionalDeferredQuadP renderLightDirectional; RenderLightPointDeferredP renderLightPoint; RenderLightSpotDeferredP renderLightSpot; RenderScreenDeferredQuadP renderScreen; RenderPC render; VertexPositionColor[] cameraVertices; Vector3 position; Vector3 direction; Vector3 lightDiffuse; Vector3 lightSpecular; BoundingBox boundingBox; Matrix4 world; Matrix4 view; Matrix4 projection; Matrix4 matrixIdentity; public Camera1Draw1(Demo demo, int instanceIndex) { this.demo = demo; instanceIndexName = " " + instanceIndex.ToString(); quadName = "Quad"; matrixIdentity = Matrix4.Identity; } public void Initialize(PhysicsScene scene) { this.scene = scene; targets = new DrawBuffersEnum[4]; cameraVertices = new VertexPositionColor[24]; renderClear = new RenderClearDeferredQuadP(); renderLightDirectional = new RenderLightDirectionalDeferredQuadP(); renderLightPoint = new RenderLightPointDeferredP(); renderLightSpot = new RenderLightSpotDeferredP(); renderScreen = new RenderScreenDeferredQuadP(); render = new RenderPC(); } public void SetControllers(bool enableDrawBoundingBoxes, bool enableDrawContactPoints, bool enableDrawSlipingObjects, bool enableDrawImpactFactors, bool enableDrawLights, bool enableWireframe) { oldKeyboardState = demo.GetKeyboardState(); this.enableDrawBoundingBoxes = enableDrawBoundingBoxes; this.enableDrawContactPoints = enableDrawContactPoints; this.enableDrawSlipingObjects = enableDrawSlipingObjects; this.enableDrawImpactFactors = enableDrawImpactFactors; this.enableDrawLights = enableDrawLights; this.enableWireframe = enableWireframe; PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Find("Camera 1" + instanceIndexName); if (objectBase != null) { objectBase.UserControllers.DrawMethods += new DrawMethod(Draw); objectBase.UserControllers.DrawMethods += new DrawMethod(DrawBoundingBoxes); objectBase.UserControllers.DrawMethods += new DrawMethod(DrawContactPoints); objectBase.UserControllers.DrawMethods += new DrawMethod(DrawImpactFactors); } } public void RefreshControllers() { oldKeyboardState = demo.GetKeyboardState(); } public void Draw(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; DemoKeyboardState keyboardState = demo.GetKeyboardState(); if (keyboardState[Key.B] && !oldKeyboardState[Key.B]) enableDrawBoundingBoxes = !enableDrawBoundingBoxes; if (keyboardState[Key.C] && !oldKeyboardState[Key.C]) enableDrawContactPoints = !enableDrawContactPoints; if (keyboardState[Key.V] && !oldKeyboardState[Key.V]) enableDrawSlipingObjects = !enableDrawSlipingObjects; if (keyboardState[Key.I] && !oldKeyboardState[Key.I]) enableDrawImpactFactors = !enableDrawImpactFactors; if (keyboardState[Key.G] && !oldKeyboardState[Key.G]) enableDrawLights = !enableDrawLights; if (keyboardState[Key.N] && !oldKeyboardState[Key.N]) enableWireframe = !enableWireframe; oldKeyboardState = keyboardState; demo.EnableWireframe = enableWireframe; PhysicsObject menuPhysicsObjectWithCamera = demo.MenuScene.PhysicsScene.GetPhysicsObjectWithCamera(0); if (menuPhysicsObjectWithCamera != null) { if (menuPhysicsObjectWithCamera.Camera.UserDataObj != null) { Camera3Draw1 menuCamera = menuPhysicsObjectWithCamera.Camera.UserDataObj as Camera3Draw1; if (menuCamera != null) { menuCamera.EnableDrawBoundingBoxes = enableDrawBoundingBoxes; menuCamera.EnableDrawContactPoints = enableDrawContactPoints; menuCamera.EnableDrawSlipingObjects = enableDrawSlipingObjects; menuCamera.EnableDrawLights = enableDrawLights; menuCamera.EnableWireframe = enableWireframe; } } } float time = args.Time; PhysicsObject drawPhysicsObject, transparentPhysicsObject, lightPhysicsObject; PhysicsLight sceneLight, drawLight; DemoMesh mesh, quad; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); sceneLight = scene.Light; quad = demo.Meshes[quadName]; GL.BindFramebuffer(FramebufferTarget.Framebuffer, demo.SceneFrameBuffer); targets[0] = DrawBuffersEnum.ColorAttachment0; targets[1] = DrawBuffersEnum.ColorAttachment1; targets[2] = DrawBuffersEnum.ColorAttachment2; targets[3] = DrawBuffersEnum.ColorAttachment3; GL.DrawBuffers(4, targets); GL.Clear(ClearBufferMask.DepthBufferBit); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.Disable(EnableCap.Blend); GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); GL.Disable(EnableCap.CullFace); renderClear.SetClearScreenColor(ref demo.ClearScreenColor); quad.Draw(renderClear); GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); for (int i = 0; i < objectBase.Camera.DrawPhysicsObjectCount; i++) { drawPhysicsObject = objectBase.Camera.GetDrawPhysicsObject(i); if ((drawPhysicsObject.UserControllers.DrawMethods == null) || (drawPhysicsObject == objectBase)) { if (drawPhysicsObject.UserDataStr == null) continue; if ((drawPhysicsObject.Shape == null) && drawPhysicsObject.IsBrokenRigidGroup) continue; if ((drawPhysicsObject.RigidGroupOwner != drawPhysicsObject) && (drawPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; drawPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); mesh = demo.Meshes[drawPhysicsObject.UserDataStr]; mesh.Draw(ref world, ref view, ref projection, sceneLight, drawPhysicsObject.Material, objectBase.Camera, drawPhysicsObject.RigidGroupOwner.IsSleeping && enableDrawSlipingObjects, enableWireframe); } else { if (drawPhysicsObject.UserControllers.EnableDraw) continue; if ((drawPhysicsObject.Shape == null) && drawPhysicsObject.IsBrokenRigidGroup) continue; if ((drawPhysicsObject.RigidGroupOwner != drawPhysicsObject) && (drawPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; drawPhysicsObject.UserControllers.DrawMethodArgs.Time = time; drawPhysicsObject.UserControllers.DrawMethodArgs.OwnerIndex = drawPhysicsObject.Index; drawPhysicsObject.UserControllers.DrawMethodArgs.OwnerSceneIndex = scene.Index; drawPhysicsObject.UserControllers.DrawMethods(drawPhysicsObject.UserControllers.DrawMethodArgs); } } if (objectBase.Camera.TransparentPhysicsObjectCount != 0) { targets[0] = DrawBuffersEnum.ColorAttachment0; targets[1] = DrawBuffersEnum.ColorAttachment1; targets[2] = DrawBuffersEnum.None; targets[3] = DrawBuffersEnum.None; GL.DrawBuffers(4, targets); GL.DepthMask(false); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha); GL.BlendEquation(BlendEquationMode.FuncAdd); for (int i = 0; i < objectBase.Camera.TransparentPhysicsObjectCount; i++) { transparentPhysicsObject = objectBase.Camera.GetTransparentPhysicsObject(i); if ((transparentPhysicsObject.UserControllers.DrawMethods == null) || (transparentPhysicsObject == objectBase)) { if (transparentPhysicsObject.UserDataStr == null) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); mesh = demo.Meshes[transparentPhysicsObject.UserDataStr]; mesh.Draw(ref world, ref view, ref projection, sceneLight, transparentPhysicsObject.Material, objectBase.Camera, transparentPhysicsObject.RigidGroupOwner.IsSleeping && enableDrawSlipingObjects, enableWireframe); } else { if (transparentPhysicsObject.UserControllers.EnableDraw) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.UserControllers.DrawMethodArgs.Time = time; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerIndex = transparentPhysicsObject.Index; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerSceneIndex = scene.Index; transparentPhysicsObject.UserControllers.DrawMethods(transparentPhysicsObject.UserControllers.DrawMethodArgs); } } targets[0] = DrawBuffersEnum.None; targets[1] = DrawBuffersEnum.None; targets[2] = DrawBuffersEnum.ColorAttachment2; targets[3] = DrawBuffersEnum.ColorAttachment3; GL.DrawBuffers(4, targets); GL.DepthMask(true); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.Disable(EnableCap.Blend); for (int i = 0; i < objectBase.Camera.TransparentPhysicsObjectCount; i++) { transparentPhysicsObject = objectBase.Camera.GetTransparentPhysicsObject(i); if (!transparentPhysicsObject.Material.TransparencySecondPass) continue; if ((transparentPhysicsObject.UserControllers.DrawMethods == null) || (transparentPhysicsObject == objectBase)) { if (transparentPhysicsObject.UserDataStr == null) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); mesh = demo.Meshes[transparentPhysicsObject.UserDataStr]; mesh.Draw(ref world, ref view, ref projection, sceneLight, transparentPhysicsObject.Material, objectBase.Camera, transparentPhysicsObject.RigidGroupOwner.IsSleeping && enableDrawSlipingObjects, enableWireframe); } else { if (transparentPhysicsObject.UserControllers.EnableDraw) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.UserControllers.DrawMethodArgs.Time = time; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerIndex = transparentPhysicsObject.Index; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerSceneIndex = scene.Index; transparentPhysicsObject.UserControllers.DrawMethods(transparentPhysicsObject.UserControllers.DrawMethodArgs); } } } GL.BindFramebuffer(FramebufferTarget.Framebuffer, demo.LightFrameBuffer); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); GL.ClearColor(demo.ClearLightColor); GL.Clear(ClearBufferMask.ColorBufferBit); GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.SrcAlpha); GL.BlendEquation(BlendEquationMode.FuncAdd); if ((sceneLight != null) && sceneLight.Enabled) { GL.Disable(EnableCap.CullFace); sceneLight.GetDirection(ref direction); sceneLight.GetDiffuse(ref lightDiffuse); sceneLight.GetSpecular(ref lightSpecular); renderLightDirectional.Enable = true; renderLightDirectional.Width = objectBase.Camera.Projection.Width; renderLightDirectional.Height = objectBase.Camera.Projection.Height; renderLightDirectional.SetView(ref view); renderLightDirectional.SetProjection(ref projection); renderLightDirectional.SetLightDirection(ref direction); renderLightDirectional.SetLightDiffuse(ref lightDiffuse); renderLightDirectional.SetLightSpecular(ref lightSpecular); renderLightDirectional.Intensity = sceneLight.Intensity; renderLightDirectional.SpecularTexture = demo.SpecularTexture; renderLightDirectional.NormalTexture = demo.NormalTexture; renderLightDirectional.DepthTexture = demo.DepthTexture; quad.Draw(renderLightDirectional); } for (int i = 0; i < objectBase.Camera.LightPhysicsObjectCount; i++) { lightPhysicsObject = objectBase.Camera.GetLightPhysicsObject(i); drawLight = lightPhysicsObject.Light; if ((drawLight == null) || !drawLight.Enabled) continue; if (drawLight.Type == PhysicsLightType.Directional) { GL.Disable(EnableCap.CullFace); drawLight.GetDirection(ref direction); drawLight.GetDiffuse(ref lightDiffuse); drawLight.GetSpecular(ref lightSpecular); renderLightDirectional.Enable = true; renderLightDirectional.Width = objectBase.Camera.Projection.Width; renderLightDirectional.Height = objectBase.Camera.Projection.Height; renderLightDirectional.SetView(ref view); renderLightDirectional.SetProjection(ref projection); renderLightDirectional.SetLightDirection(ref direction); renderLightDirectional.SetLightDiffuse(ref lightDiffuse); renderLightDirectional.SetLightSpecular(ref lightSpecular); renderLightDirectional.Intensity = drawLight.Intensity; renderLightDirectional.SpecularTexture = demo.SpecularTexture; renderLightDirectional.NormalTexture = demo.NormalTexture; renderLightDirectional.DepthTexture = demo.DepthTexture; quad.Draw(renderLightDirectional); } else if (drawLight.Type == PhysicsLightType.Point) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = false; if (enableDrawLights) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = true; lightPhysicsObject.Material.TransparencyFactor = 0.5f; lightPhysicsObject.Material.TransparencySecondPass = false; } GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); lightPhysicsObject.MainWorldTransform.GetPosition(ref position); lightPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); drawLight.GetDiffuse(ref lightDiffuse); drawLight.GetSpecular(ref lightSpecular); renderLightPoint.Enable = true; renderLightPoint.Width = objectBase.Camera.Projection.Width; renderLightPoint.Height = objectBase.Camera.Projection.Height; renderLightPoint.SetWorld(ref world); renderLightPoint.SetView(ref view); renderLightPoint.SetProjection(ref projection); renderLightPoint.SetLightPosition(ref position); renderLightPoint.SetLightDiffuse(ref lightDiffuse); renderLightPoint.SetLightSpecular(ref lightSpecular); renderLightPoint.Range = drawLight.Range; renderLightPoint.Intensity = drawLight.Intensity; renderLightPoint.SpecularTexture = demo.SpecularTexture; renderLightPoint.NormalTexture = demo.NormalTexture; renderLightPoint.DepthTexture = demo.DepthTexture; mesh = demo.Meshes[lightPhysicsObject.UserDataStr]; mesh.Draw(renderLightPoint); } else if (drawLight.Type == PhysicsLightType.Spot) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = false; if (enableDrawLights) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = true; lightPhysicsObject.Material.TransparencyFactor = 0.5f; lightPhysicsObject.Material.TransparencySecondPass = false; } GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); lightPhysicsObject.MainWorldTransform.GetPosition(ref position); lightPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); drawLight.GetDiffuse(ref lightDiffuse); drawLight.GetSpecular(ref lightSpecular); direction.X = -world.Row2.X; direction.Y = -world.Row2.Y; direction.Z = -world.Row2.Z; Vector3.Subtract(ref position, ref direction, out position); renderLightSpot.Enable = true; renderLightSpot.Width = objectBase.Camera.Projection.Width; renderLightSpot.Height = objectBase.Camera.Projection.Height; renderLightSpot.SetWorld(ref world); renderLightSpot.SetView(ref view); renderLightSpot.SetProjection(ref projection); renderLightSpot.SetLightPosition(ref position); renderLightSpot.SetLightDirection(ref direction); renderLightSpot.SetLightDiffuse(ref lightDiffuse); renderLightSpot.SetLightSpecular(ref lightSpecular); renderLightSpot.Range = drawLight.Range; renderLightSpot.Intensity = drawLight.Intensity; renderLightSpot.InnerRadAngle = drawLight.SpotInnerRadAngle; renderLightSpot.OuterRadAngle = drawLight.SpotOuterRadAngle; renderLightSpot.SpecularTexture = demo.SpecularTexture; renderLightSpot.NormalTexture = demo.NormalTexture; renderLightSpot.DepthTexture = demo.DepthTexture; mesh = demo.Meshes[lightPhysicsObject.UserDataStr]; mesh.Draw(renderLightSpot); } } if (!demo.EnableMenu) { GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); } else { GL.BindFramebuffer(FramebufferTarget.Framebuffer, demo.ScreenFrameBuffer); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); } GL.Disable(EnableCap.CullFace); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.Disable(EnableCap.Blend); renderScreen.Width = objectBase.Camera.Projection.Width; renderScreen.Height = objectBase.Camera.Projection.Height; renderScreen.ColorTexture = demo.ColorTexture; renderScreen.LightTexture = demo.LightTexture; quad.Draw(renderScreen); GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); } public void DrawBoundingBoxes(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; if (!enableDrawBoundingBoxes) return; float time = args.Time; PhysicsObject visiblePhysicsObject; Vector3 min, max; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); world = matrixIdentity; GL.Color3(1.0f, 1.0f, 1.0f); render.SetWorld(ref world); render.SetView(ref view); render.SetProjection(ref projection); render.Apply(); for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++) { visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i); visiblePhysicsObject.GetBoundingBox(ref boundingBox); min = boundingBox.Min; max = boundingBox.Max; cameraVertices[0].Position.X = min.X; cameraVertices[0].Position.Y = min.Y; cameraVertices[0].Position.Z = min.Z; cameraVertices[1].Position.X = max.X; cameraVertices[1].Position.Y = min.Y; cameraVertices[1].Position.Z = min.Z; cameraVertices[2].Position.X = min.X; cameraVertices[2].Position.Y = min.Y; cameraVertices[2].Position.Z = min.Z; cameraVertices[3].Position.X = min.X; cameraVertices[3].Position.Y = max.Y; cameraVertices[3].Position.Z = min.Z; cameraVertices[4].Position.X = min.X; cameraVertices[4].Position.Y = min.Y; cameraVertices[4].Position.Z = min.Z; cameraVertices[5].Position.X = min.X; cameraVertices[5].Position.Y = min.Y; cameraVertices[5].Position.Z = max.Z; cameraVertices[6].Position.X = max.X; cameraVertices[6].Position.Y = max.Y; cameraVertices[6].Position.Z = max.Z; cameraVertices[7].Position.X = min.X; cameraVertices[7].Position.Y = max.Y; cameraVertices[7].Position.Z = max.Z; cameraVertices[8].Position.X = max.X; cameraVertices[8].Position.Y = max.Y; cameraVertices[8].Position.Z = max.Z; cameraVertices[9].Position.X = max.X; cameraVertices[9].Position.Y = min.Y; cameraVertices[9].Position.Z = max.Z; cameraVertices[10].Position.X = max.X; cameraVertices[10].Position.Y = max.Y; cameraVertices[10].Position.Z = max.Z; cameraVertices[11].Position.X = max.X; cameraVertices[11].Position.Y = max.Y; cameraVertices[11].Position.Z = min.Z; cameraVertices[12].Position.X = min.X; cameraVertices[12].Position.Y = max.Y; cameraVertices[12].Position.Z = min.Z; cameraVertices[13].Position.X = min.X; cameraVertices[13].Position.Y = max.Y; cameraVertices[13].Position.Z = max.Z; cameraVertices[14].Position.X = min.X; cameraVertices[14].Position.Y = max.Y; cameraVertices[14].Position.Z = min.Z; cameraVertices[15].Position.X = max.X; cameraVertices[15].Position.Y = max.Y; cameraVertices[15].Position.Z = min.Z; cameraVertices[16].Position.X = max.X; cameraVertices[16].Position.Y = min.Y; cameraVertices[16].Position.Z = max.Z; cameraVertices[17].Position.X = max.X; cameraVertices[17].Position.Y = min.Y; cameraVertices[17].Position.Z = min.Z; cameraVertices[18].Position.X = max.X; cameraVertices[18].Position.Y = min.Y; cameraVertices[18].Position.Z = max.Z; cameraVertices[19].Position.X = min.X; cameraVertices[19].Position.Y = min.Y; cameraVertices[19].Position.Z = max.Z; cameraVertices[20].Position.X = min.X; cameraVertices[20].Position.Y = max.Y; cameraVertices[20].Position.Z = max.Z; cameraVertices[21].Position.X = min.X; cameraVertices[21].Position.Y = min.Y; cameraVertices[21].Position.Z = max.Z; cameraVertices[22].Position.X = max.X; cameraVertices[22].Position.Y = max.Y; cameraVertices[22].Position.Z = min.Z; cameraVertices[23].Position.X = max.X; cameraVertices[23].Position.Y = min.Y; cameraVertices[23].Position.Z = min.Z; GL.Begin(PrimitiveType.Lines); for (int j = 0; j < 24; j += 2) { GL.Vertex3(cameraVertices[j].Position); GL.Vertex3(cameraVertices[j + 1].Position); } GL.End(); } } public void DrawContactPoints(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; if (!enableDrawContactPoints) return; GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); float time = args.Time; PhysicsObject visiblePhysicsObject; int contactPointCount; Vector3 start1, end1, start2, end2; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); world = matrixIdentity; render.SetWorld(ref world); render.SetView(ref view); render.SetProjection(ref projection); render.Apply(); for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++) { visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i); for (int j = 0; j < visiblePhysicsObject.CollisionPairCount; j++) { contactPointCount = visiblePhysicsObject.GetCollisionPairContactPointCount(j); for (int k = 0; k < contactPointCount; k++) { visiblePhysicsObject.GetCollisionPairContactPointAnchor2(j, k, ref position); visiblePhysicsObject.GetCollisionPairContactPointNormal(j, k, ref direction); Vector3.Multiply(ref direction, 0.5f, out direction); start1 = position; end1 = direction; Vector3.Add(ref start1, ref end1, out end1); start2 = end1; end2 = direction; Vector3.Add(ref start2, ref end2, out end2); GL.Begin(PrimitiveType.Lines); GL.Color3(1.0f, 1.0f, 1.0f); GL.Vertex3(start1); GL.Vertex3(end1); GL.Color3(0.6f, 0.8f, 0.2f); GL.Vertex3(start2); GL.Vertex3(end2); GL.End(); } } } GL.DepthMask(true); GL.Enable(EnableCap.DepthTest); } public void DrawImpactFactors(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; if (!enableDrawImpactFactors) return; GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); float time = args.Time; PhysicsObject visiblePhysicsObject; int contactPointCount; Vector3 start1, end1, start2, end2; float impactFactor, velocityMagnitude; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); world = matrixIdentity; render.SetWorld(ref world); render.SetView(ref view); render.SetProjection(ref projection); render.Apply(); for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++) { visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i); for (int j = 0; j < visiblePhysicsObject.CollisionPairCount; j++) { contactPointCount = visiblePhysicsObject.GetCollisionPairContactPointCount(j); for (int k = 0; k < contactPointCount; k++) { visiblePhysicsObject.GetCollisionPairContactPointAnchor2(j, k, ref position); visiblePhysicsObject.GetCollisionPairContactPointNormal(j, k, ref direction); impactFactor = visiblePhysicsObject.GetCollisionPairContactPointImpactFactor(j, k); velocityMagnitude = Math.Min(Math.Max(visiblePhysicsObject.MainWorldTransform.GetLinearVelocityMagnitude() - visiblePhysicsObject.MaxSleepLinearVelocity, 0.0f) + Math.Max(visiblePhysicsObject.MainWorldTransform.GetAngularVelocityMagnitude() - visiblePhysicsObject.MaxSleepAngularVelocity, 0.0f), 1.0f); impactFactor *= velocityMagnitude; if (impactFactor < 0.001f) continue; Vector3.Multiply(ref direction, (float)impactFactor, out direction); Vector3.Multiply(ref direction, 0.5f, out direction); start1 = position; end1 = direction; Vector3.Add(ref start1, ref end1, out end1); start2 = end1; end2 = direction; Vector3.Add(ref start2, ref end2, out end2); GL.Begin(PrimitiveType.Lines); GL.Color3(1.0f, 1.0f, 1.0f); GL.Vertex3(start1); GL.Vertex3(end1); GL.Color3(0.6f, 0.8f, 0.2f); GL.Vertex3(start2); GL.Vertex3(end2); GL.End(); } } } GL.DepthMask(true); GL.Enable(EnableCap.DepthTest); } } }
// Copyright (C) 2015-2017 Luca Piccioni // // 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 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. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using BindingsGen.GLSpecs; namespace BindingsGen { internal class RegistryDocumentation { #region Generation Methods internal static bool GenerateDocumentation(SourceStreamWriter sw, RegistryContext ctx, Enumerant enumerant, IList<RegistryDocumentationHandler> docHandlers) { // Loads documentation information foreach (RegistryDocumentationHandler docHandler in docHandlers) docHandler.Load(); string defaultApi = ctx.Class.ToUpperInvariant(); List<KeyValuePair<string, string>> docHandlersDoc = docHandlers.Select(docHandler => new KeyValuePair<string, string>(docHandler.Api ?? defaultApi, docHandler.QueryEnumSummary(ctx, enumerant))).ToList(); if (docHandlersDoc.Count == 2 && docHandlersDoc[0].Value == docHandlersDoc[1].Value) { string api = (docHandlers[0].Api ?? defaultApi) + "|" + (docHandlers[1].Api ?? defaultApi); string doc = docHandlersDoc[0].Value; docHandlersDoc.Clear(); docHandlersDoc.Add(new KeyValuePair<string, string>(api, doc)); } if (docHandlersDoc.Count == 4) { bool func1 = docHandlersDoc[0].Value == docHandlersDoc[2].Value; bool func2 = docHandlersDoc[1].Value == docHandlersDoc[3].Value; if (func1 && func2) { string api1 = (docHandlers[0].Api ?? defaultApi) + "|" + (docHandlers[2].Api ?? defaultApi); string doc1 = docHandlersDoc[0].Value; string api2 = (docHandlers[1].Api ?? defaultApi) + "|" + (docHandlers[3].Api ?? defaultApi); string doc2 = docHandlersDoc[1].Value; docHandlersDoc.Clear(); docHandlersDoc.Add(new KeyValuePair<string, string>(api1, doc1)); docHandlersDoc.Add(new KeyValuePair<string, string>(api2, doc2)); } } sw.WriteLine("/// <summary>"); if (docHandlersDoc.Count > 1) { foreach (KeyValuePair<string, string> doc in docHandlersDoc) { sw.WriteLine("/// <para>"); sw.WriteLine("/// {0}", SplitDocumentationLines($"[{doc.Key}] {doc.Value}")); sw.WriteLine("/// </para>"); } } else { sw.WriteLine("/// {0}", SplitDocumentationLines($"[{docHandlersDoc[0].Key}] {docHandlersDoc[0].Value}")); } sw.WriteLine("/// </summary>"); // Dispose documentation information foreach (RegistryDocumentationHandler docHandler in docHandlers) docHandler.Dispose(); return true; } /// <summary> /// Generate a <see cref="Command"/> documentation using the Khronos reference pages. /// </summary> /// <param name="sw"> /// A <see cref="SourceStreamWriter"/> used to write the documentation of <paramref name="command"/>. /// </param> /// <param name="ctx"> /// A <see cref="RegistryContext"/> that defines the OpenGL specification. /// </param> /// <param name="command"> /// The <see cref="Command"/> to be documented. /// </param> /// <param name="fail"> /// /// </param> /// <param name="commandParams"> /// /// </param> /// <param name="docHandlers"> /// /// </param> internal static bool GenerateDocumentation(SourceStreamWriter sw, RegistryContext ctx, Command command, bool fail, List<CommandParameter> commandParams, IList<RegistryDocumentationHandler> docHandlers) { // Loads documentation information foreach (RegistryDocumentationHandler docHandler in docHandlers) docHandler.Load(); string defaultApi = ctx.Class.ToUpperInvariant(); #region Summary sw.WriteLine("/// <summary>"); if (docHandlers.Count > 1) { List<KeyValuePair<string, string>> docHandlersDoc = docHandlers.Select(docHandler => new KeyValuePair<string, string>(docHandler.Api ?? defaultApi, docHandler.QueryCommandSummary(ctx, command))).ToList(); if (docHandlersDoc.Count == 2 && docHandlersDoc[0].Value == docHandlersDoc[1].Value) { string api = docHandlersDoc[0].Key + "|" + docHandlersDoc[1].Key; string doc = docHandlersDoc[0].Value; docHandlersDoc.Clear(); docHandlersDoc.Add(new KeyValuePair<string, string>(api, doc)); } foreach (KeyValuePair<string, string> docHandler in docHandlersDoc) { sw.WriteLine("/// <para>"); sw.WriteLine("/// {0}", SplitDocumentationLines($"[{docHandler.Key}] {command.Prototype.Name}: {docHandler.Value}")); sw.WriteLine("/// </para>"); } } else { sw.WriteLine("/// {0}", SplitDocumentationLines( $"[{docHandlers[0].Api ?? defaultApi}] {command.Prototype.Name}: {docHandlers[0].QueryCommandSummary(ctx, command)}")); } sw.WriteLine("/// </summary>"); #endregion #region Parameters foreach (CommandParameter param in commandParams) { // Note: in the case of overloaded methods, some parameters are implicit. Skip the documentation for those parameters. if (param.IsImplicit(ctx, command)) continue; sw.WriteLine("/// <param name=\"{0}\">", param.ImplementationNameRaw); #if GENERATE_DOC_MULTIPARAMS if (docHandlers.Count > 1 && false) { foreach (RegistryDocumentationHandler docHandler in docHandlers) { List<string> paramDoc = SplitDocumentationLines(docHandler.QueryCommandParamSummary(ctx, command, param)); sw.WriteLine("/// <para>"); foreach (string line in paramDoc) sw.WriteLine("/// {0}", line); sw.WriteLine("/// </para>"); } } else { List<string> paramDoc = SplitDocumentationLines(docHandlers[0].QueryCommandParamSummary(ctx, command, param)); foreach (string line in paramDoc) sw.WriteLine("/// {0}", line); } #else List<string> paramDoc = SplitDocumentationLines(docHandlers[0].QueryCommandParamSummary(ctx, command, param)); foreach (string line in paramDoc) sw.WriteLine("/// {0}", line); #endif sw.WriteLine("/// </param>"); } #endregion #region Remarks #if GENERATE_DOC_REMARKS IEnumerable<string> remarksDoc = docHandlers[0].QueryCommandRemarks(ctx, command); List<string> remarksLines = new List<string>(remarksDoc); if (remarksLines.Count > 0 && false) { sw.WriteLine("/// <remarks>"); foreach (string remarksLine in remarksLines) { sw.WriteLine("/// <para>"); sw.WriteLine("/// {0}", SplitDocumentationLines(remarksLine)); sw.WriteLine("/// </para>"); } sw.WriteLine("/// </remarks>"); } #endif #endregion #region Errors #if GENERATE_DOC_EXCEPTIONS IEnumerable<string> errorsDoc = docHandlers[0].QueryCommandErrors(ctx, command); List<string> errorsLines = new List<string>(errorsDoc); if (remarksLines.Count > 0) { foreach (string errorLine in errorsLines) { sw.WriteLine("/// <exception cref=\"KhronosException\">"); sw.WriteLine("/// {0}", SplitDocumentationLines(errorLine)); sw.WriteLine("/// </exception>"); } } #endif #endregion #region See Also #if GENERATE_DOC_SEEALSO IEnumerable<string> seealsoDoc = docHandlers[0].QueryCommandSeeAlso(ctx, command); List<string> seealsoLines = new List<string>(seealsoDoc); if (seealsoLines.Count > 0) { foreach (string seealsoLine in seealsoLines) sw.WriteLine("/// {0}", seealsoLine); } #endif #endregion // Dispose documentation information foreach (RegistryDocumentationHandler docHandler in docHandlers) docHandler.Dispose(); return true; } #endregion #region Text Processing Utilities public static List<string> SplitDocumentationLines(string documentation) { const int maxLineLength = 120; List<string> documentationLines = new List<string>(); string[] documentationTokens = Regex.Split(documentation, " "); StringBuilder documentationLine = new StringBuilder(); for (int i = 0; i < documentationTokens.Length; i++) { if (documentationLine.Length + documentationTokens[i].Length > maxLineLength) { documentationLines.Add(documentationLine.ToString()); documentationLine = new StringBuilder(); documentationLine.Append(documentationTokens[i]); } else { documentationLine.Append(documentationTokens[i]); } if (i < documentationTokens.Length - 1) documentationLine.Append(" "); } if (documentationLine.Length > 0) documentationLines.Add(documentationLine.ToString()); return documentationLines; } public static List<string> SplitDocumentationPeriods(string documentation) { string[] periods = Regex.Split(documentation, @"(\.|\,)( |\n|\t|$)"); return new List<string>(periods); } #endregion } internal class RegistryDocumentation<T> : RegistryDocumentation, IRegistryDocumentation where T : RegistryDocumentationHandler, new() { #region Scan & Generation /// <summary> /// The API described by this documentation handler. /// </summary> public string Api { get; set; } /// <summary> /// Index all documented OpenGL commands the the EGL manual. /// </summary> public void ScanDocumentation(string path) { Console.WriteLine("Scanning registry documentation ({0})...", Api ?? "?"); foreach (string documentationFile in Directory.GetFiles(path)) { if (documentationFile.ToLowerInvariant().EndsWith(".xml") == false) continue; try { T docHandler = new T { Api = Api }; docHandler.Load(documentationFile); docHandler.Query(); foreach (string command in docHandler.Commands) { List<T> docHandlers; if (_DocMapCommands.TryGetValue(command, out docHandlers) == false) _DocMapCommands[command] = docHandlers = new List<T>(); docHandlers.Add(docHandler); } foreach (string enumValue in docHandler.Enums) { List<T> docHandlers; if (_DocMapEnums.TryGetValue(enumValue, out docHandlers) == false) _DocMapEnums[enumValue] = docHandlers = new List<T>(); docHandlers.Add(docHandler); } // Release memory docHandler.Dispose(); } catch (Exception) { // ignored } } } public bool HasDocumentation(Command command) { return _DocMapCommands.ContainsKey(command.Prototype.Name); } public bool HasDocumentation(Enumerant enumerant) { return _DocMapEnums.ContainsKey(enumerant.Name); } public List<RegistryDocumentationHandler> GetDocumentationHandlers(Enumerant enumerant) { List<T> handlers; if (_DocMapEnums.TryGetValue(enumerant.Name, out handlers)) return handlers.ConvertAll(item => (RegistryDocumentationHandler) item); return null; } public List<RegistryDocumentationHandler> GetDocumentationHandlers(Command command) { List<T> handlers; if (_DocMapCommands.TryGetValue(command.Prototype.Name, out handlers)) return handlers.ConvertAll(item => (RegistryDocumentationHandler) item); return null; } /// <summary> /// Generate a <see cref="Command"/> documentation using the Khronos reference pages. /// </summary> /// <param name="sw"> /// A <see cref="SourceStreamWriter"/> used to write the documentation of <paramref name="command"/>. /// </param> /// <param name="ctx"> /// A <see cref="RegistryContext"/> that defines the OpenGL specification. /// </param> /// <param name="command"> /// The <see cref="Command"/> to be documented. /// </param> /// <param name="fail"> /// /// </param> /// <param name="commandParams"> /// /// </param> public bool GenerateDocumentation(SourceStreamWriter sw, RegistryContext ctx, Command command, bool fail, List<CommandParameter> commandParams) { List<T> docHandlers; if (_DocMapCommands.TryGetValue(command.Prototype.Name, out docHandlers) == false) return false; return GenerateDocumentation(sw, ctx, command, true, commandParams, docHandlers.ConvertAll(item => (RegistryDocumentationHandler) item)); } public bool GenerateDocumentation(SourceStreamWriter sw, RegistryContext ctx, Enumerant enumerant) { List<T> docHandlers; if (_DocMapEnums.TryGetValue(enumerant.Name, out docHandlers) == false) return false; return GenerateDocumentation(sw, ctx, enumerant, docHandlers.ConvertAll(item => (RegistryDocumentationHandler) item)); } /// <summary> /// Map between the GL command name and the relative documentation. /// </summary> private readonly Dictionary<string, List<T>> _DocMapCommands = new Dictionary<string, List<T>>(); /// <summary> /// Map between the GL command name and the relative documentation. /// </summary> private readonly Dictionary<string, List<T>> _DocMapEnums = new Dictionary<string, List<T>>(); #endregion } internal static class CollectionExtensions { private static List<IRegistryDocumentation> GetDocRegistries(IEnumerable<IRegistryDocumentation> docs, Enumerant enumerant) { List<IRegistryDocumentation> validDocs = docs.Where(doc => doc.HasDocumentation(enumerant)).ToList(); return FilterDocRegistries(validDocs); } private static List<IRegistryDocumentation> GetDocRegistries(IEnumerable<IRegistryDocumentation> docs, Command command) { List<IRegistryDocumentation> validDocs = docs.Where(doc => doc.HasDocumentation(command)).ToList(); return FilterDocRegistries(validDocs); } private static List<IRegistryDocumentation> FilterDocRegistries(List<IRegistryDocumentation> validDocs) { if (validDocs.Exists(item => item.Api == "GL2.1") && validDocs.Exists(item => item.Api == "GL4")) validDocs.RemoveAll(item => item.Api == "GL2.1"); if (validDocs.Exists(item => item.Api == "GLES3.2") && validDocs.Exists(item => item.Api == "GLES1.1")) validDocs.RemoveAll(item => item.Api == "GLES1.1"); return validDocs; } public static void GenerateDocumentation(this ICollection<IRegistryDocumentation> docs, SourceStreamWriter sw, RegistryContext ctx, Enumerant enumerant) { if (docs == null || docs.Count == 0) return; List<IRegistryDocumentation> validDocs = GetDocRegistries(docs, enumerant); if (validDocs.Count > 0) { if (validDocs.Count > 1) { List<RegistryDocumentationHandler> handlers = new List<RegistryDocumentationHandler>(); foreach (IRegistryDocumentation docRegistry in validDocs) { List<RegistryDocumentationHandler> registryHandlers = docRegistry.GetDocumentationHandlers(enumerant); if (registryHandlers != null) handlers.AddRange(registryHandlers); } RegistryDocumentation.GenerateDocumentation(sw, ctx, enumerant, handlers); } else validDocs[0].GenerateDocumentation(sw, ctx, enumerant); } else { RegistryDocumentation.GenerateDocumentation(sw, ctx, enumerant, new List<RegistryDocumentationHandler>(new RegistryDocumentationHandler[] { new RegistryDocumentationHandlerDefault() })); } } /// <summary> /// Generate a <see cref="Command"/> documentation using the Khronos reference pages. /// </summary> /// <param name="docs"> /// /// </param> /// <param name="sw"> /// A <see cref="SourceStreamWriter"/> used to write the documentation of <paramref name="command"/>. /// </param> /// <param name="ctx"> /// A <see cref="RegistryContext"/> that defines the OpenGL specification. /// </param> /// <param name="command"> /// The <see cref="Command"/> to be documented. /// </param> /// <param name="fail"> /// /// </param> /// <param name="commandParams"> /// /// </param> public static void GenerateDocumentation(this ICollection<IRegistryDocumentation> docs, SourceStreamWriter sw, RegistryContext ctx, Command command, bool fail, List<CommandParameter> commandParams) { if (docs == null || docs.Count == 0) return; List<IRegistryDocumentation> validDocs = GetDocRegistries(docs, command); if (validDocs.Count > 0) { if (validDocs.Count > 1) { List<RegistryDocumentationHandler> handlers = new List<RegistryDocumentationHandler>(); foreach (IRegistryDocumentation docRegistry in validDocs) { List<RegistryDocumentationHandler> registryHandlers = docRegistry.GetDocumentationHandlers(command); if (registryHandlers != null) handlers.AddRange(registryHandlers); } RegistryDocumentation.GenerateDocumentation(sw, ctx, command, fail, commandParams, handlers); } else validDocs[0].GenerateDocumentation(sw, ctx, command, fail, commandParams); } else { RegistryDocumentation.GenerateDocumentation(sw, ctx, command, fail, commandParams, new List<RegistryDocumentationHandler>(new RegistryDocumentationHandler[] { new RegistryDocumentationHandlerDefault() })); } } } }
// 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.Diagnostics.Contracts; using System.Text; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. public sealed partial class FileInfo : FileSystemInfo { private string _name; [System.Security.SecurityCritical] private FileInfo() { } [System.Security.SecuritySafeCritical] public FileInfo(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); Contract.EndContractBlock(); Init(fileName); } [System.Security.SecurityCritical] private void Init(string fileName) { OriginalPath = fileName; // Must fully qualify the path for the security check string fullPath = Path.GetFullPath(fileName); _name = Path.GetFileName(fileName); FullPath = fullPath; DisplayPath = GetDisplayPath(fileName); } private string GetDisplayPath(string originalPath) { return originalPath; } [System.Security.SecuritySafeCritical] internal FileInfo(string fullPath, string originalPath) { Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!"); _name = originalPath ?? Path.GetFileName(fullPath); OriginalPath = _name; FullPath = fullPath; DisplayPath = _name; } public override string Name { get { return _name; } } public long Length { [System.Security.SecuritySafeCritical] // auto-generated get { if ((FileSystemObject.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, DisplayPath), DisplayPath); } return FileSystemObject.Length; } } /* Returns the name of the directory that the file is in */ public string DirectoryName { [System.Security.SecuritySafeCritical] get { return Path.GetDirectoryName(FullPath); } } /* Creates an instance of the parent directory */ public DirectoryInfo Directory { get { string dirName = DirectoryName; if (dirName == null) return null; return new DirectoryInfo(dirName); } } public bool IsReadOnly { get { return (Attributes & FileAttributes.ReadOnly) != 0; } set { if (value) Attributes |= FileAttributes.ReadOnly; else Attributes &= ~FileAttributes.ReadOnly; } } [System.Security.SecuritySafeCritical] // auto-generated public StreamReader OpenText() { return new StreamReader(FullPath, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); } public StreamWriter CreateText() { return new StreamWriter(FullPath, append: false); } public StreamWriter AppendText() { return new StreamWriter(FullPath, append: true); } // Copies an existing file to a new file. An exception is raised if the // destination file already exists. Use the // Copy(string, string, boolean) method to allow // overwriting an existing file. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName // and Write permissions to destFileName. // public FileInfo CopyTo(string destFileName) { if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); Contract.EndContractBlock(); destFileName = File.InternalCopy(FullPath, destFileName, false); return new FileInfo(destFileName, null); } // Copies an existing file to a new file. If overwrite is // false, then an IOException is thrown if the destination file // already exists. If overwrite is true, the file is // overwritten. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName and Create // and Write permissions to destFileName. // public FileInfo CopyTo(string destFileName, bool overwrite) { if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); Contract.EndContractBlock(); destFileName = File.InternalCopy(FullPath, destFileName, overwrite); return new FileInfo(destFileName, null); } public FileStream Create() { return File.Create(FullPath); } // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. On Win95, the file will be // deleted irregardless of whether the file is being used. // // Your application must have Delete permission to the target file. // [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.DeleteFile(FullPath); } // Tests if the given file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. // // Your application must have Read permission for the target directory. public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // User must explicitly specify opening a new file or appending to one. public FileStream Open(FileMode mode) { return Open(mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None); } public FileStream Open(FileMode mode, FileAccess access) { return Open(mode, access, FileShare.None); } public FileStream Open(FileMode mode, FileAccess access, FileShare share) { return new FileStream(FullPath, mode, access, share); } [System.Security.SecuritySafeCritical] // auto-generated public FileStream OpenRead() { return new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false); } public FileStream OpenWrite() { return new FileStream(FullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } // Moves a given file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // [System.Security.SecuritySafeCritical] public void MoveTo(string destFileName) { if (destFileName == null) throw new ArgumentNullException(nameof(destFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); Contract.EndContractBlock(); string fullDestFileName = Path.GetFullPath(destFileName); // These checks are in place to ensure Unix error throwing happens the same way // as it does on Windows.These checks can be removed if a solution to #2460 is // found that doesn't require validity checks before making an API call. if (!new DirectoryInfo(Path.GetDirectoryName(FullName)).Exists) { throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullName)); } if (!Exists) { throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, FullName), FullName); } FileSystem.Current.MoveFile(FullPath, fullDestFileName); FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. Invalidate(); } public FileInfo Replace(string destinationFileName, string destinationBackupFileName) { return Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false); } public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); return new FileInfo(destinationFileName); } // Returns the display path public override string ToString() { return DisplayPath; } public void Decrypt() { File.Decrypt(FullPath); } public void Encrypt() { File.Encrypt(FullPath); } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data. THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data. THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using System.Linq; using System.Diagnostics; using CyPhyGUIs; using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes; namespace CyPhySoT { /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhySoTInterpreter : IMgaComponentEx, IGMEVersionInfo, ICyPhyInterpreter { [ComVisible(false)] public const string RunCommand = ""; [ComVisible(false)] public string OutputBaseDir { get; set; } [ComVisible(false)] public string ProjectFilename { get; set; } /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // set up the default component parameters this.componentParameters = new SortedDictionary<string, object>(); this.componentParameters.Add("labels", ""); this.componentParameters.Add("runCommand", RunCommand); this.componentParameters.Add("output_dir", string.Empty); this.componentParameters.Add("automation", "false"); this.componentParameters.Add("do_config", "true"); this.componentParameters.Add("configuration", string.Empty); this.componentParameters.Add("test_bench_name", string.Empty); // Mimic CyPET and CyPhy2Modelica_v2 //GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); } [ComVisible(false)] public void SetupOutputDirectory(MgaProject project, MgaFCO currentobj) { var projectDir = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)); //this.OutputBaseDir = Path.Combine(projectDir, "results", currentobj.Name); this.OutputBaseDir = this.mainParameters.OutputDirectory; if (Directory.Exists(this.OutputBaseDir) == false) { Directory.CreateDirectory(this.OutputBaseDir); } } private bool CheckModel(MgaFCO currentobj) { bool error = false; // checks // checks are done return error; } class CycleException : Exception { public CycleException(string message) : base(message) { } } [ComVisible(false)] public Dictionary<MgaFCO, List<MgaFCO>> DependencyGraph { get; set; } delegate void dfs_visit(MgaFCO fco, ref List<MgaFCO> out_); /// <summary> /// /// </summary> /// <returns>True if dependency cannot be determined.</returns> private bool UpdateDependency(MgaModel testBenchSuite) { this.Logger.WriteDebug("Updating test bench dependencies ..."); HashSet<MgaFCO> toProcess = new HashSet<MgaFCO>(new MgaObjectEqualityComparor<MgaFCO>()); // Find all FCOs with no outgoing connections foreach (MgaFCO fco in testBenchSuite.ChildFCOs.Cast<MgaFCO>().Where(fco => fco.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION)) { if (fco.PartOfConns.Cast<MgaConnPoint>().Where(connpoint => connpoint.ConnRole == "src" && connpoint.References.Count == 0).Count() == 0) { if (fco.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE) { MgaReference reference = (MgaReference)fco; if (reference.UsedByConns.Cast<MgaConnPoint>().Where(connpoint => connpoint.ConnRole == "src").Count() == 0) { toProcess.Add(fco); } } else { toProcess.Add(fco); } } } var DependencyGraph = new Dictionary<MgaFCO, List<MgaFCO>>(new MgaObjectEqualityComparor<MgaFCO>()); HashSet<MgaFCO> tempMarked = new HashSet<MgaFCO>(new MgaObjectEqualityComparor<MgaFCO>()); Dictionary<MgaFCO, List<MgaFCO>> resident = new Dictionary<MgaFCO, List<MgaFCO>>(new MgaObjectEqualityComparor<MgaFCO>()); dfs_visit Visit = null; Visit = delegate(MgaFCO fco, ref List<MgaFCO> out_) { if (tempMarked.Contains(fco)) { throw new CycleException("Cycle involving " + fco.Name); } List<MgaFCO> previousOut; if (!resident.TryGetValue(fco, out previousOut)) { //GMEConsole.Out.WriteLine("" + fco.Name); tempMarked.Add(fco); IEnumerable<MgaConnPoint> connections = fco.PartOfConns.Cast<MgaConnPoint>().Where(cp => cp.ConnRole != "src"); if (fco.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE) { MgaReference reference = (MgaReference)fco; connections = connections.Concat(reference.UsedByConns.Cast<MgaConnPoint>().Where(cp => cp.ConnRole != "src" && cp.References[1] == reference)); } foreach (MgaConnPoint connpoint in connections) { MgaSimpleConnection conn = (MgaSimpleConnection)connpoint.Owner; MgaFCO other = conn.Src; if (conn.SrcReferences.Count > 0) { other = (connpoint.Owner as MgaSimpleConnection).SrcReferences[1]; } // GMEConsole.Out.WriteLine("&nbsp; " + other.Name); Visit(other, ref out_); List<MgaFCO> dependents; if (DependencyGraph.TryGetValue(fco, out dependents) == false) { dependents = DependencyGraph[fco] = new List<MgaFCO>(); } if (other.Meta.Name == typeof(CyPhy.TestBenchRef).Name) { dependents.Add(other); } } tempMarked.Remove(fco); out_.Add(fco); resident.Add(fco, out_); } else { if (previousOut != out_) { foreach (MgaFCO fco2 in out_) { resident[fco2] = previousOut; } previousOut.AddRange(out_); out_ = previousOut; } } }; if (toProcess.Count == 0) { this.Logger.WriteError("Cycle in TestBench dependencies detected"); return true; } while (toProcess.Count > 0) { var before = toProcess.Count; List<MgaFCO> out_ = new List<MgaFCO>(); MgaFCO fco = toProcess.First(); try { Visit(fco, ref out_); } catch (CycleException ex) { this.Logger.WriteError(ex.Message); this.Logger.WriteError(ex.ToString()); return true; } foreach (MgaFCO fco2 in out_) { toProcess.Remove(fco2); } var after = toProcess.Count; if (after >= before) { string msg = "Determining dependency is not progressing."; this.Logger.WriteError(msg); return true; } } this.DependencyGraph = DependencyGraph.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Distinct().ToList()); foreach (KeyValuePair<MgaFCO, List<MgaFCO>> fcos in DependencyGraph) { this.Logger.WriteDebug("Dependency chain {0}: {1}", fcos.Key.Name, string.Join(" ", fcos.Value.Select(x => x.Name))); } return false; } private SotConfig sotConfig = new SotConfig(); [ComVisible(false)] public List<TestBench> TestBenches = new List<TestBench>(); [ComVisible(false)] public List<TestBench> GetTestbenchesFromModel(MgaProject project, MgaModel currentobj, string outputBaseDir) { componentParameters = null; //this.logFileName = Path.Combine( // Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)), // "log", // this.ComponentName + "." + System.Diagnostics.Process.GetCurrentProcess().Id + ".log"); //META.Logger.AddFileListener(this.logFileName, this.ComponentName, project); // GMEConsole = GMEConsole.CreateFromProject(project); bool disposeLogger = false; if (this.Logger == null) { this.Logger = new GMELogger(project, this.ComponentName); disposeLogger = true; } MgaGateway = new MgaGateway(project); MgaGateway.PerformInTransaction(delegate { this._GetTestbenchesFromModel(currentobj, outputBaseDir); }); if (this.Logger != null && disposeLogger) { this.Logger.Dispose(); this.Logger = null; } //META.Logger.RemoveFileListener(this.ComponentName); return this.TestBenches; } private void _GetTestbenchesFromModel(MgaModel sot, string outputBaseDir) { var tbRefs = sot .ChildObjects .OfType<MgaReference>() .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name); foreach (var tbRef in tbRefs) { var task = tbRef .Referred .ChildObjects .OfType<MgaReference>() .FirstOrDefault(x => x.Meta.Name == typeof(CyPhy.WorkflowRef).Name) .Referred .ChildObjects .OfType<MgaAtom>() .FirstOrDefault(); var parameters = task.StrAttrByName["Parameters"]; var parametersDict = new Dictionary<string, string>(); if (string.IsNullOrWhiteSpace(parameters) == false) { try { parametersDict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(parameters); } catch (Exception ex) { //Console.WriteLine(ex); //Trace.TraceWarning(ex.ToString()); this.Logger.WriteWarning(ex.ToString()); } } var testbench = new TestBench(); testbench.OutputDirectory = GetRandomTBDir(outputBaseDir); if (Directory.Exists(testbench.OutputDirectory) == false) { Directory.CreateDirectory(testbench.OutputDirectory); } testbench.Project = tbRef.Project; testbench.CurrentObj = tbRef.Referred; testbench.ParamInvoke = paramInvoked; testbench.Name = string.Format("{0}__{1}", tbRef.Referred.RegistryValue["TestBenchUniqueName"], tbRef.Referred.Name); testbench.ProgId = task.StrAttrByName["COMName"]; testbench.WorkflowParametersDict = parametersDict; TestBenches.Add(testbench); } UpdateDependency(sot); if (this.DependencyGraph == null) { this.Logger.WriteWarning("Dependency was not determined running all test benches without dependencies."); return; } // Update Testbench upstream and downstream dependencies based on the MgaFCO dependency map/list foreach (var chain in this.DependencyGraph.Where(x => x.Key.Meta.Name == typeof(CyPhy.TestBenchRef).Name)) { this.TestBenches.First(x => x.CurrentObj.ID == ((MgaReference)chain.Key).Referred.ID).UpstreamTestBenches.AddRange( chain.Value.Select(x => this.TestBenches.First(y => y.CurrentObj.ID == ((MgaReference)x).Referred.ID))); } foreach (var tb in this.TestBenches) { foreach (var upstream in tb.UpstreamTestBenches) { upstream.DownstreamTestBenches.Add(tb); } tb.CollectDeps(); } } private string GetRandomTBDir(string outputBaseDir) { string randomFolderName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); List<char> illegalStartChars = new List<char>() { '0','1','2','3','4','5','6','7','8','9' }; string OutputSubDir = Path.Combine( outputBaseDir, randomFolderName); int maxFolders = 0; while (illegalStartChars.Contains(randomFolderName.FirstOrDefault()) || File.Exists(OutputSubDir) || Directory.Exists(OutputSubDir)) { if (maxFolders++ > 2000000) { throw new Exception( string.Format("Number of tries ({0}) to create an output folder exceeded in {0}. ", maxFolders, outputBaseDir)); } randomFolderName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); OutputSubDir = Path.Combine( outputBaseDir, randomFolderName); } return OutputSubDir; } private void WriteSoTManifest() { using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json"))) { writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented)); } } internal int paramInvoked = 0; #region IMgaComponentEx Members private MgaGateway MgaGateway { get; set; } //private GMEConsole GMEConsole { get; set; } string logFileName { get; set; } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { this.paramInvoked = param; this.ProjectFilename = project.ProjectConnStr.Substring("MGA=".Length); sotConfig.OriginalProjectFileName = this.ProjectFilename; if (!enabled) { return; } string currentWorkDir = System.IO.Directory.GetCurrentDirectory(); try { this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName); this.Logger.GMEConsoleLoggingLevel = SmartLogger.MessageType_enum.Debug; if (currentobj == null) { this.Logger.WriteFailed("CyPhySOT must be called from a TestBenchSuite."); return; } this.Logger.WriteInfo("Starting CyPhySoT..."); System.Windows.Forms.Application.DoEvents(); // Need to call this interpreter in the same way as the MasterInterpreter will call it. // initialize main parameters var parameters = new InterpreterMainParameters() { Project = project, CurrentFCO = currentobj, SelectedFCOs = selectedobjs, StartModeParam = param, VerboseConsole = true }; this.mainParameters = parameters; parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length)); string kindName = string.Empty; // Set up the output directory and check Kind of currentObj. MgaGateway.PerformInTransaction(delegate { string outputDirName = project.Name; if (currentobj != null) { outputDirName = currentobj.Name; kindName = currentobj.MetaBase.Name; } parameters.OutputDirectory = Path.GetFullPath(Path.Combine( parameters.ProjectDirectory, "results", outputDirName)); //this.Parameters.PackageName = Modelica.Factory.GetModifiedName(currentobj.Name); }); if (string.IsNullOrEmpty(kindName) == false && kindName != typeof(CyPhyClasses.TestBenchSuite).Name) { this.Logger.WriteFailed("CyPhySOT must be called from a TestBenchSuite."); return; } PreConfigArgs preConfigArgs = new PreConfigArgs(); preConfigArgs.ProjectDirectory = parameters.ProjectDirectory; // call the preconfiguration with no parameters and get preconfig var preConfig = this.PreConfig(preConfigArgs); // get previous GUI config var previousConfig = META.ComComponent.DeserializeConfiguration( parameters.ProjectDirectory, typeof(CyPhySoTSettings), this.ComponentProgID); // get interpreter config through GUI var config = this.DoGUIConfiguration(preConfig, previousConfig); if (config == null) { this.Logger.WriteWarning("Operation cancelled by the user."); return; } // if config is valid save it and update it on the file system META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID); // assign the new configuration to mainParameters parameters.config = config; // call the main (ICyPhyComponent) function this.Main(parameters); } catch (Exception ex) { this.Logger.WriteError("{0} has finished with critical errors see log file {1}.", this.ComponentName, this.logFileName); this.Logger.WriteError(ex.ToString()); } finally { if (this.Logger != null) { this.Logger.Dispose(); this.Logger = null; } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } } /// <summary> /// Helper function for copying entire common folder for post processing /// </summary> /// <param name="source">Source directory</param> /// <param name="target">Destination directory</param> private static void CopyFilesRecursively( DirectoryInfo source, DirectoryInfo target) { foreach (DirectoryInfo dir in source.GetDirectories()) { CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name)); } foreach (FileInfo file in source.GetFiles()) { file.CopyTo(Path.Combine(target.FullName, file.Name), true); } } private ComponentStartMode Convert(int param) { switch (param) { case (int)ComponentStartMode.GME_BGCONTEXT_START: return ComponentStartMode.GME_BGCONTEXT_START; case (int)ComponentStartMode.GME_BROWSER_START: return ComponentStartMode.GME_BROWSER_START; case (int)ComponentStartMode.GME_CONTEXT_START: return ComponentStartMode.GME_CONTEXT_START; case (int)ComponentStartMode.GME_EMBEDDED_START: return ComponentStartMode.GME_EMBEDDED_START; case (int)ComponentStartMode.GME_ICON_START: return ComponentStartMode.GME_ICON_START; case (int)ComponentStartMode.GME_MAIN_START: return ComponentStartMode.GME_MAIN_START; case (int)ComponentStartMode.GME_MENU_START: return ComponentStartMode.GME_MENU_START; case (int)ComponentStartMode.GME_SILENT_MODE: return ComponentStartMode.GME_SILENT_MODE; } return ComponentStartMode.GME_SILENT_MODE; } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion #region CyPhyGUIs /// <summary> /// Result of the latest run of this interpreter. /// </summary> private InterpreterResult result = new InterpreterResult(); /// <summary> /// Parameter of this run. /// </summary> private InterpreterMainParameters mainParameters { get; set; } /// <summary> /// Output directory where all files must be generated /// </summary> private string OutputDirectory { get { return this.mainParameters.OutputDirectory; } } private void UpdateSuccess(string message, bool success) { this.result.Success = this.result.Success && success; this.runtime.Enqueue(new Tuple<string, TimeSpan>(message, DateTime.Now - this.startTime)); if (success) { this.Logger.WriteDebug("{0} : OK", message); } else { this.Logger.WriteError("{0} : FAILED", message); } } public CyPhyGUIs.GMELogger Logger { get; set; } ///// <summary> ///// Name of the log file. (It is not a full path) ///// </summary> //private string LogFileFilename { get; set; } ///// <summary> ///// Full path to the log file. ///// </summary> //private string LogFilePath //{ // get // { // return Path.Combine(this.result.LogFileDirectory, this.LogFileFilename); // } //} /// <summary> /// ProgId of the configuration class of this interpreter. /// </summary> public string InterpreterConfigurationProgId { get { return (typeof(CyPhySoT.CyPhySoTSettings).GetCustomAttributes(typeof(ProgIdAttribute), false)[0] as ProgIdAttribute).Value; } } /// <summary> /// Preconfig gets called first. No transaction is open, but one may be opened. /// In this function model may be processed and some object ids get serialized /// and returned as preconfiguration (project-wise configuration). /// </summary> /// <param name="preConfigParameters"></param> /// <returns>Null if no configuration is required by the DoGUIConfig.</returns> public IInterpreterPreConfiguration PreConfig(IPreConfigParameters parameters) { return null; } public IInterpreterConfiguration DoGUIConfiguration(IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig) { var settings = previousConfig as CyPhySoT.CyPhySoTSettings; if (settings == null) { settings = new CyPhySoT.CyPhySoTSettings(); } return settings; } private Queue<Tuple<string, TimeSpan>> runtime = new Queue<Tuple<string, TimeSpan>>(); private DateTime startTime = DateTime.Now; public IInterpreterResult Main(IInterpreterMainParameters parameters) { this.runtime.Clear(); this.mainParameters = (InterpreterMainParameters)parameters; this.result.Success = true; var configSuccess = this.mainParameters != null; this.paramInvoked = this.mainParameters.StartModeParam; this.ProjectFilename = this.mainParameters.Project.ProjectConnStr.Substring("MGA=".Length); this.OutputBaseDir = this.mainParameters.OutputDirectory; sotConfig.OriginalProjectFileName = this.ProjectFilename; bool disposeLogger = false; if (this.Logger == null) { this.Logger = new CyPhyGUIs.GMELogger(this.mainParameters.Project, this.ComponentName); this.Logger.WriteInfo("Running CyPhySoT"); System.Windows.Forms.Application.DoEvents(); disposeLogger = true; } if (this.mainParameters.VerboseConsole) { this.Logger.GMEConsoleLoggingLevel = SmartLogger.MessageType_enum.Debug; } else { this.Logger.GMEConsoleLoggingLevel = SmartLogger.MessageType_enum.Info; } CyPhy.TestBenchSuite tbs = CyPhyClasses.TestBenchSuite.Cast(parameters.CurrentFCO); // MgaGateway.PerformInTransaction(delegate // { // foreach (var testBenchRef in tbs.Children.TestBenchRefCollection) // { // if (testBenchRef.Referred == null) // { // continue; // } // var testBench = testBenchRef.Referred.TestBenchType; // if (testBench != null && // testBench.Impl.MetaBase.Name != (typeof(CyPhy.TestBench)).Name) // { // this.Logger.WriteError(string.Format(@"Test benches must currently // be of type TestBench in a CyPhySoT. Please see {0}.", // testBenchRef.ToHyperLink())); // this.result.Success = false; // object automation; // if (this.componentParameters != null && // this.componentParameters.TryGetValue("automation", out automation)) // { // if ((string)automation == "true") // { // throw new NotSupportedException(@"Error: only test benches of // type TestBench are currently supported in a CyPhySoT!"); // } // } // } // } // }); if (this.result.Success == false) { return this.result; } var asyncResult = this.Logger.LoggingVersionInfo.BeginInvoke(parameters.Project, null, null); var header = this.Logger.LoggingVersionInfo.EndInvoke(asyncResult); this.Logger.WriteDebug(header); this.UpdateSuccess("Configuration", configSuccess); this.result.Labels = ""; //this.result.LogFileDirectory = Path.Combine(this.mainParameters.ProjectDirectory, "log"); //this.LogFileFilename = this.ComponentName + "." + System.Diagnostics.Process.GetCurrentProcess().Id + ".log"; //META.Logger.AddFileListener(this.LogFilePath, this.ComponentName, parameters.Project); try { MgaGateway.PerformInTransaction(delegate { this.WorkInMainTransaction(); }, abort: true); this.WorkOutsideOfMainTransaction(); this.PrintRuntimeStatistics(); if (this.result.Success) { this.Logger.WriteInfo("CyPhySoT finished successfully."); this.Logger.WriteInfo("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory); this.Logger.WriteDebug("[SUCCESS: {0}]", this.result.Success); } else { this.Logger.WriteError("CyPhySoT failed! See error messages above."); } } finally { if (this.Logger != null && disposeLogger) { this.Logger.Dispose(); this.Logger = null; } if (MgaGateway != null && MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; //GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } //META.Logger.RemoveFileListener(this.ComponentName); return this.result; } private void PrintRuntimeStatistics() { this.Logger.WriteDebug("======================================================"); this.Logger.WriteDebug("Start time: {0}", this.startTime); foreach (var time in this.runtime) { this.Logger.WriteDebug("{0} = {1}", time.Item1, time.Item2); } this.Logger.WriteDebug("======================================================"); } #endregion private void WorkInMainTransaction() { // 1) check model, if fails return success = false this.Logger.WriteDebug("Checking rules..."); var checker = new Rules.Checker(this.mainParameters, this.Logger); var successRules = checker.Check(this.result.Traceability); this.UpdateSuccess("SoT check", successRules); if (successRules == false) { checker.PrintDetails(); return; } // 1.5) TODO : Integrate the checks here to checker if (UpdateDependency(this.mainParameters.CurrentFCO as MgaModel)) { this.UpdateSuccess("UpdateDependency - failed", false); return; } // 2) Setup the output directory sotConfig.SoTID = this.mainParameters.CurrentFCO.ID; //this.SetupOutputDirectory(this.mainParameters.Project, this.mainParameters.CurrentFCO); //this.UpdateSuccess("SetupOutputDirectory", true); } private void WorkOutsideOfMainTransaction() { if (Directory.Exists(this.OutputBaseDir) == false) { Directory.CreateDirectory(this.OutputBaseDir); } // 3) Copy mga project file to output directory string outputFile = Path.Combine(this.OutputBaseDir, Path.GetFileName(this.ProjectFilename)); this.mainParameters.Project.Save("MGA=" + outputFile, true); sotConfig.ProjectFileName = Path.GetFileName(outputFile); this.CleanUpTempMgaProject(outputFile); this.UpdateSuccess("Copy mga project", true); // 4) Copy Interpreter configuration files var projectDir = Path.GetDirectoryName(this.ProjectFilename); foreach (var configXML in Directory.GetFiles(Path.Combine(projectDir, "config"), "*.xml")) { var newConfigXML = configXML.Replace(projectDir, this.OutputBaseDir); if (Directory.Exists(Path.GetDirectoryName(newConfigXML)) == false) { Directory.CreateDirectory(Path.GetDirectoryName(newConfigXML)); } File.Copy(configXML, newConfigXML, true); } // CyPhy2CAD stores its config in an xml file instead of in the project //string CADConfigXml = Path.Combine(Path.GetDirectoryName(projectFile), "CyPhy2CAD_config.xml"); //if (File.Exists(CADConfigXml)) //{ // string CADConfigXmlCopy = Path.Combine(OutputBaseDir, "CyPhy2CAD_config.xml"); // File.Copy(CADConfigXml, CADConfigXmlCopy, true); //} //string ModelicaConfigXml = Path.Combine(Path.GetDirectoryName(projectFile), // "CyPhy2Modelica_config_v2.xml"); //if (File.Exists(ModelicaConfigXml)) //{ // string ModelicaConfigXmlCopy = Path.Combine(OutputBaseDir, // "CyPhy2Modelica_config_v2.xml"); // File.Copy(ModelicaConfigXml, ModelicaConfigXmlCopy, true); //} this.UpdateSuccess("Copied interpreter configs", true); // 5) Write out the manifest.json file WriteSoTManifest(); this.UpdateSuccess("WriteSoTManifest", true); } private void CleanUpTempMgaProject(string outputFile) { var newProject = new MgaProject(); bool ro_mode; // open the copied temporary mga file newProject.Open("MGA=" + outputFile, out ro_mode); IMgaTerritory terr = null; try { // create a new transaction terr = newProject.BeginTransactionInNewTerr(); // get the sot object on which the job manager will operate var sot = newProject.GetObjectByID(sotConfig.SoTID); if (sot != null) { // if the sot object exists in the project GME.MGA.Meta.objtype_enum objtype; MgaObject parent; // get the parent folder of which this SoT belongs to. sot.GetParent(out parent, out objtype); if (objtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { // if it is really a folder cast it var parentSoTFolder = parent as MgaFolder; // get all SoT objects in the folder except the one we operate on // mark them for deletion var sotsToDelete = parentSoTFolder .ChildFCOs .Cast<MgaFCO>() .Where(x => x.ID != sotConfig.SoTID) .ToList(); try { // destroy all SoTs that are not used by this sot run sotsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } // get all not null test bench objects that this sot run uses. var referredTBsInSot = sot .ChildObjects .OfType<MgaReference>() .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name && x.Referred != null) .Select(x => x.Referred) .Cast<MgaModel>() .ToList(); foreach (var tb in referredTBsInSot) { GME.MGA.Meta.objtype_enum tbParentObjtype; MgaObject tbParent; // get the parent folder where the referenced test bench located tb.GetParent(out tbParent, out tbParentObjtype); if (tbParentObjtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { var parentTBFolder = tbParent as MgaFolder; // get all test benches that are not used by the sot // WARNING: sometimes COM object comparison can fail this code is not the safest. var tbsToDelete = parentTBFolder .ChildFCOs .OfType<MgaModel>() .Where(x => referredTBsInSot.Contains(x) == false) .ToList(); try { // delete test benches that sot does not use tbsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } } } } } // commit changes if everything is successful newProject.CommitTransaction(); } catch { // abort all changes if exception occured newProject.AbortTransaction(); } finally { if (terr != null) { // destroy the territory we were working in if it is not null terr.Destroy(); } } // close the project AND save all changes newProject.Close(); } } class MgaObjectEqualityComparor<T> : EqualityComparer<T> where T : IMgaObject { public override bool Equals(T x, T y) { return x.ID.Equals(y.ID); } public override int GetHashCode(T obj) { return obj.ID.GetHashCode(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; //using Region = Apache.Geode.Client.IRegion<Object, Object>; using AssertionException = Apache.Geode.Client.AssertionException; public abstract class ThinClientSecurityAuthzTestBase : ThinClientRegionSteps { #region Protected members protected const string SubregionName = "AuthSubregion"; protected const string CacheXml1 = "cacheserver_notify_subscription.xml"; protected const string CacheXml2 = "cacheserver_notify_subscription2.xml"; #endregion #region Private methods private static string IndicesToString(int[] indices) { string str = string.Empty; if (indices != null && indices.Length > 0) { str += indices[0]; for (int index = 1; index < indices.Length; ++index) { str += ','; str += indices[index]; } } return str; } private IRegion<TKey, TValue> CreateSubregion<TKey, TValue>(IRegion<TKey, TValue> region) { Util.Log("CreateSubregion " + SubregionName); IRegion<TKey, TValue> subregion = region.GetSubRegion(SubregionName); if (subregion == null) { //subregion = region.CreateSubRegion(SubregionName, region.Attributes); subregion = CacheHelper.GetRegion<TKey, TValue>(region.FullPath).CreateSubRegion(SubregionName, region.Attributes); } return subregion; } private bool CheckFlags(OpFlags flags, OpFlags checkFlag) { return ((flags & checkFlag) == checkFlag); } protected void DoOp(OperationCode op, int[] indices, OpFlags flags, ExpectedResult expectedResult) { DoOp(op, indices, flags, expectedResult, null, false); } protected void DoOp(OperationCode op, int[] indices, OpFlags flags, ExpectedResult expectedResult, Properties<string, string> creds, bool isMultiuser) { IRegion<object, object> region; if(isMultiuser) region = CacheHelper.GetRegion<object, object>(RegionName, creds); else region = CacheHelper.GetRegion<object, object>(RegionName); if (CheckFlags(flags, OpFlags.UseSubRegion)) { IRegion<object, object> subregion = null; if (CheckFlags(flags, OpFlags.NoCreateSubRegion)) { subregion = region.GetSubRegion(SubregionName); if (CheckFlags(flags, OpFlags.CheckNoRegion)) { Assert.IsNull(subregion); return; } else { Assert.IsNotNull(subregion); } } else { subregion = CreateSubregion(region); if (isMultiuser) subregion = region.GetSubRegion(SubregionName); } Assert.IsNotNull(subregion); region = subregion; } else if (CheckFlags(flags, OpFlags.CheckNoRegion)) { Assert.IsNull(region); return; } else { Assert.IsNotNull(region); } string valPrefix; if (CheckFlags(flags, OpFlags.UseNewVal)) { valPrefix = NValuePrefix; } else { valPrefix = ValuePrefix; } int numOps = indices.Length; Util.Log("Got DoOp for op: " + op + ", numOps: " + numOps + ", indices: " + IndicesToString(indices)); bool exceptionOccured = false; bool breakLoop = false; for (int indexIndex = 0; indexIndex < indices.Length; ++indexIndex) { if (breakLoop) { break; } int index = indices[indexIndex]; string key = KeyPrefix + index; string expectedValue = (valPrefix + index); try { switch (op) { case OperationCode.Get: Object value = null; if (CheckFlags(flags, OpFlags.LocalOp)) { int sleepMillis = 100; int numTries = 30; bool success = false; while (!success && numTries-- > 0) { if (!isMultiuser && region.ContainsValueForKey(key)) { value = region[key]; success = expectedValue.Equals(value.ToString()); if (CheckFlags(flags, OpFlags.CheckFail)) { success = !success; } } else { value = null; success = CheckFlags(flags, OpFlags.CheckFail); } if (!success) { Thread.Sleep(sleepMillis); } } } else { if (!isMultiuser) { if (CheckFlags(flags, OpFlags.CheckNoKey)) { Assert.IsFalse(region.GetLocalView().ContainsKey(key)); } else { Assert.IsTrue(region.GetLocalView().ContainsKey(key)); region.GetLocalView().Invalidate(key); } } try { value = region[key]; } catch (Client.KeyNotFoundException ) { Util.Log("KeyNotFoundException while getting key. should be ok as we are just testing auth"); } } if (!isMultiuser && value != null) { if (CheckFlags(flags, OpFlags.CheckFail)) { Assert.AreNotEqual(expectedValue, value.ToString()); } else { Assert.AreEqual(expectedValue, value.ToString()); } } break; case OperationCode.Put: region[key] = expectedValue; break; case OperationCode.Destroy: if (!isMultiuser && !region.GetLocalView().ContainsKey(key)) { // Since DESTROY will fail unless the value is present // in the local cache, this is a workaround for two cases: // 1. When the operation is supposed to succeed then in // the current AuthzCredentialGenerators the clients having // DESTROY permission also has CREATE/UPDATE permission // so that calling region.Put() will work for that case. // 2. When the operation is supposed to fail with // NotAuthorizedException then in the current // AuthzCredentialGenerators the clients not // having DESTROY permission are those with reader role that have // GET permission. // // If either of these assumptions fails, then this has to be // adjusted or reworked accordingly. if (CheckFlags(flags, OpFlags.CheckNotAuthz)) { value = region[key]; Assert.AreEqual(expectedValue, value.ToString()); } else { region[key] = expectedValue; } } if ( !isMultiuser && CheckFlags(flags, OpFlags.LocalOp)) { region.GetLocalView().Remove(key); //Destroyed replaced by Remove() API } else { region.Remove(key); //Destroyed replaced by Remove API } break; //TODO: Need to fix Stack overflow exception.. case OperationCode.RegisterInterest: if (CheckFlags(flags, OpFlags.UseList)) { breakLoop = true; // Register interest list in this case List<CacheableKey> keyList = new List<CacheableKey>(numOps); for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; keyList.Add(KeyPrefix + keyNum); } region.GetSubscriptionService().RegisterKeys(keyList.ToArray()); } else if (CheckFlags(flags, OpFlags.UseRegex)) { breakLoop = true; region.GetSubscriptionService().RegisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']'); } else if (CheckFlags(flags, OpFlags.UseAllKeys)) { breakLoop = true; region.GetSubscriptionService().RegisterAllKeys(); } break; //TODO: Need to fix Stack overflow exception.. case OperationCode.UnregisterInterest: if (CheckFlags(flags, OpFlags.UseList)) { breakLoop = true; // Register interest list in this case List<CacheableKey> keyList = new List<CacheableKey>(numOps); for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; keyList.Add(KeyPrefix + keyNum); } region.GetSubscriptionService().UnregisterKeys(keyList.ToArray()); } else if (CheckFlags(flags, OpFlags.UseRegex)) { breakLoop = true; region.GetSubscriptionService().UnregisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']'); } else if (CheckFlags(flags, OpFlags.UseAllKeys)) { breakLoop = true; region.GetSubscriptionService().UnregisterAllKeys(); } break; case OperationCode.Query: breakLoop = true; ISelectResults<object> queryResults; if (!isMultiuser) { queryResults = (ResultSet<object>)region.Query<object>( "SELECT DISTINCT * FROM " + region.FullPath); } else { queryResults = CacheHelper.getMultiuserCache(creds).GetQueryService().NewQuery<object>("SELECT DISTINCT * FROM " + region.FullPath).Execute(); } Assert.IsNotNull(queryResults); if (!CheckFlags(flags, OpFlags.CheckFail)) { Assert.AreEqual(numOps, queryResults.Size); } //CacheableHashSet querySet = new CacheableHashSet(queryResults.Size); List<string> querySet = new List<string>(queryResults.Size); ResultSet<object> rs = queryResults as ResultSet<object>; foreach ( object result in rs) { querySet.Add(result.ToString()); } for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; string expectedVal = valPrefix + keyNumIndex; if (CheckFlags(flags, OpFlags.CheckFail)) { Assert.IsFalse(querySet.Contains(expectedVal)); } else { Assert.IsTrue(querySet.Contains(expectedVal)); } } break; case OperationCode.RegionDestroy: breakLoop = true; if ( !isMultiuser && CheckFlags(flags, OpFlags.LocalOp)) { region.GetLocalView().DestroyRegion(); } else { region.DestroyRegion(); } break; case OperationCode.GetServerKeys: breakLoop = true; ICollection<object> serverKeys = region.Keys; break; //TODO: Need to fix System.ArgumentOutOfRangeException: Index was out of range. Know issue with GetAll() case OperationCode.GetAll: //ICacheableKey[] keymap = new ICacheableKey[5]; List<object> keymap = new List<object>(); for (int i = 0; i < 5; i++) { keymap.Add(i); //CacheableInt32 item = CacheableInt32.Create(i); //Int32 item = i; // NOTE: GetAll should operate right after PutAll //keymap[i] = item; } Dictionary<Object, Object> entrymap = new Dictionary<Object, Object>(); //CacheableHashMap entrymap = CacheableHashMap.Create(); region.GetAll(keymap, entrymap, null, false); if (entrymap.Count < 5) { Assert.Fail("DoOp: Got fewer entries for op " + op); } break; case OperationCode.PutAll: // NOTE: PutAll should operate right before GetAll //CacheableHashMap entrymap2 = CacheableHashMap.Create(); Dictionary<Object, Object> entrymap2 = new Dictionary<object, object>(); for (int i = 0; i < 5; i++) { //CacheableInt32 item = CacheableInt32.Create(i); Int32 item = i; entrymap2.Add(item, item); } region.PutAll(entrymap2); break; case OperationCode.RemoveAll: Dictionary<Object, Object> entrymap3 = new Dictionary<object, object>(); for (int i = 0; i < 5; i++) { //CacheableInt32 item = CacheableInt32.Create(i); Int32 item = i; entrymap3.Add(item, item); } region.PutAll(entrymap3); ICollection<object> keys = new LinkedList<object>(); for (int i = 0; i < 5; i++) { Int32 item = i; keys.Add(item); } region.RemoveAll(keys); break; case OperationCode.ExecuteCQ: Pool/*<object, object>*/ pool = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_"); QueryService qs; if (pool != null) { qs = pool.GetQueryService(); } else { //qs = CacheHelper.DCache.GetQueryService(); qs = null; } CqAttributesFactory<object, object> cqattrsfact = new CqAttributesFactory<object, object>(); CqAttributes<object, object> cqattrs = cqattrsfact.Create(); CqQuery<object, object> cq = qs.NewCq("cq_security", "SELECT * FROM /" + region.Name, cqattrs, false); qs.ExecuteCqs(); qs.StopCqs(); qs.CloseCqs(); break; case OperationCode.ExecuteFunction: if (!isMultiuser) { Pool/*<object, object>*/ pool2 = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_"); if (pool2 != null) { Client.FunctionService<object>.OnServer(pool2).Execute("securityTest"); Client.FunctionService<object>.OnRegion<object, object>(region).Execute("FireNForget"); } else { expectedResult = ExpectedResult.Success; } } else { //FunctionService fs = CacheHelper.getMultiuserCache(creds).GetFunctionService(); //Execution exe = fs.OnServer(); IRegionService userCache = CacheHelper.getMultiuserCache(creds); Apache.Geode.Client.Execution<object> exe = Client.FunctionService<object>.OnServer(userCache); exe.Execute("securityTest"); exe = Client.FunctionService<object>.OnServers(userCache); Client.FunctionService<object>.OnRegion<object, object>(region); Client.FunctionService<object>.OnRegion<object, object>(userCache.GetRegion<object, object>(region.Name)).Execute("FireNForget"); } break; default: Assert.Fail("DoOp: Unhandled operation " + op); break; } if (expectedResult != ExpectedResult.Success) { Assert.Fail("Expected an exception while performing operation"); } } catch (AssertionException ex) { Util.Log("DoOp: failed assertion: {0}", ex); throw; } catch (NotAuthorizedException ex) { exceptionOccured = true; if (expectedResult == ExpectedResult.NotAuthorizedException) { Util.Log( "DoOp: Got expected NotAuthorizedException when doing operation [" + op + "] with flags [" + flags + "]: " + ex.Message); continue; } else { Assert.Fail("DoOp: Got unexpected NotAuthorizedException when " + "doing operation: " + ex.Message); } } catch (Exception ex) { exceptionOccured = true; if (expectedResult == ExpectedResult.OtherException) { Util.Log("DoOp: Got expected exception when doing operation: " + ex.GetType() + "::" + ex.Message); continue; } else { Assert.Fail("DoOp: Got unexpected exception when doing operation: " + ex); } } } if (!exceptionOccured && expectedResult != ExpectedResult.Success) { Assert.Fail("Expected an exception while performing operation"); } Util.Log(" doop done"); } protected void ExecuteOpBlock(List<OperationWithAction> opBlock, string authInit, Properties<string, string> extraAuthProps, Properties<string, string> extraAuthzProps, TestCredentialGenerator gen, Random rnd, bool isMultiuser, bool ssl,bool withPassword) { foreach (OperationWithAction currentOp in opBlock) { // Start client with valid credentials as specified in // OperationWithAction OperationCode opCode = currentOp.OpCode; OpFlags opFlags = currentOp.Flags; int clientNum = currentOp.ClientNum; if (clientNum > m_clients.Length) { Assert.Fail("ExecuteOpBlock: Unknown client number " + clientNum); } ClientBase client = m_clients[clientNum - 1]; Util.Log("ExecuteOpBlock: performing operation number [" + currentOp.OpNum + "]: " + currentOp); Properties<string, string> clientProps = null; if (!CheckFlags(opFlags, OpFlags.UseOldConn)) { Properties<string, string> opCredentials; int newRnd = rnd.Next(100) + 1; string currentRegionName = '/' + RegionName; if (CheckFlags(opFlags, OpFlags.UseSubRegion)) { currentRegionName += ('/' + SubregionName); } string credentialsTypeStr; OperationCode authOpCode = currentOp.AuthzOperationCode; int[] indices = currentOp.Indices; CredentialGenerator cGen = gen.GetCredentialGenerator(); Properties<string, string> javaProps = null; if (CheckFlags(opFlags, OpFlags.CheckNotAuthz) || CheckFlags(opFlags, OpFlags.UseNotAuthz)) { opCredentials = gen.GetDisallowedCredentials( new OperationCode[] { authOpCode }, new string[] { currentRegionName }, indices, newRnd); credentialsTypeStr = " unauthorized " + authOpCode; } else { opCredentials = gen.GetAllowedCredentials(new OperationCode[] { opCode, authOpCode }, new string[] { currentRegionName }, indices, newRnd); credentialsTypeStr = " authorized " + authOpCode; } if (cGen != null) { javaProps = cGen.JavaProperties; } clientProps = SecurityTestUtil.ConcatProperties( opCredentials, extraAuthProps, extraAuthzProps); // Start the client with valid credentials but allowed or disallowed to // perform an operation Util.Log("ExecuteOpBlock: For client" + clientNum + credentialsTypeStr + " credentials: " + opCredentials); if(!isMultiuser) client.Call(SecurityTestUtil.CreateClientSSL, RegionName, CacheHelper.Locators, authInit, clientProps, ssl, withPassword); else client.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); } ExpectedResult expectedResult; if (CheckFlags(opFlags, OpFlags.CheckNotAuthz)) { expectedResult = ExpectedResult.NotAuthorizedException; } else if (CheckFlags(opFlags, OpFlags.CheckException)) { expectedResult = ExpectedResult.OtherException; } else { expectedResult = ExpectedResult.Success; } // Perform the operation from selected client if (!isMultiuser) client.Call(DoOp, opCode, currentOp.Indices, opFlags, expectedResult); else client.Call(DoOp, opCode, currentOp.Indices, opFlags, expectedResult, clientProps, true); } } protected List<AuthzCredentialGenerator> GetAllGeneratorCombos(bool isMultiUser) { List<AuthzCredentialGenerator> generators = new List<AuthzCredentialGenerator>(); foreach (AuthzCredentialGenerator.ClassCode authzClassCode in Enum.GetValues(typeof(AuthzCredentialGenerator.ClassCode))) { List<CredentialGenerator> cGenerators = SecurityTestUtil.getAllGenerators(isMultiUser); foreach (CredentialGenerator cGen in cGenerators) { AuthzCredentialGenerator authzGen = AuthzCredentialGenerator .Create(authzClassCode); if (authzGen != null) { if (authzGen.Init(cGen)) { generators.Add(authzGen); } } } } return generators; } protected void RunOpsWithFailoverSSL(OperationWithAction[] opCodes, string testName, bool withPassword) { RunOpsWithFailover(opCodes, testName, false, true,withPassword); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName) { RunOpsWithFailover(opCodes, testName, false); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName, bool isMultiUser) { RunOpsWithFailover(opCodes, testName, isMultiUser, false, false); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName, bool isMultiUser, bool ssl, bool withPassword) { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC", null, ssl); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(isMultiUser)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(authzGen); Util.Log(testName + ": Using authinit: " + authInit); Util.Log(testName + ": Using authenticator: " + authenticator); Util.Log(testName + ": Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Perform all the ops on the clients List<OperationWithAction> opBlock = new List<OperationWithAction>(); Random rnd = new Random(); for (int opNum = 0; opNum < opCodes.Length; ++opNum) { // Start client with valid credentials as specified in // OperationWithAction OperationWithAction currentOp = opCodes[opNum]; if (currentOp == OperationWithAction.OpBlockEnd || currentOp == OperationWithAction.OpBlockNoFailover) { // End of current operation block; execute all the operations // on the servers with/without failover if (opBlock.Count > 0) { // Start the first server and execute the operation block CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs, ssl); Util.Log("Cacheserver 1 started."); CacheHelper.StopJavaServer(2, false); ExecuteOpBlock(opBlock, authInit, extraAuthProps, extraAuthzProps, tgen, rnd, isMultiUser, ssl, withPassword); if (currentOp == OperationWithAction.OpBlockNoFailover) { CacheHelper.StopJavaServer(1); } else { // Failover to the second server and run the block again CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs, ssl); Util.Log("Cacheserver 2 started."); CacheHelper.StopJavaServer(1); ExecuteOpBlock(opBlock, authInit, extraAuthProps, extraAuthzProps, tgen, rnd, isMultiUser, ssl, withPassword); } opBlock.Clear(); } } else { currentOp.OpNum = opNum; opBlock.Add(currentOp); } } // Close all clients here since we run multiple iterations for pool and non pool configs foreach (ClientBase client in m_clients) { client.Call(Close); } } CacheHelper.StopJavaLocator(1, true, ssl); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #endregion /// <summary> /// This class specifies flags that can be used to alter the behaviour of /// operations being performed by the <see cref="DoOp"/> method. /// </summary> [Flags] public enum OpFlags { /// <summary> /// Default behaviour. /// </summary> None = 0x0, /// <summary> /// Check that the operation should fail. /// </summary> CheckFail = 0x1, /// <summary> /// Check that the operation should throw <c>NotAuthorizedException</c>. /// </summary> CheckNotAuthz = 0x2, /// <summary> /// Do the connection with unauthorized credentials but do not check that the /// operation throws <c>NotAuthorizedException</c>. /// </summary> UseNotAuthz = 0x4, /// <summary> /// Check that the region should not be available. /// </summary> CheckNoRegion = 0x8, /// <summary> /// Check that the operation should throw an exception other than the /// <c>NotAuthorizedException</c>. /// </summary> CheckException = 0x10, /// <summary> /// Check for values starting with <c>NValuePrefix</c> instead of /// <c>ValuePrefix</c>. /// </summary> UseNewVal = 0x20, /// <summary> /// Register a regular expression. /// </summary> UseRegex = 0x40, /// <summary> /// Register a list of keys. /// </summary> UseList = 0x80, /// <summary> /// Register all keys. /// </summary> UseAllKeys = 0x100, /// <summary> /// Perform the local version of the operation (if applicable). /// </summary> LocalOp = 0x200, /// <summary> /// Check that the key for the operation should not be present. /// </summary> CheckNoKey = 0x400, /// <summary> /// Use the sub-region for performing the operation. /// </summary> UseSubRegion = 0x800, /// <summary> /// Do not try to create the sub-region. /// </summary> NoCreateSubRegion = 0x1000, /// <summary> /// Do not re-connect using new credentials rather use the previous /// connection. /// </summary> UseOldConn = 0x2000, } /// <summary> /// This class encapsulates an <see cref="OperationCode"/> with associated flags, the /// client to perform the operation, and the number of operations to perform. /// </summary> public class OperationWithAction { /// <summary> /// The operation to be performed. /// </summary> private OperationCode m_opCode; /// <summary> /// The operation for which authorized or unauthorized credentials have to be /// generated. This is the same as {@link #opCode} when not specified. /// </summary> private OperationCode m_authzOpCode; /// <summary> /// The client number on which the operation has to be performed. /// </summary> private int m_clientNum; /// <summary> /// Bitwise or'd <see cref="OpFlags"/> to change/specify the behaviour of /// the operations. /// </summary> private OpFlags m_flags; /// <summary> /// Indices of the keys array to be used for operations. The keys used /// will be concatenation of <c>KeyPrefix</c> and <c>index</c> integer. /// </summary> private int[] m_indices; /// <summary> /// An index for the operation used for logging. /// </summary> private int m_opNum; /// <summary> /// Indicates end of an operation block which can be used for testing with /// failover. /// </summary> public static readonly OperationWithAction OpBlockEnd = new OperationWithAction( OperationCode.Get, 4); /// <summary> /// Indicates end of an operation block which should not be used for testing /// with failover. /// </summary> public static readonly OperationWithAction OpBlockNoFailover = new OperationWithAction(OperationCode.Get, 5); private void SetIndices(int numOps) { this.m_indices = new int[numOps]; for (int index = 0; index < numOps; ++index) { this.m_indices[index] = index; } } public OperationWithAction(OperationCode opCode) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = 1; this.m_flags = OpFlags.None; SetIndices(4); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = OpFlags.None; SetIndices(4); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum, OpFlags flags, int numOps) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = flags; SetIndices(numOps); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, OperationCode deniedOpCode, int clientNum, OpFlags flags, int numOps) { this.m_opCode = opCode; this.m_authzOpCode = deniedOpCode; this.m_clientNum = clientNum; this.m_flags = flags; SetIndices(numOps); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum, OpFlags flags, int[] indices) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = flags; this.m_indices = indices; this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, OperationCode authzOpCode, int clientNum, OpFlags flags, int[] indices) { this.m_opCode = opCode; this.m_authzOpCode = authzOpCode; this.m_clientNum = clientNum; this.m_flags = flags; this.m_indices = indices; this.m_opNum = 0; } public OperationCode OpCode { get { return this.m_opCode; } } public OperationCode AuthzOperationCode { get { return this.m_authzOpCode; } } public int ClientNum { get { return this.m_clientNum; } } public OpFlags Flags { get { return this.m_flags; } } public int[] Indices { get { return this.m_indices; } } public int OpNum { get { return this.m_opNum; } set { this.m_opNum = value; } } public override string ToString() { return "opCode:" + this.m_opCode + ",authOpCode:" + this.m_authzOpCode + ",clientNum:" + this.m_clientNum + ",flags:" + this.m_flags + ",numOps:" + this.m_indices.Length + ",indices:" + IndicesToString(this.m_indices); } } /// <summary> /// Simple interface to generate credentials with authorization based on key /// indices also. This is utilized by the post-operation authorization tests /// <c>ThinClientAuthzObjectModTests</c> where authorization depends on /// the actual keys being used for the operation. /// </summary> public interface TestCredentialGenerator { /// <summary> /// Get allowed credentials for the given set of operations in the given /// regions and indices of keys. /// </summary> Properties<string, string> GetAllowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num); /// <summary> /// Get disallowed credentials for the given set of operations in the given /// regions and indices of keys. /// </summary> Properties<string, string> GetDisallowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num); /// <summary> /// Get the <see cref="CredentialGenerator"/> if any. /// </summary> /// <returns></returns> CredentialGenerator GetCredentialGenerator(); } /// <summary> /// Contains a <c>AuthzCredentialGenerator</c> and implements the /// <c>TestCredentialGenerator</c> interface. /// </summary> protected class TestAuthzCredentialGenerator : TestCredentialGenerator { private AuthzCredentialGenerator authzGen; public TestAuthzCredentialGenerator(AuthzCredentialGenerator authzGen) { this.authzGen = authzGen; } public Properties<string, string> GetAllowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num) { return this.authzGen.GetAllowedCredentials(opCodes, regionNames, num); } public Properties<string, string> GetDisallowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num) { return this.authzGen.GetDisallowedCredentials(opCodes, regionNames, num); } public CredentialGenerator GetCredentialGenerator() { return authzGen.GetCredentialGenerator(); } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Represents a collection of extended properties. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class ExtendedPropertyCollection : ComplexPropertyCollection<ExtendedProperty>, ICustomUpdateSerializer { /// <summary> /// Creates the complex property. /// </summary> /// <param name="xmlElementName">Name of the XML element.</param> /// <returns>Complex property instance.</returns> internal override ExtendedProperty CreateComplexProperty(string xmlElementName) { return new ExtendedProperty(); } /// <summary> /// Gets the name of the collection item XML element. /// </summary> /// <param name="complexProperty">The complex property.</param> /// <returns>XML element name.</returns> internal override string GetCollectionItemXmlElementName(ExtendedProperty complexProperty) { // This method is unused in this class, so just return null. return null; } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="localElementName">Name of the local element.</param> internal override void LoadFromXml(EwsServiceXmlReader reader, string localElementName) { ExtendedProperty extendedProperty = new ExtendedProperty(); extendedProperty.LoadFromXml(reader, reader.LocalName); this.InternalAdd(extendedProperty); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal override void WriteToXml(EwsServiceXmlWriter writer, string xmlElementName) { foreach (ExtendedProperty extendedProperty in this) { extendedProperty.WriteToXml(writer, XmlElementNames.ExtendedProperty); } } /// <summary> /// Gets existing or adds new extended property. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <returns>ExtendedProperty.</returns> private ExtendedProperty GetOrAddExtendedProperty(ExtendedPropertyDefinition propertyDefinition) { ExtendedProperty extendedProperty; if (!this.TryGetProperty(propertyDefinition, out extendedProperty)) { extendedProperty = new ExtendedProperty(propertyDefinition); this.InternalAdd(extendedProperty); } return extendedProperty; } /// <summary> /// Sets an extended property. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <param name="value">The value.</param> internal void SetExtendedProperty(ExtendedPropertyDefinition propertyDefinition, object value) { ExtendedProperty extendedProperty = this.GetOrAddExtendedProperty(propertyDefinition); extendedProperty.Value = value; } /// <summary> /// Removes a specific extended property definition from the collection. /// </summary> /// <param name="propertyDefinition">The definition of the extended property to remove.</param> /// <returns>True if the property matching the extended property definition was successfully removed from the collection, false otherwise.</returns> internal bool RemoveExtendedProperty(ExtendedPropertyDefinition propertyDefinition) { EwsUtilities.ValidateParam(propertyDefinition, "propertyDefinition"); ExtendedProperty extendedProperty; if (this.TryGetProperty(propertyDefinition, out extendedProperty)) { return this.InternalRemove(extendedProperty); } else { return false; } } /// <summary> /// Tries to get property. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <param name="extendedProperty">The extended property.</param> /// <returns>True of property exists in collection.</returns> private bool TryGetProperty(ExtendedPropertyDefinition propertyDefinition, out ExtendedProperty extendedProperty) { extendedProperty = this.Items.Find((prop) => prop.PropertyDefinition.Equals(propertyDefinition)); return extendedProperty != null; } /// <summary> /// Tries to get property value. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <param name="propertyValue">The property value.</param> /// <typeparam name="T">Type of expected property value.</typeparam> /// <returns>True if property exists in collection.</returns> internal bool TryGetValue<T>(ExtendedPropertyDefinition propertyDefinition, out T propertyValue) { ExtendedProperty extendedProperty; if (this.TryGetProperty(propertyDefinition, out extendedProperty)) { // Verify that the type parameter and property definition's type are compatible. if (!typeof(T).IsAssignableFrom(propertyDefinition.Type)) { string errorMessage = string.Format( Strings.PropertyDefinitionTypeMismatch, EwsUtilities.GetPrintableTypeName(propertyDefinition.Type), EwsUtilities.GetPrintableTypeName(typeof(T))); throw new ArgumentException(errorMessage, "propertyDefinition"); } propertyValue = (T)extendedProperty.Value; return true; } else { propertyValue = default(T); return false; } } #region ICustomXmlUpdateSerializer Members /// <summary> /// Writes the update to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="ewsObject">The ews object.</param> /// <param name="propertyDefinition">Property definition.</param> /// <returns> /// True if property generated serialization. /// </returns> bool ICustomUpdateSerializer.WriteSetUpdateToXml( EwsServiceXmlWriter writer, ServiceObject ewsObject, PropertyDefinition propertyDefinition) { List<ExtendedProperty> propertiesToSet = new List<ExtendedProperty>(); propertiesToSet.AddRange(this.AddedItems); propertiesToSet.AddRange(this.ModifiedItems); foreach (ExtendedProperty extendedProperty in propertiesToSet) { writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetSetFieldXmlElementName()); extendedProperty.PropertyDefinition.WriteToXml(writer); writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetXmlElementName()); extendedProperty.WriteToXml(writer, XmlElementNames.ExtendedProperty); writer.WriteEndElement(); writer.WriteEndElement(); } foreach (ExtendedProperty extendedProperty in this.RemovedItems) { writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName()); extendedProperty.PropertyDefinition.WriteToXml(writer); writer.WriteEndElement(); } return true; } /// <summary> /// Writes the deletion update to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="ewsObject">The ews object.</param> /// <returns> /// True if property generated serialization. /// </returns> bool ICustomUpdateSerializer.WriteDeleteUpdateToXml(EwsServiceXmlWriter writer, ServiceObject ewsObject) { foreach (ExtendedProperty extendedProperty in this.Items) { writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName()); extendedProperty.PropertyDefinition.WriteToXml(writer); writer.WriteEndElement(); } return true; } #endregion } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using System; using System.Xml; using System.Text; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.Shell; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using System.Diagnostics.CodeAnalysis; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { [StructLayoutAttribute(LayoutKind.Sequential)] internal struct _DROPFILES { public Int32 pFiles; public Int32 X; public Int32 Y; public Int32 fNC; public Int32 fWide; } /// <summary> /// Defines possible types of output that can produced by a language project /// </summary> [PropertyPageTypeConverterAttribute(typeof(OutputTypeConverter))] public enum OutputType { /// <summary> /// The output type is a windows executable. /// </summary> WinExe, /// <summary> /// The output type is an executable. /// </summary> Exe, /// <summary> /// The output type is a class library. /// </summary> Library } /// <summary> /// Debug values used by DebugModeConverter. /// </summary> [PropertyPageTypeConverterAttribute(typeof(DebugModeConverter))] public enum DebugMode { Project, Program, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URL")] URL } [PropertyPageTypeConverterAttribute(typeof(CopyToOutputDirectoryConverter))] public enum CopyToOutputDirectory { DoNotCopy, Always, PreserveNewest, } /// <summary> /// Defines the version of the CLR that is appropriate to the project. /// </summary> [PropertyPageTypeConverterAttribute(typeof(PlatformTypeConverter))] public enum PlatformType { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "not")] notSpecified, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v1, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v11, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")] v2, [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "cli")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "cli")] cli1 } /// <summary> /// Defines the currect state of a property page. /// </summary> [Flags] internal enum PropPageStatus { Dirty = 0x1, Validate = 0x2, Clean = 0x4 } [Flags] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] internal enum ModuleKindFlags { ConsoleApplication, WindowsApplication, DynamicallyLinkedLibrary, ManifestResourceFile, UnmanagedDynamicallyLinkedLibrary } /// <summary> /// Defines the status of the command being queried /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] internal enum QueryStatusResult { /// <summary> /// The command is not supported. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NOTSUPPORTED")] NOTSUPPORTED = 0, /// <summary> /// The command is supported /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SUPPORTED")] SUPPORTED = 1, /// <summary> /// The command is enabled /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ENABLED")] ENABLED = 2, /// <summary> /// The command is toggled on /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "LATCHED")] LATCHED = 4, /// <summary> /// The command is toggled off (the opposite of LATCHED). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "NINCHED")] NINCHED = 8, /// <summary> /// The command is invisible. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "INVISIBLE")] INVISIBLE = 16 } /// <summary> /// Defines the type of item to be added to the hierarchy. /// </summary> internal enum HierarchyAddType { AddNewItem, AddExistingItem } /// <summary> /// Defines the component from which a command was issued. /// </summary> internal enum CommandOrigin { [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ui")] UiHierarchy, OleCommandTarget } /// <summary> /// Defines the current status of the build process. /// </summary> internal enum MSBuildResult { /// <summary> /// The build is currently suspended. /// </summary> Suspended, /// <summary> /// The build has been restarted. /// </summary> Resumed, /// <summary> /// The build failed. /// </summary> Failed, /// <summary> /// The build was successful. /// </summary> Successful, } /// <summary> /// Defines the type of action to be taken in showing the window frame. /// </summary> internal enum WindowFrameShowAction { DontShow, Show, ShowNoActivate, Hide, } /// <summary> /// Defines drop types /// </summary> internal enum DropDataType { None, Shell, VsStg, VsRef } /// <summary> /// Used by the hierarchy node to decide which element to redraw. /// </summary> [Flags] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] internal enum UIHierarchyElement { None = 0, /// <summary> /// This will be translated to VSHPROPID_IconIndex /// </summary> Icon = 1, /// <summary> /// This will be translated to VSHPROPID_StateIconIndex /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] SccState = 2, /// <summary> /// This will be translated to VSHPROPID_Caption /// </summary> Caption = 4 } /// <summary> /// Defines the global propeties used by the msbuild project. /// </summary> internal enum GlobalProperty { /// <summary> /// Property specifying that we are building inside VS. /// </summary> BuildingInsideVisualStudio, /// <summary> /// The VS installation directory. This is the same as the $(DevEnvDir) macro. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Env")] DevEnvDir, /// <summary> /// The name of the solution the project is created. This is the same as the $(SolutionName) macro. /// </summary> SolutionName, /// <summary> /// The file name of the solution. This is the same as $(SolutionFileName) macro. /// </summary> SolutionFileName, /// <summary> /// The full path of the solution. This is the same as the $(SolutionPath) macro. /// </summary> SolutionPath, /// <summary> /// The directory of the solution. This is the same as the $(SolutionDir) macro. /// </summary> SolutionDir, /// <summary> /// The extension of teh directory. This is the same as the $(SolutionExt) macro. /// </summary> SolutionExt, /// <summary> /// The fxcop installation directory. /// </summary> FxCopDir, /// <summary> /// The ResolvedNonMSBuildProjectOutputs msbuild property /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VSIDE")] VSIDEResolvedNonMSBuildProjectOutputs, /// <summary> /// The Configuartion property. /// </summary> Configuration, /// <summary> /// The platform property. /// </summary> Platform, /// <summary> /// The RunCodeAnalysisOnce property /// </summary> RunCodeAnalysisOnce, /// <summary> /// The VisualStudioStyleErrors property. We use this to determine correct error spans for build errors. /// </summary> VisualStudioStyleErrors, /// <summary> /// The SqmSessionGuid property /// </summary> SqmSessionGuid } public class AfterProjectFileOpenedEventArgs : EventArgs { private bool added; /// <summary> /// True if the project is added to the solution after the solution is opened. false if the project is added to the solution while the solution is being opened. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool Added { get { return this.added; } } public AfterProjectFileOpenedEventArgs(bool added) { this.added = added; } } public class BeforeProjectFileClosedEventArgs : EventArgs { private bool removed; /// <summary> /// true if the project was removed from the solution before the solution was closed. false if the project was removed from the solution while the solution was being closed. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool Removed { get { return this.removed; } } public BeforeProjectFileClosedEventArgs(bool removed) { this.removed = removed; } } /// <summary> /// This class is used for the events raised by a HierarchyNode object. /// </summary> internal class HierarchyNodeEventArgs : EventArgs { private HierarchyNode child; public HierarchyNodeEventArgs(HierarchyNode child) { this.child = child; } public HierarchyNode Child { get { return this.child; } } } /// <summary> /// Event args class for triggering file change event arguments. /// </summary> internal class FileChangedOnDiskEventArgs : EventArgs { /// <summary> /// File name that was changed on disk. /// </summary> private string fileName; /// <summary> /// The item ide of the file that has changed. /// </summary> private uint itemID; /// <summary> /// The reason the file has changed on disk. /// </summary> private _VSFILECHANGEFLAGS fileChangeFlag; /// <summary> /// Constructs a new event args. /// </summary> /// <param name="fileName">File name that was changed on disk.</param> /// <param name="id">The item id of the file that was changed on disk.</param> public FileChangedOnDiskEventArgs(string fileName, uint id, _VSFILECHANGEFLAGS flag) { this.fileName = fileName; this.itemID = id; this.fileChangeFlag = flag; } /// <summary> /// Gets the file name that was changed on disk. /// </summary> /// <value>The file that was changed on disk.</value> public string FileName { get { return this.fileName; } } /// <summary> /// Gets item id of the file that has changed /// </summary> /// <value>The file that was changed on disk.</value> public uint ItemID { get { return this.itemID; } } /// <summary> /// The reason while the file has chnaged on disk. /// </summary> /// <value>The reason while the file has chnaged on disk.</value> public _VSFILECHANGEFLAGS FileChangeFlag { get { return this.fileChangeFlag; } } } /// <summary> /// Defines the event args for the active configuration chnage event. /// </summary> internal class ActiveConfigurationChangedEventArgs : EventArgs { /// <summary> /// The hierarchy whose configuration has changed /// </summary> private IVsHierarchy hierarchy; /// <summary> /// Constructs a new event args. /// </summary> /// <param name="hierarchy">The hierarchy that has changed its configuration.</param> public ActiveConfigurationChangedEventArgs(IVsHierarchy hierarchy) { this.hierarchy = hierarchy; } /// <summary> /// The hierarchy whose configuration has changed /// </summary> public IVsHierarchy Hierarchy { get { return this.hierarchy; } } } /// <summary> /// Argument of the event raised when a project property is changed. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] internal class ProjectPropertyChangedArgs : EventArgs { private string propertyName; private string oldValue; private string newValue; public ProjectPropertyChangedArgs(string propertyName, string oldValue, string newValue) { this.propertyName = propertyName; this.oldValue = oldValue; this.newValue = newValue; } public string NewValue { get { return newValue; } } public string OldValue { get { return oldValue; } } public string PropertyName { get { return propertyName; } } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace IO.Swagger.Model { /// <summary> /// /// </summary> [DataContract] public class CommonVariableRelationship : IEquatable<CommonVariableRelationship> { /// <summary> /// Initializes a new instance of the <see cref="CommonVariableRelationship" /> class. /// </summary> public CommonVariableRelationship() { } /// <summary> /// id /// </summary> /// <value>id</value> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; set; } /// <summary> /// Our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors /// </summary> /// <value>Our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors</value> [DataMember(Name="confidence_level", EmitDefaultValue=false)] public string ConfidenceLevel { get; set; } /// <summary> /// A quantitative representation of our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors /// </summary> /// <value>A quantitative representation of our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors</value> [DataMember(Name="confidence_score", EmitDefaultValue=false)] public float? ConfidenceScore { get; set; } /// <summary> /// Direction is positive if higher predictor values generally precede higher outcome values. Direction is negative if higher predictor values generally precede lower outcome values. /// </summary> /// <value>Direction is positive if higher predictor values generally precede higher outcome values. Direction is negative if higher predictor values generally precede lower outcome values.</value> [DataMember(Name="direction", EmitDefaultValue=false)] public string Direction { get; set; } /// <summary> /// duration_of_action /// </summary> /// <value>duration_of_action</value> [DataMember(Name="duration_of_action", EmitDefaultValue=false)] public int? DurationOfAction { get; set; } /// <summary> /// error_message /// </summary> /// <value>error_message</value> [DataMember(Name="error_message", EmitDefaultValue=false)] public string ErrorMessage { get; set; } /// <summary> /// User estimated (or default number of seconds) after cause measurement before a perceivable effect is observed /// </summary> /// <value>User estimated (or default number of seconds) after cause measurement before a perceivable effect is observed</value> [DataMember(Name="onset_delay", EmitDefaultValue=false)] public int? OnsetDelay { get; set; } /// <summary> /// Variable ID for the outcome variable /// </summary> /// <value>Variable ID for the outcome variable</value> [DataMember(Name="outcome_variable_id", EmitDefaultValue=false)] public int? OutcomeVariableId { get; set; } /// <summary> /// Variable ID for the predictor variable /// </summary> /// <value>Variable ID for the predictor variable</value> [DataMember(Name="predictor_variable_id", EmitDefaultValue=false)] public int? PredictorVariableId { get; set; } /// <summary> /// ID for default unit of the predictor variable /// </summary> /// <value>ID for default unit of the predictor variable</value> [DataMember(Name="predictor_unit_id", EmitDefaultValue=false)] public int? PredictorUnitId { get; set; } /// <summary> /// A value representative of the relevance of this predictor relative to other predictors of this outcome. Usually used for relevancy sorting. /// </summary> /// <value>A value representative of the relevance of this predictor relative to other predictors of this outcome. Usually used for relevancy sorting.</value> [DataMember(Name="sinn_rank", EmitDefaultValue=false)] public float? SinnRank { get; set; } /// <summary> /// A value represented to the size of the effect which the predictor appears to have on the outcome. /// </summary> /// <value>A value represented to the size of the effect which the predictor appears to have on the outcome.</value> [DataMember(Name="strength_score", EmitDefaultValue=false)] public float? StrengthScore { get; set; } /// <summary> /// Can be weak, medium, or strong based on the size of the effect which the predictor appears to have on the outcome relative to other variable relationship strength scores. /// </summary> /// <value>Can be weak, medium, or strong based on the size of the effect which the predictor appears to have on the outcome relative to other variable relationship strength scores.</value> [DataMember(Name="strength_level", EmitDefaultValue=false)] public string StrengthLevel { get; set; } /// <summary> /// Number of users who feel that there is a plausible causal relationship between the predictor and outcome variables. /// </summary> /// <value>Number of users who feel that there is a plausible causal relationship between the predictor and outcome variables.</value> [DataMember(Name="up_votes", EmitDefaultValue=false)] public int? UpVotes { get; set; } /// <summary> /// Number of users who do not feel that there is a plausible causal relationship between the predictor and outcome variables. /// </summary> /// <value>Number of users who do not feel that there is a plausible causal relationship between the predictor and outcome variables.</value> [DataMember(Name="down_votes", EmitDefaultValue=false)] public int? DownVotes { get; set; } /// <summary> /// Value for the predictor variable (in it's default unit) which typically precedes an above average outcome value /// </summary> /// <value>Value for the predictor variable (in it's default unit) which typically precedes an above average outcome value</value> [DataMember(Name="value_predicting_high_outcome", EmitDefaultValue=false)] public float? ValuePredictingHighOutcome { get; set; } /// <summary> /// Value for the predictor variable (in it's default unit) which typically precedes a below average outcome value /// </summary> /// <value>Value for the predictor variable (in it's default unit) which typically precedes a below average outcome value</value> [DataMember(Name="value_predicting_low_outcome", EmitDefaultValue=false)] public float? ValuePredictingLowOutcome { get; set; } /// <summary> /// Number of users whose data was aggregated to obtain this relationship /// </summary> /// <value>Number of users whose data was aggregated to obtain this relationship</value> [DataMember(Name="number_of_users", EmitDefaultValue=false)] public int? NumberOfUsers { get; set; } /// <summary> /// Source of data for this common variable relationship /// </summary> /// <value>Source of data for this common variable relationship</value> [DataMember(Name="data_source", EmitDefaultValue=false)] public string DataSource { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CommonVariableRelationship {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" ConfidenceLevel: ").Append(ConfidenceLevel).Append("\n"); sb.Append(" ConfidenceScore: ").Append(ConfidenceScore).Append("\n"); sb.Append(" Direction: ").Append(Direction).Append("\n"); sb.Append(" DurationOfAction: ").Append(DurationOfAction).Append("\n"); sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n"); sb.Append(" OnsetDelay: ").Append(OnsetDelay).Append("\n"); sb.Append(" OutcomeVariableId: ").Append(OutcomeVariableId).Append("\n"); sb.Append(" PredictorVariableId: ").Append(PredictorVariableId).Append("\n"); sb.Append(" PredictorUnitId: ").Append(PredictorUnitId).Append("\n"); sb.Append(" SinnRank: ").Append(SinnRank).Append("\n"); sb.Append(" StrengthScore: ").Append(StrengthScore).Append("\n"); sb.Append(" StrengthLevel: ").Append(StrengthLevel).Append("\n"); sb.Append(" UpVotes: ").Append(UpVotes).Append("\n"); sb.Append(" DownVotes: ").Append(DownVotes).Append("\n"); sb.Append(" ValuePredictingHighOutcome: ").Append(ValuePredictingHighOutcome).Append("\n"); sb.Append(" ValuePredictingLowOutcome: ").Append(ValuePredictingLowOutcome).Append("\n"); sb.Append(" NumberOfUsers: ").Append(NumberOfUsers).Append("\n"); sb.Append(" DataSource: ").Append(DataSource).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CommonVariableRelationship); } /// <summary> /// Returns true if CommonVariableRelationship instances are equal /// </summary> /// <param name="obj">Instance of CommonVariableRelationship to be compared</param> /// <returns>Boolean</returns> public bool Equals(CommonVariableRelationship other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.ConfidenceLevel == other.ConfidenceLevel || this.ConfidenceLevel != null && this.ConfidenceLevel.Equals(other.ConfidenceLevel) ) && ( this.ConfidenceScore == other.ConfidenceScore || this.ConfidenceScore != null && this.ConfidenceScore.Equals(other.ConfidenceScore) ) && ( this.Direction == other.Direction || this.Direction != null && this.Direction.Equals(other.Direction) ) && ( this.DurationOfAction == other.DurationOfAction || this.DurationOfAction != null && this.DurationOfAction.Equals(other.DurationOfAction) ) && ( this.ErrorMessage == other.ErrorMessage || this.ErrorMessage != null && this.ErrorMessage.Equals(other.ErrorMessage) ) && ( this.OnsetDelay == other.OnsetDelay || this.OnsetDelay != null && this.OnsetDelay.Equals(other.OnsetDelay) ) && ( this.OutcomeVariableId == other.OutcomeVariableId || this.OutcomeVariableId != null && this.OutcomeVariableId.Equals(other.OutcomeVariableId) ) && ( this.PredictorVariableId == other.PredictorVariableId || this.PredictorVariableId != null && this.PredictorVariableId.Equals(other.PredictorVariableId) ) && ( this.PredictorUnitId == other.PredictorUnitId || this.PredictorUnitId != null && this.PredictorUnitId.Equals(other.PredictorUnitId) ) && ( this.SinnRank == other.SinnRank || this.SinnRank != null && this.SinnRank.Equals(other.SinnRank) ) && ( this.StrengthScore == other.StrengthScore || this.StrengthScore != null && this.StrengthScore.Equals(other.StrengthScore) ) && ( this.StrengthLevel == other.StrengthLevel || this.StrengthLevel != null && this.StrengthLevel.Equals(other.StrengthLevel) ) && ( this.UpVotes == other.UpVotes || this.UpVotes != null && this.UpVotes.Equals(other.UpVotes) ) && ( this.DownVotes == other.DownVotes || this.DownVotes != null && this.DownVotes.Equals(other.DownVotes) ) && ( this.ValuePredictingHighOutcome == other.ValuePredictingHighOutcome || this.ValuePredictingHighOutcome != null && this.ValuePredictingHighOutcome.Equals(other.ValuePredictingHighOutcome) ) && ( this.ValuePredictingLowOutcome == other.ValuePredictingLowOutcome || this.ValuePredictingLowOutcome != null && this.ValuePredictingLowOutcome.Equals(other.ValuePredictingLowOutcome) ) && ( this.NumberOfUsers == other.NumberOfUsers || this.NumberOfUsers != null && this.NumberOfUsers.Equals(other.NumberOfUsers) ) && ( this.DataSource == other.DataSource || this.DataSource != null && this.DataSource.Equals(other.DataSource) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 57 + this.Id.GetHashCode(); if (this.ConfidenceLevel != null) hash = hash * 57 + this.ConfidenceLevel.GetHashCode(); if (this.ConfidenceScore != null) hash = hash * 57 + this.ConfidenceScore.GetHashCode(); if (this.Direction != null) hash = hash * 57 + this.Direction.GetHashCode(); if (this.DurationOfAction != null) hash = hash * 57 + this.DurationOfAction.GetHashCode(); if (this.ErrorMessage != null) hash = hash * 57 + this.ErrorMessage.GetHashCode(); if (this.OnsetDelay != null) hash = hash * 57 + this.OnsetDelay.GetHashCode(); if (this.OutcomeVariableId != null) hash = hash * 57 + this.OutcomeVariableId.GetHashCode(); if (this.PredictorVariableId != null) hash = hash * 57 + this.PredictorVariableId.GetHashCode(); if (this.PredictorUnitId != null) hash = hash * 57 + this.PredictorUnitId.GetHashCode(); if (this.SinnRank != null) hash = hash * 57 + this.SinnRank.GetHashCode(); if (this.StrengthScore != null) hash = hash * 57 + this.StrengthScore.GetHashCode(); if (this.StrengthLevel != null) hash = hash * 57 + this.StrengthLevel.GetHashCode(); if (this.UpVotes != null) hash = hash * 57 + this.UpVotes.GetHashCode(); if (this.DownVotes != null) hash = hash * 57 + this.DownVotes.GetHashCode(); if (this.ValuePredictingHighOutcome != null) hash = hash * 57 + this.ValuePredictingHighOutcome.GetHashCode(); if (this.ValuePredictingLowOutcome != null) hash = hash * 57 + this.ValuePredictingLowOutcome.GetHashCode(); if (this.NumberOfUsers != null) hash = hash * 57 + this.NumberOfUsers.GetHashCode(); if (this.DataSource != null) hash = hash * 57 + this.DataSource.GetHashCode(); return hash; } } } }
/* * Copyright (c) 2013 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace MiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } public static List<object> DeserializeArrayNoRecursion(string json) { if (json == null) { return null; } else if (json == "" || json == "[]") { return new List<object>(0); } Parser parser = new Parser(json); return parser.ParseArrayOnly(); } sealed class Parser : IDisposable { const string WORD_BREAK = "{}[],:\""; public static bool IsWordBreak(char c) { return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; } enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL } ; StringReader json; public Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table [name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } internal List<object> ParseArrayOnly() { String wholeArray = json.ReadToEnd().TrimEnd(new char[] { ']', ' ' }); List<object> array = new List<object>(); int lvl = 0, start = 0; for (int i = 0; i < wholeArray.Length; i++) { char currChar = wholeArray [i]; if (currChar == '{') { lvl++; if (lvl == 1) { start = i; } } else if (currChar == '}') { lvl--; if (lvl == 0) { array.Add(wholeArray.Substring(start, i - start + 1)); } } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new char[4]; for (int i=0; i< 4; i++) { hex [i] = NextChar; } s.Append((char)Convert.ToInt32(new string(hex), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (Char.IsWhiteSpace(PeekChar)) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (!IsWordBreak(PeekChar)) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } switch (PeekChar) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } switch (NextWord) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append((bool)value ? "true" : "false"); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(new string((char)value, 1)); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj [e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u"); builder.Append(codepoint.ToString("x4")); } break; } } builder.Append('\"'); } void SerializeOther(object value) { // NOTE: decimals lose precision during serialization. // They always have, I'm just letting you know. // Previously floats and doubles lost precision too. if (value is float) { builder.Append(((float)value).ToString("R")); } else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) { builder.Append(value); } else if (value is double || value is decimal) { builder.Append(Convert.ToDouble(value).ToString("R")); } else { SerializeString(value.ToString()); } } } } }
// // System.Data.SqlClient.SqlParameterCollection.cs // // Author: // Rodrigo Moya ([email protected]) // Daniel Morgan ([email protected]) // Tim Coleman ([email protected]) // Diego Caravana ([email protected]) // Umadevi S ([email protected]) // // (C) Ximian, Inc 2002 // Copyright (C) Tim Coleman, 2002 // // // 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. // using Mono.Data.Tds; using System; using System.ComponentModel; using System.Data; using System.Data.Common; #if NET_2_0 using System.Data.ProviderBase; #endif // NET_2_0 using System.Collections; namespace System.Data.SqlClient { [ListBindable (false)] [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DataParametersEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )] #if NET_2_0 public sealed class SqlParameterCollection : DbParameterBaseCollection, IDataParameterCollection, IList, ICollection, IEnumerable #else public sealed class SqlParameterCollection : MarshalByRefObject, IDataParameterCollection, IList, ICollection, IEnumerable #endif // NET_2_0 { #region Fields ArrayList list = new ArrayList(); TdsMetaParameterCollection metaParameters; SqlCommand command; #endregion // Fields #region Constructors internal SqlParameterCollection (SqlCommand command) { this.command = command; metaParameters = new TdsMetaParameterCollection (); } #endregion // Constructors #region Properties #if ONLY_1_1 || ONLY_1_0 [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] #endif public #if NET_2_0 override #endif // NET_2_0 int Count { get { return list.Count; } } #if NET_2_0 public override bool IsFixedSize { get { return list.IsFixedSize; } } public override bool IsReadOnly { get { return list.IsReadOnly; } } public override bool IsSynchronized { get { return list.IsSynchronized; } } public override object SyncRoot { get { return list.SyncRoot; } } #endif [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public #if NET_2_0 new #endif // NET_2_0 SqlParameter this [int index] { get { return (SqlParameter) list [index]; } set { list [index] = (SqlParameter) value; } } object IDataParameterCollection.this [string parameterName] { get { return this[parameterName]; } set { if (!(value is SqlParameter)) throw new InvalidCastException ("Only SQLParameter objects can be used."); this [parameterName] = (SqlParameter) value; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public #if NET_2_0 new #endif // NET_2_0 SqlParameter this [string parameterName] { get { foreach (SqlParameter p in list) if (p.ParameterName.Equals (parameterName)) return p; throw new IndexOutOfRangeException ("The specified name does not exist: " + parameterName); } set { if (!Contains (parameterName)) throw new IndexOutOfRangeException("The specified name does not exist: " + parameterName); this [IndexOf (parameterName)] = value; } } #if NET_2_0 protected DbParameter GetParameter (int index) { throw new NotImplementedException(); } protected void SetParameter (int index, DbParameter value) { throw new NotImplementedException(); } /*public IEnumerator GetEnumerator () { throw new NotImplementedException(); }*/ protected override Type ItemType { get { throw new NotImplementedException(); } } #endif object IList.this [int index] { get { return (SqlParameter) this [index]; } set { this [index] = (SqlParameter) value; } } bool IList.IsFixedSize { get { return list.IsFixedSize; } } bool IList.IsReadOnly { get { return list.IsReadOnly; } } bool ICollection.IsSynchronized { get { return list.IsSynchronized; } } object ICollection.SyncRoot { get { return list.SyncRoot; } } internal TdsMetaParameterCollection MetaParameters { get { return metaParameters; } } #endregion // Properties #region Methods public #if NET_2_0 override #endif // NET_2_0 int Add (object value) { if (!(value is SqlParameter)) throw new InvalidCastException ("The parameter was not an SqlParameter."); Add ((SqlParameter) value); return IndexOf (value); } public SqlParameter Add (SqlParameter value) { if (value.Container != null) throw new ArgumentException ("The SqlParameter specified in the value parameter is already added to this or another SqlParameterCollection."); value.Container = this; list.Add (value); metaParameters.Add (value.MetaParameter); return value; } public SqlParameter Add (string parameterName, object value) { return Add (new SqlParameter (parameterName, value)); } public SqlParameter Add (string parameterName, SqlDbType sqlDbType) { return Add (new SqlParameter (parameterName, sqlDbType)); } public SqlParameter Add (string parameterName, SqlDbType sqlDbType, int size) { return Add (new SqlParameter (parameterName, sqlDbType, size)); } public SqlParameter Add (string parameterName, SqlDbType sqlDbType, int size, string sourceColumn) { return Add (new SqlParameter (parameterName, sqlDbType, size, sourceColumn)); } public #if NET_2_0 override #endif // NET_2_0 void Clear() { metaParameters.Clear (); foreach (SqlParameter p in list) p.Container = null; list.Clear (); } public #if NET_2_0 override #endif // NET_2_0 bool Contains (object value) { if (!(value is SqlParameter)) throw new InvalidCastException ("The parameter was not an SqlParameter."); return Contains (((SqlParameter) value).ParameterName); } public #if NET_2_0 override #endif // NET_2_0 bool Contains (string value) { foreach (SqlParameter p in list) if (p.ParameterName.Equals (value)) return true; return false; } #if NET_2_0 public bool Contains (SqlParameter value) { return (this.IndexOf(value) != -1); } #endif // NET_2_0 public #if NET_2_0 override #endif // NET_2_0 void CopyTo (Array array, int index) { list.CopyTo (array, index); } public #if NET_2_0 override #endif // NET_2_0 IEnumerator GetEnumerator() { return list.GetEnumerator (); } public #if NET_2_0 override #endif // NET_2_0 int IndexOf (object value) { if (!(value is SqlParameter)) throw new InvalidCastException ("The parameter was not an SqlParameter."); return IndexOf (((SqlParameter) value).ParameterName); } public #if NET_2_0 override #endif // NET_2_0 int IndexOf (string parameterName) { for (int i = 0; i < Count; i += 1) if (this [i].ParameterName.Equals (parameterName)) return i; return -1; } #if NET_2_0 public int IndexOf (SqlParameter value) { return list.IndexOf(value); } #endif // NET_2_0 public #if NET_2_0 override #endif // NET_2_0 void Insert (int index, object value) { list.Insert (index, value); } #if NET_2_0 public void Insert (int index, SqlParameter value) { list.Insert (index,value); } #endif //NET_2_0 public #if NET_2_0 override #endif // NET_2_0 void Remove (object value) { //TODO : this neds validation to check if the object is a // sqlparameter. ((SqlParameter) value).Container = null; metaParameters.Remove (((SqlParameter) value).MetaParameter); list.Remove (value); } #if NET_2_0 public void Remove (SqlParameter value) { //both this and the above code are the same. but need to work with // 1.1! value.Container = null; metaParameters.Remove (value.MetaParameter); list.Remove (value); } #endif //NET_2_0 public #if NET_2_0 override #endif // NET_2_0 void RemoveAt (int index) { this [index].Container = null; metaParameters.RemoveAt (index); list.RemoveAt (index); } public #if NET_2_0 override #endif // NET_2_0 void RemoveAt (string parameterName) { RemoveAt (IndexOf (parameterName)); } #if NET_2_0 public override void AddRange (Array values) { if (values == null) throw new ArgumentNullException("The argument passed was null"); foreach ( object value in values) { if (!(value is SqlParameter)) throw new InvalidCastException ("Element in the array parameter was not an SqlParameter."); SqlParameter param = (SqlParameter) value; if (param.Container != null) throw new ArgumentException ("An SqlParameter specified in the array is already added to this or another SqlParameterCollection."); param.Container = this; list.Add (param); metaParameters.Add (param.MetaParameter); } } public void AddRange (SqlParameter[] values) { this.AddRange(values); } #endif #endregion // Methods } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Codex.ObjectModel; using Codex.Search; using Codex.Storage; using WebUI.Util; using Reference = Codex.ObjectModel.SymbolReferenceEntry; namespace WebUI.Controllers { public class ReferencesController : Controller { private readonly ElasticsearchStorage Storage; public ReferencesController(IStorage storage) { Storage = (ElasticsearchStorage)storage; } [Route("repos/{repoName}/references/{projectId}")] [Route("references/{projectId}")] public async Task<ActionResult> References(string projectId, string symbolId, string projectScope = null) { try { Requests.LogRequest(this); var definitionResult = await ((IStorage)Storage).GetDefinitionsAsync(this.GetSearchRepos(), projectId, symbolId); var definitionSpan = definitionResult?.FirstOrDefault()?.Span; var definition = definitionSpan?.Definition; var symbolName = definition?.ShortName ?? symbolId; Responses.PrepareResponse(Response); var referencesResult = await Storage.GetReferencesToSymbolAsync( this.GetSearchRepos(), new Symbol() { ProjectId = projectId, Id = SymbolId.UnsafeCreateWithValue(symbolId), }.SetProjectScope(projectScope)); if (referencesResult.Entries.Count != 0) { if (definition != null) { if (projectScope == null) { var relatedDefinitions = await Storage.GetRelatedDefinitions(this.GetSearchRepos(), definition.Id.Value, definition.ProjectId); referencesResult.RelatedDefinitions = relatedDefinitions; } else { var definitionReferences = await Storage.GetReferencesToSymbolAsync( this.GetSearchRepos(), new Symbol() { ProjectId = projectId, Id = SymbolId.UnsafeCreateWithValue(symbolId), Kind = nameof(ReferenceKind.Definition) }); referencesResult.Entries.InsertRange(0, definitionReferences.Entries); } } referencesResult.SymbolName = symbolName; return PartialView((object)GenerateReferencesHtml(referencesResult)); } return PartialView((object)$"No references to project {projectId} and symbol {symbolId} found."); } catch (Exception ex) { return Responses.Exception(ex); } } private static void WriteImplementedInterfaceMembers(StringWriter writer, List<SymbolSearchResultEntry> implementedInterfaceMembers) { Write(writer, string.Format(@"<div class=""rH"" onclick=""ToggleExpandCollapse(this);return false;"">Implemented interface member{0}:</div>", implementedInterfaceMembers.Count > 1 ? "s" : "")); Write(writer, @"<div class=""rK"">"); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { writer.Write(GetSymbolText(implementedInterfaceMember)); } writer.Write("</div>"); } public static string GetSymbolText(SymbolSearchResultEntry searchResult) { var resultText = $@"<a onclick=""LoadSourceCode('{searchResult.Symbol.ProjectId.AsJavaScriptStringEncoded()}', '{searchResult.File.AsJavaScriptStringEncoded()}', '{searchResult.Symbol.Id}');return false;"" href=""/?rightProject={searchResult.Symbol.ProjectId}&rightSymbol={searchResult.Symbol.Id}""> <div class=""resultItem""> <img src=""/content/icons/{searchResult.Glyph}"" height=""16"" width=""16"" /><div class=""resultKind"">{searchResult.Symbol.Kind.ToLowerInvariant()}</div><div class=""resultName"">{searchResult.Symbol.ShortName}</div><div class=""resultDescription"">{searchResult.DisplayName}</div> </div> </a>"; return resultText; } private static void WriteBaseMember(StringWriter writer, SymbolSearchResultEntry baseDefinition) { Write(writer, string.Format(@"<div class=""rH"" onclick=""ToggleExpandCollapse(this);return false;"">Base:</div>")); Write(writer, @"<div class=""rK"">"); writer.Write(GetSymbolText(baseDefinition)); writer.Write("</div>"); } public static string GenerateReferencesHtml(SymbolReferenceResult symbolReferenceResult) { var references = symbolReferenceResult.Entries; var definitionProjectId = symbolReferenceResult.ProjectId; var symbolId = symbolReferenceResult.SymbolId; var symbolName = symbolReferenceResult.SymbolName; int totalReferenceCount = 0; var referenceKindGroups = CreateReferences(references, out totalReferenceCount); using (var writer = new StringWriter()) { if ((symbolReferenceResult.RelatedDefinitions?.Count ?? 0) != 0) { var baseMember = symbolReferenceResult.RelatedDefinitions .Where(r => r.ReferenceKind == nameof(ReferenceKind.Override)) .FirstOrDefault(); if (baseMember != null) { WriteBaseMember(writer, baseMember); } var implementedMembers = symbolReferenceResult.RelatedDefinitions .Where(r => r.ReferenceKind == nameof(ReferenceKind.InterfaceMemberImplementation)) .ToList(); if (implementedMembers.Count != 0) { WriteImplementedInterfaceMembers(writer, implementedMembers); } } foreach (var referenceKind in referenceKindGroups.OrderBy(t => (int)t.Item1)) { string formatString = ""; switch (referenceKind.Item1) { case ReferenceKind.Reference: formatString = "{0} reference{1} to {2}"; break; case ReferenceKind.Definition: formatString = "{0} definition{1} of {2}"; break; case ReferenceKind.Constructor: formatString = "{0} constructor{1} of {2}"; break; case ReferenceKind.Instantiation: formatString = "{0} instantiation{1} of {2}"; break; case ReferenceKind.DerivedType: formatString = "{0} type{1} derived from {2}"; break; case ReferenceKind.InterfaceInheritance: formatString = "{0} interface{1} inheriting from {2}"; break; case ReferenceKind.InterfaceImplementation: formatString = "{0} implementation{1} of {2}"; break; case ReferenceKind.Override: formatString = "{0} override{1} of {2}"; break; case ReferenceKind.InterfaceMemberImplementation: formatString = "{0} implementation{1} of {2}"; break; case ReferenceKind.Write: formatString = "{0} write{1} to {2}"; break; case ReferenceKind.Read: formatString = "{0} read{1} of {2}"; break; case ReferenceKind.GuidUsage: formatString = "{0} usage{1} of Guid {2}"; break; case ReferenceKind.EmptyArrayAllocation: formatString = "{0} allocation{1} of empty arrays"; break; case ReferenceKind.MSBuildPropertyAssignment: formatString = "{0} assignment{1} to MSBuild property {2}"; break; case ReferenceKind.MSBuildPropertyUsage: formatString = "{0} usage{1} of MSBuild property {2}"; break; case ReferenceKind.MSBuildItemAssignment: formatString = "{0} assignment{1} to MSBuild item {2}"; break; case ReferenceKind.MSBuildItemUsage: formatString = "{0} usage{1} of MSBuild item {2}"; break; case ReferenceKind.MSBuildTargetDeclaration: formatString = "{0} declaration{1} of MSBuild target {2}"; break; case ReferenceKind.MSBuildTargetUsage: formatString = "{0} usage{1} of MSBuild target {2}"; break; case ReferenceKind.MSBuildTaskDeclaration: formatString = "{0} import{1} of MSBuild task {2}"; break; case ReferenceKind.MSBuildTaskUsage: formatString = "{0} call{1} to MSBuild task {2}"; break; case ReferenceKind.Text: formatString = "{0} text search hit{1} for '{2}'"; break; default: throw new NotImplementedException("Missing case for " + referenceKind.Item1); } var referencesOfSameKind = referenceKind.Item2.OrderBy(g => g.Item1, StringComparer.OrdinalIgnoreCase); totalReferenceCount = CountItems(referenceKind); string headerText = string.Format( formatString, totalReferenceCount, totalReferenceCount == 1 ? "" : "s", symbolName); Write(writer, string.Format(@"<div class=""rH"" onclick=""ToggleExpandCollapse(this); return false;"">{0}</div>", headerText)); Write(writer, @"<div class=""rK"">"); foreach (var sameAssemblyReferencesGroup in referencesOfSameKind) { string assemblyName = sameAssemblyReferencesGroup.Item1; Write(writer, "<div class=\"rA\" onclick=\"ToggleExpandCollapse(this); return false;\">{0} ({1})</div>", assemblyName, CountItems(sameAssemblyReferencesGroup)); Write(writer, "<div class=\"rG\" id=\"{0}\">", assemblyName); foreach (var sameFileReferencesGroup in sameAssemblyReferencesGroup.Item2.OrderBy(g => g.Item1)) { Write(writer, "<div class=\"rF\">"); var fileName = sameFileReferencesGroup.Item1; var glyph = "url('content/icons/" + GetGlyph(fileName) + ".png');"; WriteLine(writer, "<div class=\"rN\" style=\"background-image: {2}\">{0} ({1})</div>", fileName, CountItems(sameFileReferencesGroup), glyph); foreach (var sameLineReferencesGroup in sameFileReferencesGroup.Item2) { var first = sameLineReferencesGroup.First(); var lineNumber = first.ReferringSpan.LineNumber + 1; string onClick = $@"LoadSourceCode('{first.ReferringProjectId}', '{first.ReferringFilePath.AsJavaScriptStringEncoded()}', null, {lineNumber});return false;"; var url = $"/?leftProject={definitionProjectId}&leftSymbol={symbolId}&rightProject={first.ReferringProjectId}&file={HttpUtility.UrlEncode(first.ReferringFilePath)}&line={lineNumber}"; Write(writer, "<a class=\"rL\" onclick=\"{0}\" href=\"{1}\">", onClick, url); Write(writer, "<b>{0}</b>", sameLineReferencesGroup.Key); MergeOccurrences(writer, sameLineReferencesGroup); WriteLine(writer, "</a>"); } WriteLine(writer, "</div>"); } WriteLine(writer, "</div>"); } WriteLine(writer, "</div>"); } return writer.ToString(); } } private static string GetGlyph(string fileName) { return ModelConverter.GetFileNameGlyph(fileName); } private static int CountItems(Tuple<string, IEnumerable<IGrouping<int, Reference>>> sameFileReferencesGroup) { int count = 0; foreach (var line in sameFileReferencesGroup.Item2) { foreach (var occurrence in line) { count++; } } return count; } private static int CountItems( Tuple<string, IEnumerable<Tuple<string, IEnumerable<IGrouping<int, Reference>>>>> resultsInAssembly) { int count = 0; foreach (var file in resultsInAssembly.Item2) { count += CountItems(file); } return count; } private static int CountItems( Tuple<ReferenceKind, IEnumerable<Tuple<string, IEnumerable<Tuple<string, IEnumerable<IGrouping<int, Reference>>>>>>> results) { int count = 0; foreach (var item in results.Item2) { count += CountItems(item); } return count; } private static IEnumerable<Tuple<ReferenceKind, IEnumerable<Tuple<string, IEnumerable<Tuple<string, IEnumerable<IGrouping<int, Reference>> >> >> >> CreateReferences( IEnumerable<SymbolReferenceEntry> list, out int totalReferenceCount) { totalReferenceCount = 0; var result = list.GroupBy ( r0 => ParseReferenceKind(r0.ReferringSpan.Reference.ReferenceKind), (kind, referencesOfSameKind) => Tuple.Create ( kind, referencesOfSameKind.GroupBy ( r1 => r1.ReferringProjectId, (assemblyName, referencesInSameAssembly) => Tuple.Create ( assemblyName, referencesInSameAssembly.GroupBy ( r2 => r2.ReferringFilePath, (filePath, referencesInSameFile) => Tuple.Create ( filePath, referencesInSameFile.GroupBy ( r3 => r3.ReferringSpan.LineNumber + 1 ) ) ) ) ) ) ); return result; } private static ReferenceKind ParseReferenceKind(string kind) { ReferenceKind referenceKind; if (!Enum.TryParse<ReferenceKind>(kind, true, out referenceKind)) { referenceKind = ReferenceKind.Reference; } return referenceKind; } private static void MergeOccurrences(TextWriter writer, IEnumerable<SymbolReferenceEntry> referencesOnTheSameLineEx) { foreach (var referencesOnTheSameLineGroup in referencesOnTheSameLineEx.GroupBy(r => r.ReferringSpan.LineSpanText)) { var text = referencesOnTheSameLineGroup.Key; var referencesOnTheSameLine = referencesOnTheSameLineGroup.OrderBy(r => r.ReferringSpan.LineSpanStart); int current = 0; foreach (var occurrence in referencesOnTheSameLine) { if (occurrence.ReferringSpan.LineSpanStart < current) { continue; } if (occurrence.ReferringSpan.LineSpanStart > current) { var length = occurrence.ReferringSpan.LineSpanStart - current; length = Math.Min(length, text.Length); var substring = text.Substring(current, length); Write(writer, HttpUtility.HtmlEncode(substring)); } Write(writer, "<i>"); var highlightStart = occurrence.ReferringSpan.LineSpanStart; var highlightLength = occurrence.ReferringSpan.Length; if (highlightStart >= 0 && highlightStart < text.Length && highlightStart + highlightLength <= text.Length) { var highlightText = text.Substring(highlightStart, highlightLength); Write(writer, HttpUtility.HtmlEncode(highlightText)); } Write(writer, "</i>"); current = occurrence.ReferringSpan.LineSpanEnd; } if (current < text.Length) { Write(writer, HttpUtility.HtmlEncode(text.Substring(current, text.Length - current))); } } } private static void Write(TextWriter sw, string text) { sw.Write(text); } private static void Write(TextWriter sw, string format, params object[] args) { sw.Write(string.Format(format, args)); } private static void WriteLine(TextWriter sw, string text) { sw.WriteLine(text); } private static void WriteLine(TextWriter sw, string format, params object[] args) { sw.WriteLine(string.Format(format, args)); } } }
/* * * (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.Collections.Generic; using System.Globalization; using System.Text; using System.Web; using ASC.Core; using ASC.Core.Users; using ASC.Notify.Model; using ASC.Notify.Recipients; using ASC.Web.Community.Modules.News.Resources; using ASC.Web.Community.News.Code; using ASC.Web.Community.News.Code.DAO; using ASC.Web.Community.News.Code.Module; using ASC.Web.Community.Product; using ASC.Web.Core.Users; using ASC.Web.Core.Utility.Skins; using ASC.Web.Studio; using ASC.Web.Studio.Controls.Common; using ASC.Web.Studio.UserControls.Common.Comments; using ASC.Web.Studio.Utility; using ASC.Web.Studio.Utility.HtmlUtility; using FeedNS = ASC.Web.Community.News.Code; namespace ASC.Web.Community.News { public partial class Default : MainPage { //private BBCodeParser.Parser postParser = new BBCodeParser.Parser(CommonControlsConfigurer.SimpleTextConfig); private RequestInfo info; public RequestInfo Info { get { return info ?? (info = new RequestInfo(Request)); } } public int PageNumber { get { return ViewState["PageNumber"] != null ? Convert.ToInt32(ViewState["PageNumber"]) : 0; } set { ViewState["PageNumber"] = value; } } public int PageSize { get { return ViewState["PageSize"] != null ? Convert.ToInt32(ViewState["PageSize"]) : 20; } set { ViewState["PageSize"] = value; } } public long FeedsCount { get; set; } protected string EventTitle { get; set; } protected string StatusSubscribe { get; set; } protected Uri FeedItemUrlWithParam { get { return new Uri("~/Products/Community/Modules/News/EditNews.aspx?docID=" + Info.UserIdAttribute, UriKind.Relative); } } protected void Page_Load(object sender, EventArgs e) { commentList.Visible = CommunitySecurity.CheckPermissions(NewsConst.Action_Comment); pgNavigator.EntryCount = 1; pgNavigator.EntryCountOnPage = 1; if (IsPostBack) return; var storage = FeedStorageFactory.Create(); if (!string.IsNullOrEmpty(Request["docID"])) { long docID; if (long.TryParse(Request["docID"], out docID)) { //Show panel ContentView.Visible = false; FeedView.Visible = true; var feed = storage.GetFeed(docID); if (feed != null) { if (!feed.Readed) { storage.ReadFeed(feed.Id, SecurityContext.CurrentAccount.ID.ToString()); } FeedViewCtrl.Feed = feed; hdnField.Value = feed.Id.ToString(CultureInfo.CurrentCulture); InitCommentsView(storage, feed); FeedView.DataBind(); EventTitle = feed.Caption; var subscriptionProvider = NewsNotifySource.Instance.GetSubscriptionProvider(); var amAsRecipient = (IDirectRecipient)NewsNotifySource.Instance.GetRecipientsProvider().GetRecipient(SecurityContext.CurrentAccount.ID.ToString()); var isSubsribedOnComments = subscriptionProvider.IsSubscribed(NewsConst.NewComment, amAsRecipient, feed.Id.ToString()); var SubscribeTopicLink = string.Format(CultureInfo.CurrentCulture, string.Format(CultureInfo.CurrentCulture, "<a id=\"statusSubscribe\" class=\"follow-status " + (isSubsribedOnComments ? "subscribed" : "unsubscribed") + "\" title=\"{0}\" href=\"#\" onclick=\"SubscribeOnComments(this,'{1}','{2}','{3}');\"></a>", (isSubsribedOnComments ? NewsResource.UnsubscribeFromNewComments : NewsResource.SubscribeOnNewComments), feed.Id, NewsResource.SubscribeOnNewComments.ReplaceSingleQuote(), NewsResource.UnsubscribeFromNewComments.ReplaceSingleQuote())); SubscribeLinkBlock.Text = SubscribeTopicLink; Title = HeaderStringHelper.GetPageTitle((Master as NewsMaster).CurrentPageCaption ?? feed.Caption); } else { Response.Redirect(VirtualPathUtility.ToAbsolute("~/Products/Community/Modules/News/")); ContentView.Visible = true; FeedView.Visible = false; FeedRepeater.Visible = true; } } } else { PageNumber = string.IsNullOrEmpty(Request["page"]) ? 1 : Convert.ToInt32(Request["page"]); PageSize = string.IsNullOrEmpty(Request["size"]) ? 20 : Convert.ToInt32(Request["size"]); LoadData(); } InitScripts(); } private void InitScripts() { var jsResource = new StringBuilder(); jsResource.Append("jq('#tableForNavigation select').val(" + PageSize + ").change(function(evt) {changeCountOfRows(this.value);}).tlCombobox();"); Page.RegisterInlineScript(jsResource.ToString(), true); } private void InitCommentsView(IFeedStorage storage, FeedNS.Feed feed) { IList<CommentInfo> comments = BuildCommentsList(storage.GetFeedComments(feed.Id)); //AppendChildsComments(ref comments, storage.GetFeedComments(feed.Id)); ConfigureComments(commentList, feed); commentList.Items = comments; commentList.TotalCount = GetCommentsCount(comments); } private static void ConfigureComments(CommentsList commentList, FeedNS.Feed feed) { CommonControlsConfigurer.CommentsConfigure(commentList); commentList.BehaviorID = "_commentsObj"; commentList.FckDomainName = "news_comments"; commentList.ModuleName = "news"; commentList.ObjectID = feed != null ? feed.Id.ToString(CultureInfo.CurrentCulture) : ""; } private static int GetCommentsCount(ICollection<CommentInfo> comments) { var count = comments.Count; foreach (var info in comments) { count += GetCommentsCount(info.CommentList); } return count; } private static CommentInfo GetCommentInfo(FeedComment comment) { var info = new CommentInfo { CommentID = comment.Id.ToString(CultureInfo.CurrentCulture), UserID = new Guid(comment.Creator), TimeStamp = comment.Date, TimeStampStr = comment.Date.Ago(), IsRead = true, Inactive = comment.Inactive, CommentBody = HtmlUtility.GetFull(comment.Comment), UserFullName = DisplayUserSettings.GetFullUserName(new Guid(comment.Creator)), UserProfileLink = CommonLinkUtility.GetUserProfile(comment.Creator), UserAvatarPath = UserPhotoManager.GetBigPhotoURL(new Guid(comment.Creator)), IsEditPermissions = CommunitySecurity.CheckPermissions(comment, NewsConst.Action_Edit), IsResponsePermissions = CommunitySecurity.CheckPermissions(NewsConst.Action_Comment), UserPost = CoreContext.UserManager.GetUsers((new Guid(comment.Creator))).Title }; return info; } private static List<CommentInfo> BuildCommentsList(List<FeedComment> loaded) { return BuildCommentsList(loaded, 0); } private static List<CommentInfo> BuildCommentsList(List<FeedComment> loaded, long parentId) { var result = new List<CommentInfo>(); foreach (var comment in FeedComment.SelectChildLevel(parentId, loaded)) { var info = GetCommentInfo(comment); info.CommentList = BuildCommentsList(loaded, comment.Id); result.Add(info); } return result; } private void LoadData() { var storage = FeedStorageFactory.Create(); var feedType = FeedType.All; if (!string.IsNullOrEmpty(Request["type"])) { feedType = (FeedType)Enum.Parse(typeof(FeedType), Request["type"], true); var feedTypeInfo = FeedTypeInfo.FromFeedType(feedType); Title = HeaderStringHelper.GetPageTitle((Master as NewsMaster).CurrentPageCaption ?? feedTypeInfo.TypeName); } else { Title = HeaderStringHelper.GetPageTitle((Master as NewsMaster).CurrentPageCaption ?? NewsResource.NewsBreadCrumbs); } var feedsCount = !string.IsNullOrEmpty(Request["search"]) ? storage.SearchFeedsCount(Request["search"], feedType, Info.UserId) : storage.GetFeedsCount(feedType, Info.UserId); FeedsCount = feedsCount; if (feedsCount == 0) { FeedRepeater.Visible = false; MessageShow.Visible = true; string buttonLink; string buttonName; var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); var emptyScreenControl = new EmptyScreenControl { Describe = currentUser.IsVisitor() ? NewsResource.EmptyScreenTextVisitor : NewsResource.EmptyScreenText }; switch (feedType) { case FeedType.News: emptyScreenControl.ImgSrc = WebImageSupplier.GetAbsoluteWebPath("150x_news.png", NewsConst.ModuleId); emptyScreenControl.Header = NewsResource.EmptyScreenNewsCaption; buttonLink = FeedUrls.EditNewsUrl; buttonName = NewsResource.EmptyScreenNewsLink; break; case FeedType.Order: emptyScreenControl.ImgSrc = WebImageSupplier.GetAbsoluteWebPath("150x_order.png", NewsConst.ModuleId); emptyScreenControl.Header = NewsResource.EmptyScreenOrdersCaption; buttonLink = FeedUrls.EditOrderUrl; buttonName = NewsResource.EmptyScreenOrderLink; break; case FeedType.Advert: emptyScreenControl.ImgSrc = WebImageSupplier.GetAbsoluteWebPath("150x_advert.png", NewsConst.ModuleId); emptyScreenControl.Header = NewsResource.EmptyScreenAdvertsCaption; buttonLink = FeedUrls.EditAdvertUrl; buttonName = NewsResource.EmptyScreenAdvertLink; break; case FeedType.Poll: emptyScreenControl.ImgSrc = WebImageSupplier.GetAbsoluteWebPath("150x_poll.png", NewsConst.ModuleId); emptyScreenControl.Header = NewsResource.EmptyScreenPollsCaption; buttonLink = FeedUrls.EditPollUrl; buttonName = NewsResource.EmptyScreenPollLink; break; default: emptyScreenControl.ImgSrc = WebImageSupplier.GetAbsoluteWebPath("150x_newslogo.png", NewsConst.ModuleId); emptyScreenControl.Header = NewsResource.EmptyScreenEventsCaption; buttonLink = FeedUrls.EditNewsUrl; buttonName = NewsResource.EmptyScreenEventLink; break; } if (CommunitySecurity.CheckPermissions(NewsConst.Action_Add) && String.IsNullOrEmpty(Request["uid"]) && String.IsNullOrEmpty(Request["search"])) emptyScreenControl.ButtonHTML = String.Format("<a class='link underline blue plus' href='{0}'>{1}</a>", buttonLink, buttonName); MessageShow.Controls.Add(emptyScreenControl); } else { var pageSize = PageSize; var pageCount = (int)(feedsCount / pageSize + 1); if (pageCount < PageNumber) PageNumber = pageCount; var feeds = !string.IsNullOrEmpty(Request["search"]) ? storage.SearchFeeds(Request["search"], feedType, Info.UserId, pageSize, (PageNumber - 1) * pageSize) : storage.GetFeeds(feedType, Info.UserId, pageSize, (PageNumber - 1) * pageSize); pgNavigator.EntryCountOnPage = pageSize; pgNavigator.EntryCount = 0 < pageCount ? (int)feedsCount : pageSize; pgNavigator.CurrentPageNumber = PageNumber; pgNavigator.ParamName = "page"; if (!string.IsNullOrEmpty(Request["search"])) { pgNavigator.PageUrl = string.Format( CultureInfo.CurrentCulture, "{0}?search={1}&size={2}", VirtualPathUtility.ToAbsolute("~/Products/Community/Modules/News/"), Request["search"], pageSize ); } else { pgNavigator.PageUrl = string.IsNullOrEmpty(Request["type"]) ? string.Format( CultureInfo.CurrentCulture, "{0}?{1}&size={2}", VirtualPathUtility.ToAbsolute("~/Products/Community/Modules/News/"), (string.IsNullOrEmpty(Info.UserIdAttribute) ? string.Empty : "?" + Info.UserIdAttribute.Substring(1)), pageSize ) : string.Format( CultureInfo.CurrentCulture, "{0}?type={1}{2}&size={3}", VirtualPathUtility.ToAbsolute("~/Products/Community/Modules/News/"), Request["type"], Info.UserIdAttribute, pageSize); } FeedRepeater.DataSource = feeds; FeedRepeater.DataBind(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Globalization { public partial class CompareInfo { // ICU uses a char* (UTF-8) to represent a locale name. private readonly byte[] m_sortNameAsUtf8; internal unsafe CompareInfo(CultureInfo culture) { m_name = culture.m_name; m_sortName = culture.SortName; m_sortNameAsUtf8 = System.Text.Encoding.UTF8.GetBytes(m_sortName); } internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); if (value.Length == 0) { return startIndex; } if (count < value.Length) { return -1; } if (ignoreCase) { fixed (char* pSource = source) { int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false); return index != -1 ? startIndex + index : -1; } } int endIndex = startIndex + (count - value.Length); for (int i = startIndex; i <= endIndex; i++) { int valueIndex, sourceIndex; for (valueIndex = 0, sourceIndex = i; valueIndex < value.Length && source[sourceIndex] == value[valueIndex]; valueIndex++, sourceIndex++) ; if (valueIndex == value.Length) { return i; } } return -1; } internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); if (value.Length == 0) { return startIndex; } if (count < value.Length) { return -1; } // startIndex is the index into source where we start search backwards from. // leftStartIndex is the index into source of the start of the string that is // count characters away from startIndex. int leftStartIndex = startIndex - count + 1; if (ignoreCase) { fixed (char* pSource = source) { int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true); return lastIndex != -1 ? leftStartIndex + lastIndex : -1; } } for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--) { int valueIndex, sourceIndex; for (valueIndex = 0, sourceIndex = i; valueIndex < value.Length && source[sourceIndex] == value[valueIndex]; valueIndex++, sourceIndex++) ; if (valueIndex == value.Length) { return i; } } return -1; } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Contract.Assert(source != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0); } [System.Security.SecuritySafeCritical] private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2); } [System.Security.SecuritySafeCritical] private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Contract.Assert(string1 != null); Contract.Assert(string2 != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); fixed (char* pString1 = string1) { fixed (char* pString2 = string2) { return Interop.GlobalizationInterop.CompareString(m_sortNameAsUtf8, pString1 + offset1, length1, pString2 + offset2, length2, options); } } } [System.Security.SecuritySafeCritical] private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { return startIndex; } if (options == CompareOptions.Ordinal) { return IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false); } fixed (char* pSource = source) { int index = Interop.GlobalizationInterop.IndexOf(m_sortNameAsUtf8, target, pSource + startIndex, count, options); return index != -1 ? index + startIndex : -1; } } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { return startIndex; } if (options == CompareOptions.Ordinal) { return LastIndexOfOrdinal(source, target, startIndex, count, ignoreCase: false); } // startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source // of the start of the string that is count characters away from startIndex. int leftStartIndex = (startIndex - count + 1); fixed (char* pSource = source) { int lastIndex = Interop.GlobalizationInterop.LastIndexOf(m_sortNameAsUtf8, target, pSource + (startIndex - count + 1), count, options); return lastIndex != -1 ? lastIndex + leftStartIndex : -1; } } private bool StartsWith(string source, string prefix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(prefix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return Interop.GlobalizationInterop.StartsWith(m_sortNameAsUtf8, prefix, source, source.Length, options); } private bool EndsWith(string source, string suffix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(suffix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return Interop.GlobalizationInterop.EndsWith(m_sortNameAsUtf8, suffix, source, source.Length, options); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy) { Contract.Assert(source != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(m_sortNameAsUtf8, source, source.Length, null, 0, options); // As an optimization, for small sort keys we allocate the buffer on the stack. if (sortKeyLength <= 256) { byte* pSortKey = stackalloc byte[sortKeyLength]; Interop.GlobalizationInterop.GetSortKey(m_sortNameAsUtf8, source, source.Length, pSortKey, sortKeyLength, options); return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy); } byte[] sortKey = new byte[sortKeyLength]; fixed(byte* pSortKey = sortKey) { Interop.GlobalizationInterop.GetSortKey(m_sortNameAsUtf8, source, source.Length, pSortKey, sortKeyLength, options); return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy); } } [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy); } }
#if !DXCORE3 using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel; using System.Threading; namespace DevExpress.Mvvm.UI.Native { public abstract class JumpActionsManagerBase : IDisposable { public const int DefaultMillisecondsTimeout = 500; [StructLayout(LayoutKind.Sequential)] protected struct GuidData { public GuidData(Guid guid) : this(guid.ToByteArray()) { } public GuidData(byte[] bytes) { Byte0 = bytes[0]; Byte1 = bytes[1]; Byte2 = bytes[2]; Byte3 = bytes[3]; Byte4 = bytes[4]; Byte5 = bytes[5]; Byte6 = bytes[6]; Byte7 = bytes[7]; Byte8 = bytes[8]; Byte9 = bytes[9]; ByteA = bytes[10]; ByteB = bytes[11]; ByteC = bytes[12]; ByteD = bytes[13]; ByteE = bytes[14]; ByteF = bytes[15]; } public byte Byte0; public byte Byte1; public byte Byte2; public byte Byte3; public byte Byte4; public byte Byte5; public byte Byte6; public byte Byte7; public byte Byte8; public byte Byte9; public byte ByteA; public byte ByteB; public byte ByteC; public byte ByteD; public byte ByteE; public byte ByteF; public byte[] AsBytesArray { get { return new byte[16] { Byte0, Byte1, Byte2, Byte3, Byte4, Byte5, Byte6, Byte7, Byte8, Byte9, ByteA, ByteB, ByteC, ByteD, ByteE, ByteF }; } } public Guid AsGuid { get { return new Guid(AsBytesArray); } } } [ServiceContract] protected interface IApplicationInstance { [OperationContract] void Execute(string command); } const string MainMutexName = "C4339FDC-8943-4AA6-8DB9-644D68462BC7_"; protected const string InstancesFileName = "HB42A04D-FFA1-4755-9854-CB8DC81AAE89_"; protected const string InstanceNamePrefix = "5BCE503C-DB8D-440A-BEEC-9C963A364DBF_"; protected const string EndPointName = "Pipe"; Mutex mainMutex; Tuple<IntPtr, IntPtr> instancesFile = null; volatile bool disposed = false; public JumpActionsManagerBase(int millisecondsTimeout) { MillisecondsTimeout = millisecondsTimeout; } ~JumpActionsManagerBase() { Dispose(false); } public void Dispose() { if(disposed) return; disposed = true; Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { try { Mutex mainMutex = WaitMainMutex(!disposing); try { DisposeInstancesFile(); } finally { mainMutex.ReleaseMutex(); } } catch(TimeoutException) { if(disposing) throw; } } #if DEBUG protected abstract object CurrentProcessTag { get; } #endif [SecuritySafeCritical] void DisposeInstancesFile() { if(instancesFile == null) return; UnmapViewAndCloseFileMapping(instancesFile); instancesFile = null; } protected int MillisecondsTimeout { get; private set; } [SecuritySafeCritical] protected Mutex GetMainMutex(bool safe) { if(safe) return GetMainMutexCore(true); if(mainMutex == null) mainMutex = GetMainMutexCore(false); return mainMutex; } [SecuritySafeCritical] protected Mutex GetMainMutexCore(bool safe) { return new Mutex(false, MainMutexName + ApplicationId); } const byte MaxInstancesCount = 99; [SecuritySafeCritical] Tuple<IntPtr, IntPtr> GetInstancesFile() { if(instancesFile == null) { bool alreadyExists; instancesFile = CreateFileMappingAndMapView((1 + MaxInstancesCount) * Marshal.SizeOf(typeof(GuidData)), InstancesFileName + ApplicationId, out alreadyExists); if(!alreadyExists) { try { UpdateInstancesFile(new GuidData[] { }); } catch { DisposeInstancesFile(); throw; } } } return instancesFile; } protected static string GetServiceUri(GuidData applicationInstance) { return string.Format("net.pipe://localhost/{0}{1}", InstanceNamePrefix, applicationInstance.AsGuid); } protected static string GetIsAliveFlagFileName(GuidData applicationInstance) { return string.Format("IsAlive_{0}{1}", InstanceNamePrefix, applicationInstance.AsGuid); } [SecuritySafeCritical] protected GuidData[] GetApplicationInstances(bool isCurrentProcessApplicationInstance) { Tuple<IntPtr, IntPtr> instancesFile = GetInstancesFile(); GuidData listProperties = (GuidData)Marshal.PtrToStructure(instancesFile.Item2, typeof(GuidData)); int instancesCount = listProperties.Byte0; GuidData[] instances = new GuidData[instancesCount]; for(int i = 0; i < instancesCount; ++i) instances[i] = (GuidData)Marshal.PtrToStructure(instancesFile.Item2 + (1 + i) * Marshal.SizeOf(typeof(GuidData)), typeof(GuidData)); return instances; } [SecuritySafeCritical] protected bool IsAlive(GuidData instance) { bool isAliveFlagFileExists = false; Tuple<IntPtr, IntPtr> file = CreateFileMappingAndMapView(1, GetIsAliveFlagFileName(instance), out isAliveFlagFileExists); UnmapViewAndCloseFileMapping(file); return isAliveFlagFileExists; } [SecuritySafeCritical] protected void UpdateInstancesFile(GuidData[] instances) { Tuple<IntPtr, IntPtr> instancesFile = GetInstancesFile(); byte instancesCount = CorceInstancesCount(instances.Length); for(int i = 0; i < instancesCount; ++i) Marshal.StructureToPtr(instances[i], instancesFile.Item2 + (1 + i) * Marshal.SizeOf(typeof(GuidData)), false); GuidData listProperties = new GuidData() { Byte0 = instancesCount }; Marshal.StructureToPtr(listProperties, instancesFile.Item2, false); } static byte CorceInstancesCount(int instancesCount) { return (byte)(instancesCount % MaxInstancesCount); } protected void WaitOne(WaitHandle waitHandle) { if(!waitHandle.WaitOne(MillisecondsTimeout)) throw new TimeoutException(); } protected Mutex WaitMainMutex(bool safe) { Mutex mainMutex = GetMainMutex(safe); try { WaitOne(mainMutex); } catch (AbandonedMutexException) { } return mainMutex; } protected abstract string ApplicationId { get; } #if DEBUG class MemoryMappedFileInfo { public MemoryMappedFileInfo(IntPtr fileObject, IntPtr fileView, object owner) { FileObject = fileObject; FileView = fileView; Owner = owner; } public IntPtr FileObject { get; private set; } public IntPtr FileView { get; private set; } public object Owner { get; private set; } } static Dictionary<string, HashSet<MemoryMappedFileInfo>> memoryMappedFiles = new Dictionary<string, HashSet<MemoryMappedFileInfo>>(); public static void ClearMemoryMappedFiles() { memoryMappedFiles.Clear(); } [SecuritySafeCritical] public static void EmulateProcessKill(object processTag) { MemoryMappedFileInfo[] openFiles = memoryMappedFiles.SelectMany(x => x.Value).Where(m => object.Equals(m.Owner, processTag)).ToArray(); foreach(var openFile in openFiles) UnmapViewAndCloseFileMapping(new Tuple<IntPtr, IntPtr>(openFile.FileObject, openFile.FileView)); } #endif [SecurityCritical] protected Tuple<IntPtr, IntPtr> CreateFileMappingAndMapView(int dwMaximumSizeLow, string lpName, out bool alreadyExists) { if(dwMaximumSizeLow == 0) { dwMaximumSizeLow = 1; #if DEBUG if(!memoryMappedFiles.ContainsKey(lpName)) throw new FileNotFoundException(lpName, lpName); #endif } IntPtr fileObject = Import.CreateFileMapping(Import.InvalidHandleValue, IntPtr.Zero, Import.PageReadwrite, 0, (uint)dwMaximumSizeLow, lpName); if(fileObject == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); alreadyExists = Marshal.GetLastWin32Error() == Import.ERROR_ALREADY_EXISTS; IntPtr fileView = Import.MapViewOfFile(fileObject, Import.FileMapAllAccess, 0, 0, UIntPtr.Zero); if(fileView == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); #if DEBUG HashSet<MemoryMappedFileInfo> refs; if(!memoryMappedFiles.TryGetValue(lpName, out refs)) { refs = new HashSet<MemoryMappedFileInfo>(); memoryMappedFiles.Add(lpName, refs); } refs.Add(new MemoryMappedFileInfo(fileObject, fileView, CurrentProcessTag)); #endif return new Tuple<IntPtr, IntPtr>(fileObject, fileView); } [SecurityCritical] protected static void UnmapViewAndCloseFileMapping(Tuple<IntPtr, IntPtr> file) { #if DEBUG var fileData = memoryMappedFiles.Where(p => p.Value.RemoveWhere(f => f.FileObject == file.Item1) == 1).Single(); if(fileData.Value.Count == 0) memoryMappedFiles.Remove(fileData.Key); #endif Import.UnmapViewOfFile(file.Item2); Import.CloseHandle(file.Item1); } static class Import { [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern IntPtr CreateFileMapping( IntPtr lpBaseAddress, IntPtr lpFileMappingAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern IntPtr MapViewOfFile( IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumberOfBytesToMap); [return: MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); public const uint FileMapAllAccess = 0xF001F; public const uint PageReadwrite = 0x04; public static readonly IntPtr InvalidHandleValue = new IntPtr(-1); public const int ERROR_ALREADY_EXISTS = 183; } } } #endif
// Created by Paul Gonzalez Becerra using System; using System.IO; using System.Text; using Saserdote.Animation; using Saserdote.ContentPipeline; using Saserdote.DataSystems; using Saserdote.GamingServices; using Saserdote.Graphics; using Saserdote.Mathematics; using Saserdote.Mathematics.Collision; namespace Saserdote.ContentPipeline.Streams { public class ModelContentStream:IContentReader,IContentWriter { #region --- Field Variables --- // Variables private FDictionary<PackedVertex, ushort> mapped= new FDictionary<PackedVertex, ushort>(); private Game game; #endregion // Field Variables #region --- Constructors --- public ModelContentStream(Game pmGame) { game= pmGame; } #endregion // Constructors #region --- Methods --- // Gets if the vertex is the same private bool getSimilarVertexIndex(PackedVertex packed, out ushort result) { if(mapped.contains(packed)) { result= mapped[packed]; return true; } result= (ushort)0; return false; } // Meant for wavefront objects private void multiIndexVBO(FList<ObjFileHelper> faceNums, FList<Point3f> in_vertices, FList<TexCoord> in_uvs, ref FList<Point3f> out_vertices, ref FList<TexCoord> out_uvs, ref FList<ushort> out_indices) { for(int i= 0; i< faceNums.size; i++) { // Variables ushort index; PackedVertex packed; packed= new PackedVertex(in_vertices[faceNums[i].vertex], in_uvs[faceNums[i].texCoord]); if(getSimilarVertexIndex(packed, out index)) out_indices.add(index); else { out_vertices.add(in_vertices[faceNums[i].vertex]); out_uvs.add(in_uvs[faceNums[i].texCoord]); index= (ushort)(out_vertices.size-1); out_indices.add(index); mapped.add(packed, index); } } mapped.clear(); } // Creates a list of models using open assets importer public FList<Model> createModel(string fileName) { if(!File.Exists(fileName)) throw new Exception("File does not exist"); // Variables Assimp.AssimpImporter importer= new Assimp.AssimpImporter(); Assimp.Scene scene= importer.ImportFile(fileName); Assimp.Mesh[] meshes= scene.Meshes; Assimp.Animation[] anims= scene.Animations; Model mdl= new Model("Unnamed"); FList<Point3f> vertices= new FList<Point3f>(); FList<ushort> faces= new FList<ushort>(); FList<TexCoord> texcoords= new FList<TexCoord>(); FList<Bone> bones= new FList<Bone>(); FList<ushort> vIDs= new FList<ushort>(); FList<float> ws= new FList<float>(); for(int h= 0; h< scene.MeshCount; h++) { for(int k= 0; k< meshes[h].VertexCount; k++) { vertices.add(new Point3f ( meshes[h].Vertices[k].X, meshes[h].Vertices[k].Y, meshes[h].Vertices[k].Z )); } for(int k= 0; k< meshes[h].GetShortIndices().Length; k++) faces.add((ushort)(meshes[h].GetShortIndices()[k])); for(int k= 0; k< meshes[h].TextureCoordsChannelCount; k++) { for(int i= 0; i< meshes[h].GetTextureCoords(k).Length; i++) { texcoords.add(new TexCoord ( meshes[h].GetTextureCoords(k)[i].X, meshes[h].GetTextureCoords(k)[i].Y )); } } for(int k= 0; k< meshes[h].BoneCount; k++) { for(int i= 0; i< meshes[h].Bones[k].VertexWeightCount; i++) { vIDs.add((ushort)(meshes[h].Bones[k].VertexWeights[i].VertexID)); ws.add(meshes[h].Bones[k].VertexWeights[i].Weight); } bones.add(new Bone(vIDs.toArray(), ws.toArray())); vIDs.clear(); ws.clear(); } switch((uint)(meshes[h].PrimitiveType)) { case 2: mdl.meshes.add(new LMesh(vertices.toArray(), new Color(1f), faces.toArray())); break; case 4: mdl.meshes.add(new TMesh(vertices.toArray(), texcoords.toArray(), new Color(1f), faces.toArray())); break; case 8: mdl.meshes.add(new QMesh(vertices.toArray(), texcoords.toArray(), new Color(1f), faces.toArray())); break; default: mdl.meshes.add(new TMesh(vertices.toArray(), texcoords.toArray(), new Color(1f), faces.toArray())); break; } mdl.meshes.items[mdl.meshes.size-1]= transformMeshIfNecessary(fileName, mdl.meshes.items[mdl.meshes.size-1]); vertices.clear(); faces.clear(); texcoords.clear(); } return new FList<Model>(mdl); } // Transforms the mesh around to accomadate opengl if necessary private BaseMesh transformMeshIfNecessary(string fileName, BaseMesh mesh) { // Variables Matrix m= Matrix.IDENTITY; switch(fileName.Substring(fileName.LastIndexOf('.'))) { case ".dae": m.rotateYAxis(Mathx.PI_F); m= Matrix.createRotationXAxis(-Mathx.PI_OVER_2_F)*m; mesh.applyMatrix(m); break; } return mesh; } // Creates a model from a wavefront object file private FList<Model> createObj(string fileName) { // Variables string[] lines= File.ReadAllLines(fileName); ImportedMeshFile meshFile= new ImportedMeshFile("NULL"); FList<Point3f> vertices= new FList<Point3f>(); FList<TexCoord> uvs= new FList<TexCoord>(); FList<ObjFileHelper> faces= new FList<ObjFileHelper>(); FList<ushort> refFaces= new FList<ushort>(); Model mdl= new Model(); string name= "Unnamed"; for(int i= 0; i< lines.Length; i++) { // Variables string[] splits= splitString(lines[i], " \t"); if(splits.Length> 0) { if(splits[0]== "o") { if(meshFile.vertices.size!= 0) { vertices.clear(); uvs.clear(); refFaces.clear(); if(meshFile.uvs.size!= 0) multiIndexVBO(faces, meshFile.vertices, meshFile.uvs, ref vertices, ref uvs, ref refFaces); else { vertices= meshFile.vertices; for(int h= 0; h< vertices.size; h++) uvs.add(new TexCoord(0f, 0f)); for(int h= 0; h< faces.size; h++) refFaces.add((ushort)(faces[h].vertex)); } mdl.meshes.add(new TMesh(vertices.toArray(), uvs.toArray(), new Color(1f), refFaces.toArray())); mdl.meshes[mdl.meshes.size-1].name= name; } name= splits[1]; } if(splits[0]== "v") { meshFile.vertices.add(new Point3f(float.Parse(splits[1]), float.Parse(splits[2]), float.Parse(splits[3]))); } if(splits[0]== "vt") { meshFile.uvs.add(new TexCoord(float.Parse(splits[1]), float.Parse(splits[2]))); } if(splits[0]== "f") { if(splits[1].Contains("/")) { // Variables string[] douSplit; douSplit= splits[1].Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); faces.add(new ObjFileHelper(int.Parse(douSplit[0])-1, int.Parse(douSplit[1])-1, int.Parse(douSplit[1])-1)); douSplit= splits[2].Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); faces.add(new ObjFileHelper(int.Parse(douSplit[0])-1, int.Parse(douSplit[1])-1, int.Parse(douSplit[1])-1)); douSplit= splits[3].Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); faces.add(new ObjFileHelper(int.Parse(douSplit[0])-1, int.Parse(douSplit[1])-1, int.Parse(douSplit[1])-1)); } else { faces.add(new ObjFileHelper(int.Parse(splits[1])-1, int.Parse(splits[1])-1, int.Parse(splits[1])-1)); faces.add(new ObjFileHelper(int.Parse(splits[2])-1, int.Parse(splits[2])-1, int.Parse(splits[2])-1)); faces.add(new ObjFileHelper(int.Parse(splits[3])-1, int.Parse(splits[3])-1, int.Parse(splits[3])-1)); } } } } vertices.clear(); uvs.clear(); refFaces.clear(); if(meshFile.uvs.size!= 0) multiIndexVBO(faces, meshFile.vertices, meshFile.uvs, ref vertices, ref uvs, ref refFaces); else { vertices= meshFile.vertices; for(int i= 0; i< vertices.size; i++) uvs.add(new TexCoord(0f, 0f)); for(int i= 0; i< faces.size; i++) refFaces.add((ushort)(faces[i].vertex)); } mdl.meshes.add(new TMesh(vertices.toArray(), uvs.toArray(), new Color(1f), refFaces.toArray())); mdl.meshes[mdl.meshes.size-1].name= name; return (new FList<Model>(mdl)); } // Creates a model from a Venen Graphic Model file private FList<Model> createSvgm(string fileName) { if(!File.Exists(fileName)) return null; // Variables FList<Model> mdls= new FList<Model>(); string meshName; string texName, texPath; byte meshType; Point3f[] vertices; Color color; TexCoord[] uvs; ushort[] faces; using(BinaryReader brd= new BinaryReader(new FileStream(fileName, FileMode.Open), Encoding.ASCII)) { brd.ReadChars(5); while(brd.PeekChar()!= -1) { switch(brd.ReadChar()) { case 'M': mdls.add(new Model(brd.ReadString())); break; case 'm': meshType= brd.ReadByte(); meshName= brd.ReadString(); vertices= new Point3f[brd.ReadInt32()]; uvs= new TexCoord[brd.ReadInt32()]; faces= new ushort[brd.ReadInt32()]; for(int i= 0; i< vertices.Length; i++) vertices[i]= new Point3f(brd.ReadSingle(), brd.ReadSingle(), brd.ReadSingle()); for(int i= 0; i< uvs.Length; i++) uvs[i]= new TexCoord(brd.ReadSingle(), brd.ReadSingle()); color= new Color(brd.ReadByte(), brd.ReadByte(), brd.ReadByte(), brd.ReadByte()); for(int i= 0; i< faces.Length; i++) faces[i]= brd.ReadUInt16(); texName= brd.ReadString(); texPath= brd.ReadString(); switch(meshType) { case 12: mdls[mdls.size-1].meshes.add(new LMesh(vertices, color, faces)); break; case 13: mdls[mdls.size-1].meshes.add(new TMesh(vertices, uvs, color, faces)); break; case 14: mdls[mdls.size-1].meshes.add(new QMesh(vertices, uvs, color, faces)); break; default: mdls[mdls.size-1].meshes.add(new TMesh(vertices, uvs, color, faces)); break; } mdls[mdls.size-1].meshes[mdls[mdls.size-1].meshes.size-1].name= meshName; try { if(texName!= "NO_NAME_NULL_84748") mdls[mdls.size-1].meshes[mdls[mdls.size-1].meshes.size-1].texture= game.loadedTextures[texName]; } catch {} break; case 'b': switch(brd.ReadByte()) { case 12: mdls[mdls.size-1].bounds.add(new BVRectangle ( new Point2f(brd.ReadSingle(), brd.ReadSingle()), new Point2f(brd.ReadSingle(), brd.ReadSingle()) )); break; case 13: mdls[mdls.size-1].bounds.add(new BVBox ( new Point3f(brd.ReadSingle(), brd.ReadSingle(), brd.ReadSingle()), new Point3f(brd.ReadSingle(), brd.ReadSingle(), brd.ReadSingle()) )); break; case 14: mdls[mdls.size-1].bounds.add(new BVCircle ( new Point2f(brd.ReadSingle(), brd.ReadSingle()), brd.ReadSingle() )); break; case 15: mdls[mdls.size-1].bounds.add(new BVCylinder ( new Point3f(brd.ReadSingle(), brd.ReadSingle(), brd.ReadSingle()), brd.ReadSingle(), brd.ReadSingle() )); break; } break; } } brd.Close(); } return mdls; } // Writes a Venen Graphic Model file with the given filename and mdls private bool writeSvgm(string fileName, FList<Model> mdls) { if(mdls.size== 0) return false; // Variables Point3f pt; Color c; TexCoord tc; Texture tex; BoundingVolume bv; string name; int i; using(BinaryWriter bwr= new BinaryWriter(new FileStream(fileName, FileMode.Create), Encoding.ASCII)) { bwr.Write("CbPGB".ToCharArray()); for(int h= 0; h< mdls.size; h++) { bwr.Write('M'); bwr.Write(mdls[h].name); for(int k= 0; k< mdls[h].meshes.size; k++) { bwr.Write('m'); if(mdls[h].meshes[k] is LMesh) bwr.Write((byte)(12)); else if(mdls[h].meshes[k] is TMesh) bwr.Write((byte)(13)); else if(mdls[h].meshes[k] is QMesh) bwr.Write((byte)(14)); else bwr.Write((byte)(13)); bwr.Write(mdls[h].meshes[k].name); bwr.Write(mdls[h].meshes[k].getVertices().Length); bwr.Write(mdls[h].meshes[k].getTexCoords().Length); bwr.Write(mdls[h].meshes[k].getIndices().Length); for(i= 0; i< mdls[h].meshes[k].getVertices().Length; i++) { pt= mdls[h].meshes[k].getVertices()[i]; bwr.Write(pt.x); bwr.Write(pt.y); bwr.Write(pt.z); } for(i= 0; i< mdls[h].meshes[k].getTexCoords().Length; i++) { tc= mdls[h].meshes[k].getTexCoords()[i]; bwr.Write(tc.u); bwr.Write(tc.v); } if(mdls[h].meshes[k].getColors().Length> 0) c= mdls[h].meshes[k].getColors()[0]; else c= new Color(1f, 1f, 1f, 1f); bwr.Write(c.redb); bwr.Write(c.greenb); bwr.Write(c.blueb); bwr.Write(c.alphab); for(i= 0; i< mdls[h].meshes[k].getIndices().Length; i++) bwr.Write(mdls[h].meshes[k].getIndices()[i]); tex= mdls[h].meshes[k].texture; bwr.Write(tex.PATH); name= findNameOfTexture(tex.PATH); bwr.Write(name); } for(int k= 0; k< mdls[h].bounds.size; k++) { bwr.Write('b'); bv= mdls[h].bounds[k]; if(bv is BVRectangle) { bwr.Write((byte)12); bwr.Write(((BVRectangle)bv).min.x); bwr.Write(((BVRectangle)bv).min.y); bwr.Write(((BVRectangle)bv).max.x); bwr.Write(((BVRectangle)bv).max.y); } else if(bv is BVBox) { bwr.Write((byte)13); bwr.Write(((BVBox)bv).min.x); bwr.Write(((BVBox)bv).min.y); bwr.Write(((BVBox)bv).min.z); bwr.Write(((BVBox)bv).max.x); bwr.Write(((BVBox)bv).max.y); bwr.Write(((BVBox)bv).max.z); } else if(bv is BVCircle) { bwr.Write((byte)14); bwr.Write(((BVCircle)bv).pPos.x); bwr.Write(((BVCircle)bv).pPos.y); bwr.Write(((BVCircle)bv).radius); } else if(bv is BVCylinder) { bwr.Write((byte)15); bwr.Write(((BVCylinder)bv).pPos.x); bwr.Write(((BVCylinder)bv).pPos.y); bwr.Write(((BVCylinder)bv).pPos.z); bwr.Write(((BVCylinder)bv).height); bwr.Write(((BVCylinder)bv).radius); } } } } return true; } // Finds the name of the texture by the given path private string findNameOfTexture(string path) { for(int i= 0; i< game.loadedTextures.size; i++) { if(game.loadedTextures.getValueByIndex(i).PATH== path) return game.loadedTextures.getKeyByIndex(i); } return "NO_NAME_NULL_84748"; } // Splits the given string by the given chars private string[] splitString(string str, string splitBy) { return str.Split(splitBy.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); } #endregion // Methods #region --- Inherited Methods --- // Reads the file and creates it public bool load<T>(string fileName, out T result) { if(!File.Exists(fileName)) { result= default(T); return false; } // Variables string ext= fileName.Substring(fileName.LastIndexOf('.')); if(typeof(T)== typeof(Model)) { if(ext== ".sgmdl") result= (T)((object)(createSvgm(fileName)[0])); else result= (T)((object)(createModel(fileName)[0])); return true; } if(typeof(T)== typeof(FList<Model>)) { if(ext== ".sgmdl") result= (T)((object)(createSvgm(fileName))); else result= (T)((object)(createModel(fileName))); return true; } result= default(T); return false; } // Saves to the file the array of given objects and creates it public bool save<T>(string fileName, params T[] objs) { if(typeof(T)== typeof(Model)) { // Variables FList<Model> mdls= new FList<Model>(); if(objs!= null) { for(int i= 0; i< objs.Length; i++) { mdls.add((Model)((object)(objs[i]))); } } fileName= fileName.Replace(fileName.Substring(fileName.LastIndexOf('.')), ".sgmdl"); return writeSvgm(fileName, mdls); } return false; } #endregion // Inherited Methods #region --- Nested Objects --- internal struct PackedVertex { #region --- Field Variables --- // Variables public Point3f vertex; public TexCoord texCoord; #endregion // Field Variables #region --- Constructors --- public PackedVertex(Point3f pmVertex, TexCoord uv) { vertex= pmVertex; texCoord= uv; } #endregion // Constructors #region --- Methods --- // Finds if the two packed vertices are equal public bool equals(PackedVertex pv) { if(vertex!= pv.vertex) return false; if(texCoord!= pv.texCoord) return false; return true; } #endregion // Methods #region --- Inherited Methods --- // Finds if the given object is equal to the given object public override bool Equals(object obj) { if(obj== null) return false; if(obj is PackedVertex) return equals((PackedVertex)obj); return false; } // Gets the hash code public override int GetHashCode() { return vertex.GetHashCode()+texCoord.GetHashCode(); } #endregion // Inherited Methods } internal struct ObjFileHelper { #region --- Field Variables --- // Variables public readonly int vertex; public readonly int texCoord; public readonly int normal; #endregion // Field Variables #region --- Constructors --- public ObjFileHelper(int pmVertex, int pmTexCoord, int pmNormal) { vertex= pmVertex; texCoord= pmTexCoord; normal= pmNormal; } #endregion // Constructors } internal struct ImportedMeshFile { #region --- Field Variables --- // Variables public FList<Point3f> vertices; public FList<Color> colors; public FList<TexCoord> uvs; public FList<ushort> faces; public string name; public Texture texture; #endregion // Field Variables #region --- Constructors --- public ImportedMeshFile(string pmName) { name= pmName; texture= Texture.NULL; vertices= new FList<Point3f>(); colors= new FList<Color>(); uvs= new FList<TexCoord>(); faces= new FList<ushort>(); } #endregion // Constructors } #endregion // Nested Objects } } // End of File
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddByte() { var test = new SimpleBinaryOpTest__AddByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddByte { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int Op2ElementCount = VectorSize / sizeof(Byte); private const int RetElementCount = VectorSize / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static SimpleBinaryOpTest__AddByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AddByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Add( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Add( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Add( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddByte(); var result = Avx2.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { if ((byte)(left[0] + right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)(left[i] + right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Add)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web.Script.Serialization; namespace rDSN.Tron.Utility { public class HttpService { public void RegisterStaticFileDirectory(string virtualPath, string localRoot) { if (virtualPath.Last() == '/' && virtualPath.Length > 1) { virtualPath = virtualPath.Substring(0, virtualPath.Length - 1); } if (localRoot.Last() != '/' && localRoot.Last() != '\\') { localRoot += '\\'; } RegisterHandler(virtualPath, (c, p, q) => StaticFileHandler(virtualPath, Path.GetFullPath(localRoot), c, p, q)); } public delegate string WebApiRequestHandler(string subApi, string query, string requestObjectInJson); public delegate TResponse TypedWebApiHandler<in TRequest, out TResponse>(TRequest request); public delegate TResponse TypedVoidWebApiHandler<out TResponse>(); public void RegisterWebApi(string apiPath, WebApiRequestHandler handler) { RegisterHandler(apiPath, (c, p, q) => WebApiCallback(handler, c, p, q)); } public void RegisterTypedWebApi<TRequest, TResponse>(string apiPath, TypedWebApiHandler<TRequest, TResponse> handler) { RegisterHandler(apiPath, (c, p, q) => WebApiCallback( (api, query, requestObjectInJson) => { var req = new JavaScriptSerializer().Deserialize<TRequest>(requestObjectInJson); var resp = handler(req); return new JavaScriptSerializer().Serialize(resp); }, c, p, q) ); } public void RegisterTypedWebApi<TResponse>(string apiPath, TypedVoidWebApiHandler<TResponse> handler) { RegisterHandler(apiPath, (c, p, q) => WebApiCallback( (api, query, requestObjectInJson) => { var resp = handler(); return new JavaScriptSerializer().Serialize(resp); }, c, p, q) ); } public FlowErrorCode Start(int port) { if (_listener != null) { return FlowErrorCode.HttpServiceAlreadyStarted; } if (!HttpListener.IsSupported) { return FlowErrorCode.PlatformNotSupported; } _sortedHandlerArrary = _handlers.ToArray(); _listener = new HttpListener(); _listener.Prefixes.Add($@"http://+:{port}/"); _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; _listener.Start(); _listener.BeginGetContext(ContextCallback, null); _port = port; Console.WriteLine($"Http service at url: {_listener.Prefixes.First()}"); return FlowErrorCode.Success; } public void Stop() { if (_listener == null) { return; } _listener.Stop(); _listener = null; _port = 0; } protected virtual void Http404NotFoundHandler(HttpListenerContext context, string path, string query) { context.Response.StatusCode = 404; var responseString = "<HTML><BODY>404 Not Found.</BODY></HTML>"; WriteAndCloseResponse(responseString, context); } public static string MIMETypeFromFileExtension(string ext) { switch (ext) { case ".avi": return "video/x-msvideo"; case ".css": return "text/css"; case ".doc": return "application/msword"; case ".gif": return "image/gif"; case ".htm": case ".html": return "text/html"; case ".jpg": case ".jpeg": return "image/jpeg"; case ".js": return "application/x-javascript"; case ".mp3": return "audio/mpeg"; case ".png": return "image/png"; case ".pdf": return "application/pdf"; case ".ppt": return "application/vnd.ms-powerpoint"; case ".zip": return "application/zip"; case ".json": case ".ini": case ".thrift": case ".cs": case ".h": case ".cpp": case ".cc": case ".java": case ".php": case ".txt": return "text/plain"; default: return "application/octet-stream"; } } protected virtual void StaticFileHandler(string virtualPath, string localRoot, HttpListenerContext context, string subpath, string query) { if (query.Length > 0) { Trace.TraceWarning($"static file download does not support queries: {subpath}?{query}"); } var localPath = (localRoot + subpath).Replace('/', '\\').Replace("\\\\", "\\"); // TODO: cache service if (File.Exists(localPath)) { context.Response.ContentType = MIMETypeFromFileExtension(Path.GetExtension(localPath)); using (var fileStream = File.OpenRead(localPath)) { context.Response.ContentLength64 = fileStream.Length; fileStream.CopyTo(context.Response.OutputStream); } context.Response.OutputStream.Close(); } else if (Directory.Exists(localPath)) { context.Response.ContentType = "text/html"; var responseString = ListAllInDirectory(virtualPath, subpath, localPath); WriteAndCloseResponse(responseString, context); } // File not found else { context.Response.ContentType = "text/html"; Http404NotFoundHandler(context, subpath, query); } } protected string ListAllInDirectory(string virtualPath, string subPath, string localDir) { var logicalDir = (virtualPath + "/" + subPath).Replace('\\', '/').Replace("//", "/"); if (logicalDir.Last() != '/') logicalDir += "/"; var builder = new CodeBuilder(); builder.AppendLine("<html>"); builder.AppendLine("<title>" + logicalDir + "</title>"); builder.AppendLine("<body>"); builder.AppendLine("<h2>" + logicalDir + "</h2><hr>"); if (subPath.Length > 0) { builder.AppendLine("<a href=\"" + logicalDir + "../\">..</a><br>"); } foreach (var subdir in Directory.GetDirectories(localDir)) { var dirname = Path.GetFileName(subdir); builder.AppendLine("<a href=\"" + logicalDir + dirname + "/\">" + dirname + "</a><br>"); } foreach (var file in Directory.GetFiles(localDir)) { var fileName = Path.GetFileName(file); builder.AppendLine("<a href=\"" + logicalDir + fileName + "\">" + fileName + "</a><br>"); } builder.AppendLine("</body>"); builder.AppendLine("</html>"); return builder.ToString(); } protected virtual void WebApiCallback(WebApiRequestHandler apiHandler, HttpListenerContext context, string subpath, string query) { context.Response.ContentType = "text/plain"; var requestStr = ""; var request = context.Request; if (request.HasEntityBody) { using (var body = request.InputStream) // here we have data { using (var reader = new StreamReader(body, request.ContentEncoding)) { requestStr = reader.ReadToEnd(); } } } WriteAndCloseResponse(apiHandler(subpath, query, requestStr), context); } private void WriteAndCloseResponse(string response, HttpListenerContext context) { context.Response.ContentEncoding = Encoding.UTF8; var buffer = Encoding.UTF8.GetBytes(response); context.Response.ContentLength64 = buffer.Length; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Close(); } private void ContextCallback(IAsyncResult result) { var context = _listener.EndGetContext(result); // continue next request _listener.BeginGetContext(ContextCallback, null); try { Trace.WriteLine(context.Request.HttpMethod + " '" + context.Request.RawUrl + "' from " + context.Request.RemoteEndPoint + " using " + context.Request.UserAgent + ""); context.Response.KeepAlive = true; // deal with current request var path = context.Request.RawUrl; var query = ""; var queryStart = path.IndexOf('?'); if (queryStart > 0) { path = path.Substring(0, queryStart); if (queryStart < path.Length - 1) { query = path.Substring(queryStart + 1); } } string prefix; var handler = GetHandler(path, out prefix); Trace.Assert(null != handler); path = path.Substring(prefix.Length); handler(context, path, query); } catch (Exception e) { Trace.TraceError("HttpContextCallback throws exception = " + e + ", StackTrace = " + e.StackTrace); } } private void RegisterHandler(string prefix, HttpRequestHandler handler) { _handlers.Add(prefix.ToLower(), handler); } private HttpRequestHandler GetHandler(string path, out string oprefix) { var matchCount = -1; var matchIndex = -1; var max = _sortedHandlerArrary.Length; oprefix = ""; path = path.ToLower(); for (var i = 0; i < max; i++) { var prefix = _sortedHandlerArrary[i].Key; var localMatchCount = 0; for (var j = 0; j < prefix.Length && j < path.Length; j++) { if (prefix[j] == path[j]) { localMatchCount = j + 1; } else break; } // continue if if (localMatchCount >= matchCount) { matchCount = localMatchCount; if (localMatchCount == prefix.Length) { matchIndex = i; oprefix = prefix; } } // break else { break; } } if (matchIndex != -1) { return _sortedHandlerArrary[matchIndex].Value; } oprefix = "NotFound"; return Http404NotFoundHandler; } protected delegate void HttpRequestHandler(HttpListenerContext context, string subpath, string query); private int _port; private HttpListener _listener; private SortedDictionary<string, HttpRequestHandler> _handlers = new SortedDictionary<string, HttpRequestHandler>(); private KeyValuePair<string, HttpRequestHandler>[] _sortedHandlerArrary; } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; #if HAVE_BIG_INTEGER using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. /// </summary> public abstract partial class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// A <see cref="JsonReader"/> read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The <see cref="JsonReader.Close()"/> method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader is in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState => _currentState; /// <summary> /// Gets or sets a value indicating whether the source should be closed when this reader is closed. /// </summary> /// <value> /// <c>true</c> to close the source when this reader is closed; otherwise <c>false</c>. The default is <c>true</c>. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// <c>true</c> to support reading multiple pieces of JSON content; otherwise <c>false</c>. /// The default is <c>false</c>. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get => _quoteChar; protected internal set => _quoteChar = value; } /// <summary> /// Gets or sets how <see cref="DateTime"/> time zones are handled when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get => _dateTimeZoneHandling; set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateTimeZoneHandling = value; } } /// <summary> /// Gets or sets how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get => _dateParseHandling; set { if (value < DateParseHandling.None || #if HAVE_DATE_TIME_OFFSET value > DateParseHandling.DateTimeOffset #else value > DateParseHandling.DateTime #endif ) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateParseHandling = value; } } /// <summary> /// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get => _floatParseHandling; set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException(nameof(value)); } _floatParseHandling = value; } } /// <summary> /// Gets or sets how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get => _dateFormatString; set => _dateFormatString = value; } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get => _maxDepth; set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType => _tokenType; /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value => _value; /// <summary> /// Gets the .NET type for the current JSON token. /// </summary> public virtual Type ValueType => _value?.GetType(); /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return depth; } else { return depth + 1; } } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get => _culture ?? CultureInfo.InvariantCulture; set => _culture = value; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class. /// </summary> protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack != null && _stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the source. /// </summary> /// <returns><c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Int32"/>. /// </summary> /// <returns>A <see cref="Nullable{T}"/> of <see cref="Int32"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual int? ReadAsInt32() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: object v = Value; if (v is int i) { return i; } #if HAVE_BIG_INTEGER if (v is BigInteger value) { i = (int)value; } else #endif { try { i = Convert.ToInt32(v, CultureInfo.InvariantCulture); } catch (Exception ex) { // handle error for large integer overflow exceptions throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex); } } SetToken(JsonToken.Integer, i, false); return i; case JsonToken.String: string s = (string)Value; return ReadInt32String(s); } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadInt32String(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out int i)) { SetToken(JsonToken.Integer, i, false); return i; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the source as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual string ReadAsString() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; } if (JsonTokenUtils.IsPrimitiveToken(t)) { object v = Value; if (v != null) { string s; if (v is IFormattable formattable) { s = formattable.ToString(null, Culture); } else { s = v is Uri uri ? uri.OriginalString : v.ToString(); } SetToken(JsonToken.String, s, false); return s; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } /// <summary> /// Reads the next JSON token from the source as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public virtual byte[] ReadAsBytes() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] data = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, data, false); return data; } case JsonToken.String: { // attempt to convert possible base 64 or GUID string to bytes // GUID has to have format 00000000-0000-0000-0000-000000000000 string s = (string)Value; byte[] data; if (s.Length == 0) { data = CollectionUtils.ArrayEmpty<byte>(); } else if (ConvertUtils.TryConvertGuid(s, out Guid g1)) { data = g1.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid g2) { byte[] data = g2.ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal byte[] ReadArrayIntoByteArray() { List<byte> buffer = new List<byte>(); while (true) { if (!Read()) { SetToken(JsonToken.None); } if (ReadArrayElementIntoByteArrayReportDone(buffer)) { byte[] d = buffer.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; } } } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } /// <summary> /// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Double"/>. /// </summary> /// <returns>A <see cref="Nullable{T}"/> of <see cref="Double"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual double? ReadAsDouble() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: object v = Value; if (v is double d) { return d; } #if HAVE_BIG_INTEGER if (v is BigInteger value) { d = (double)value; } else #endif { d = Convert.ToDouble(v, CultureInfo.InvariantCulture); } SetToken(JsonToken.Float, d, false); return (double)d; case JsonToken.String: return ReadDoubleString((string)Value); } throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal double? ReadDoubleString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out double d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Boolean"/>. /// </summary> /// <returns>A <see cref="Nullable{T}"/> of <see cref="Boolean"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual bool? ReadAsBoolean() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: bool b; #if HAVE_BIG_INTEGER if (Value is BigInteger integer) { b = integer != 0; } else #endif { b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Boolean, b, false); return b; case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal bool? ReadBooleanString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } if (bool.TryParse(s, out bool b)) { SetToken(JsonToken.Boolean, b, false); return b; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Decimal"/>. /// </summary> /// <returns>A <see cref="Nullable{T}"/> of <see cref="Decimal"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual decimal? ReadAsDecimal() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: object v = Value; if (v is decimal d) { return d; } #if HAVE_BIG_INTEGER if (v is BigInteger value) { d = (decimal)value; } else #endif { try { d = Convert.ToDecimal(v, CultureInfo.InvariantCulture); } catch (Exception ex) { // handle error for large integer overflow exceptions throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex); } } SetToken(JsonToken.Float, d, false); return d; case JsonToken.String: return ReadDecimalString((string)Value); } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadDecimalString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out decimal d)) { SetToken(JsonToken.Float, d, false); return d; } else if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out d) == ParseResult.Success) { // This is to handle strings like "96.014e-05" that are not supported by traditional decimal.TryParse SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>. /// </summary> /// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: #if HAVE_DATE_TIME_OFFSET if (Value is DateTimeOffset offset) { SetToken(JsonToken.Date, offset.DateTime, false); } #endif return (DateTime)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeString(s); } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal DateTime? ReadDateTimeString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out DateTime dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. /// </summary> /// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime time) { SetToken(JsonToken.Date, new DateTimeOffset(time), false); } return (DateTimeOffset)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeOffsetString(s); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out DateTimeOffset dt)) { SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #endif internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> /// <param name="updateIndex">A flag indicating whether the position index inside an array should be updated.</param> protected void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); } if (Peek() != JsonContainerType.None || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { _currentState = SupportMultipleContent ? State.Start : State.Finished; } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } /// <summary> /// Changes the reader's state to <see cref="JsonReader.State.Closed"/>. /// If <see cref="JsonReader.CloseInput"/> is set to <c>true</c>, the source is also closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract contract, bool hasConverter) { // don't read properties with converters as a specific value // the value might be a string which will then get converted which will error if read as date for example if (hasConverter) { return Read(); } ReadType t = contract?.InternalReadType ?? ReadType.Read; switch (t) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; #if HAVE_DATE_TIME_OFFSET case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; #endif default: throw new ArgumentOutOfRangeException(); } return (TokenType != JsonToken.None); } internal bool ReadAndMoveToContent() { return Read() && MoveToContent(); } internal bool MoveToContent() { JsonToken t = TokenType; while (t == JsonToken.None || t == JsonToken.Comment) { if (!Read()) { return false; } t = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken t; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } else { t = TokenType; } } while (t == JsonToken.Comment); return t; } } }
// 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 gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Iap.V1 { /// <summary>Settings for <see cref="IdentityAwareProxyOAuthServiceClient"/> instances.</summary> public sealed partial class IdentityAwareProxyOAuthServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="IdentityAwareProxyOAuthServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="IdentityAwareProxyOAuthServiceSettings"/>.</returns> public static IdentityAwareProxyOAuthServiceSettings GetDefault() => new IdentityAwareProxyOAuthServiceSettings(); /// <summary> /// Constructs a new <see cref="IdentityAwareProxyOAuthServiceSettings"/> object with default settings. /// </summary> public IdentityAwareProxyOAuthServiceSettings() { } private IdentityAwareProxyOAuthServiceSettings(IdentityAwareProxyOAuthServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListBrandsSettings = existing.ListBrandsSettings; CreateBrandSettings = existing.CreateBrandSettings; GetBrandSettings = existing.GetBrandSettings; CreateIdentityAwareProxyClientSettings = existing.CreateIdentityAwareProxyClientSettings; ListIdentityAwareProxyClientsSettings = existing.ListIdentityAwareProxyClientsSettings; GetIdentityAwareProxyClientSettings = existing.GetIdentityAwareProxyClientSettings; ResetIdentityAwareProxyClientSecretSettings = existing.ResetIdentityAwareProxyClientSecretSettings; DeleteIdentityAwareProxyClientSettings = existing.DeleteIdentityAwareProxyClientSettings; OnCopy(existing); } partial void OnCopy(IdentityAwareProxyOAuthServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.ListBrands</c> and /// <c>IdentityAwareProxyOAuthServiceClient.ListBrandsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListBrandsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.CreateBrand</c> and /// <c>IdentityAwareProxyOAuthServiceClient.CreateBrandAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateBrandSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.GetBrand</c> and /// <c>IdentityAwareProxyOAuthServiceClient.GetBrandAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetBrandSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.CreateIdentityAwareProxyClient</c> and /// <c>IdentityAwareProxyOAuthServiceClient.CreateIdentityAwareProxyClientAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateIdentityAwareProxyClientSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.ListIdentityAwareProxyClients</c> and /// <c>IdentityAwareProxyOAuthServiceClient.ListIdentityAwareProxyClientsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListIdentityAwareProxyClientsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.GetIdentityAwareProxyClient</c> and /// <c>IdentityAwareProxyOAuthServiceClient.GetIdentityAwareProxyClientAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetIdentityAwareProxyClientSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.ResetIdentityAwareProxyClientSecret</c> and /// <c>IdentityAwareProxyOAuthServiceClient.ResetIdentityAwareProxyClientSecretAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ResetIdentityAwareProxyClientSecretSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>IdentityAwareProxyOAuthServiceClient.DeleteIdentityAwareProxyClient</c> and /// <c>IdentityAwareProxyOAuthServiceClient.DeleteIdentityAwareProxyClientAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteIdentityAwareProxyClientSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="IdentityAwareProxyOAuthServiceSettings"/> object.</returns> public IdentityAwareProxyOAuthServiceSettings Clone() => new IdentityAwareProxyOAuthServiceSettings(this); } /// <summary> /// Builder class for <see cref="IdentityAwareProxyOAuthServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> public sealed partial class IdentityAwareProxyOAuthServiceClientBuilder : gaxgrpc::ClientBuilderBase<IdentityAwareProxyOAuthServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public IdentityAwareProxyOAuthServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public IdentityAwareProxyOAuthServiceClientBuilder() { UseJwtAccessWithScopes = IdentityAwareProxyOAuthServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref IdentityAwareProxyOAuthServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<IdentityAwareProxyOAuthServiceClient> task); /// <summary>Builds the resulting client.</summary> public override IdentityAwareProxyOAuthServiceClient Build() { IdentityAwareProxyOAuthServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<IdentityAwareProxyOAuthServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<IdentityAwareProxyOAuthServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private IdentityAwareProxyOAuthServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return IdentityAwareProxyOAuthServiceClient.Create(callInvoker, Settings); } private async stt::Task<IdentityAwareProxyOAuthServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return IdentityAwareProxyOAuthServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => IdentityAwareProxyOAuthServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => IdentityAwareProxyOAuthServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => IdentityAwareProxyOAuthServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>IdentityAwareProxyOAuthService client wrapper, for convenient use.</summary> /// <remarks> /// API to programmatically create, list and retrieve Identity Aware Proxy (IAP) /// OAuth brands; and create, retrieve, delete and reset-secret of IAP OAuth /// clients. /// </remarks> public abstract partial class IdentityAwareProxyOAuthServiceClient { /// <summary> /// The default endpoint for the IdentityAwareProxyOAuthService service, which is a host of "iap.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "iap.googleapis.com:443"; /// <summary>The default IdentityAwareProxyOAuthService scopes.</summary> /// <remarks> /// The default IdentityAwareProxyOAuthService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="IdentityAwareProxyOAuthServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="IdentityAwareProxyOAuthServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="IdentityAwareProxyOAuthServiceClient"/>.</returns> public static stt::Task<IdentityAwareProxyOAuthServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new IdentityAwareProxyOAuthServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="IdentityAwareProxyOAuthServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="IdentityAwareProxyOAuthServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="IdentityAwareProxyOAuthServiceClient"/>.</returns> public static IdentityAwareProxyOAuthServiceClient Create() => new IdentityAwareProxyOAuthServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="IdentityAwareProxyOAuthServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="IdentityAwareProxyOAuthServiceSettings"/>.</param> /// <returns>The created <see cref="IdentityAwareProxyOAuthServiceClient"/>.</returns> internal static IdentityAwareProxyOAuthServiceClient Create(grpccore::CallInvoker callInvoker, IdentityAwareProxyOAuthServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } IdentityAwareProxyOAuthService.IdentityAwareProxyOAuthServiceClient grpcClient = new IdentityAwareProxyOAuthService.IdentityAwareProxyOAuthServiceClient(callInvoker); return new IdentityAwareProxyOAuthServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC IdentityAwareProxyOAuthService client</summary> public virtual IdentityAwareProxyOAuthService.IdentityAwareProxyOAuthServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Lists the existing brands for the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListBrandsResponse ListBrands(ListBrandsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the existing brands for the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListBrandsResponse> ListBrandsAsync(ListBrandsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the existing brands for the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListBrandsResponse> ListBrandsAsync(ListBrandsRequest request, st::CancellationToken cancellationToken) => ListBrandsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Constructs a new OAuth brand for the project if one does not exist. /// The created brand is "internal only", meaning that OAuth clients created /// under it only accept requests from users who belong to the same G Suite /// organization as the project. The brand is created in an un-reviewed status. /// NOTE: The "internal only" status can be manually changed in the Google /// Cloud console. Requires that a brand does not already exist for the /// project, and that the specified support email is owned by the caller. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Brand CreateBrand(CreateBrandRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Constructs a new OAuth brand for the project if one does not exist. /// The created brand is "internal only", meaning that OAuth clients created /// under it only accept requests from users who belong to the same G Suite /// organization as the project. The brand is created in an un-reviewed status. /// NOTE: The "internal only" status can be manually changed in the Google /// Cloud console. Requires that a brand does not already exist for the /// project, and that the specified support email is owned by the caller. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Brand> CreateBrandAsync(CreateBrandRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Constructs a new OAuth brand for the project if one does not exist. /// The created brand is "internal only", meaning that OAuth clients created /// under it only accept requests from users who belong to the same G Suite /// organization as the project. The brand is created in an un-reviewed status. /// NOTE: The "internal only" status can be manually changed in the Google /// Cloud console. Requires that a brand does not already exist for the /// project, and that the specified support email is owned by the caller. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Brand> CreateBrandAsync(CreateBrandRequest request, st::CancellationToken cancellationToken) => CreateBrandAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Retrieves the OAuth brand of the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Brand GetBrand(GetBrandRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the OAuth brand of the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Brand> GetBrandAsync(GetBrandRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves the OAuth brand of the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Brand> GetBrandAsync(GetBrandRequest request, st::CancellationToken cancellationToken) => GetBrandAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates an Identity Aware Proxy (IAP) OAuth client. The client is owned /// by IAP. Requires that the brand for the project exists and that it is /// set for internal-only use. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual IdentityAwareProxyClient CreateIdentityAwareProxyClient(CreateIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an Identity Aware Proxy (IAP) OAuth client. The client is owned /// by IAP. Requires that the brand for the project exists and that it is /// set for internal-only use. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<IdentityAwareProxyClient> CreateIdentityAwareProxyClientAsync(CreateIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an Identity Aware Proxy (IAP) OAuth client. The client is owned /// by IAP. Requires that the brand for the project exists and that it is /// set for internal-only use. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<IdentityAwareProxyClient> CreateIdentityAwareProxyClientAsync(CreateIdentityAwareProxyClientRequest request, st::CancellationToken cancellationToken) => CreateIdentityAwareProxyClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Lists the existing clients for the brand. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="IdentityAwareProxyClient"/> resources.</returns> public virtual gax::PagedEnumerable<ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient> ListIdentityAwareProxyClients(ListIdentityAwareProxyClientsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the existing clients for the brand. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="IdentityAwareProxyClient"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient> ListIdentityAwareProxyClientsAsync(ListIdentityAwareProxyClientsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an Identity Aware Proxy (IAP) OAuth client. /// Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual IdentityAwareProxyClient GetIdentityAwareProxyClient(GetIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an Identity Aware Proxy (IAP) OAuth client. /// Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<IdentityAwareProxyClient> GetIdentityAwareProxyClientAsync(GetIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Retrieves an Identity Aware Proxy (IAP) OAuth client. /// Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<IdentityAwareProxyClient> GetIdentityAwareProxyClientAsync(GetIdentityAwareProxyClientRequest request, st::CancellationToken cancellationToken) => GetIdentityAwareProxyClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Resets an Identity Aware Proxy (IAP) OAuth client secret. Useful if the /// secret was compromised. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual IdentityAwareProxyClient ResetIdentityAwareProxyClientSecret(ResetIdentityAwareProxyClientSecretRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Resets an Identity Aware Proxy (IAP) OAuth client secret. Useful if the /// secret was compromised. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<IdentityAwareProxyClient> ResetIdentityAwareProxyClientSecretAsync(ResetIdentityAwareProxyClientSecretRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Resets an Identity Aware Proxy (IAP) OAuth client secret. Useful if the /// secret was compromised. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<IdentityAwareProxyClient> ResetIdentityAwareProxyClientSecretAsync(ResetIdentityAwareProxyClientSecretRequest request, st::CancellationToken cancellationToken) => ResetIdentityAwareProxyClientSecretAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes an Identity Aware Proxy (IAP) OAuth client. Useful for removing /// obsolete clients, managing the number of clients in a given project, and /// cleaning up after tests. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteIdentityAwareProxyClient(DeleteIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes an Identity Aware Proxy (IAP) OAuth client. Useful for removing /// obsolete clients, managing the number of clients in a given project, and /// cleaning up after tests. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteIdentityAwareProxyClientAsync(DeleteIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes an Identity Aware Proxy (IAP) OAuth client. Useful for removing /// obsolete clients, managing the number of clients in a given project, and /// cleaning up after tests. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteIdentityAwareProxyClientAsync(DeleteIdentityAwareProxyClientRequest request, st::CancellationToken cancellationToken) => DeleteIdentityAwareProxyClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>IdentityAwareProxyOAuthService client wrapper implementation, for convenient use.</summary> /// <remarks> /// API to programmatically create, list and retrieve Identity Aware Proxy (IAP) /// OAuth brands; and create, retrieve, delete and reset-secret of IAP OAuth /// clients. /// </remarks> public sealed partial class IdentityAwareProxyOAuthServiceClientImpl : IdentityAwareProxyOAuthServiceClient { private readonly gaxgrpc::ApiCall<ListBrandsRequest, ListBrandsResponse> _callListBrands; private readonly gaxgrpc::ApiCall<CreateBrandRequest, Brand> _callCreateBrand; private readonly gaxgrpc::ApiCall<GetBrandRequest, Brand> _callGetBrand; private readonly gaxgrpc::ApiCall<CreateIdentityAwareProxyClientRequest, IdentityAwareProxyClient> _callCreateIdentityAwareProxyClient; private readonly gaxgrpc::ApiCall<ListIdentityAwareProxyClientsRequest, ListIdentityAwareProxyClientsResponse> _callListIdentityAwareProxyClients; private readonly gaxgrpc::ApiCall<GetIdentityAwareProxyClientRequest, IdentityAwareProxyClient> _callGetIdentityAwareProxyClient; private readonly gaxgrpc::ApiCall<ResetIdentityAwareProxyClientSecretRequest, IdentityAwareProxyClient> _callResetIdentityAwareProxyClientSecret; private readonly gaxgrpc::ApiCall<DeleteIdentityAwareProxyClientRequest, wkt::Empty> _callDeleteIdentityAwareProxyClient; /// <summary> /// Constructs a client wrapper for the IdentityAwareProxyOAuthService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="IdentityAwareProxyOAuthServiceSettings"/> used within this client. /// </param> public IdentityAwareProxyOAuthServiceClientImpl(IdentityAwareProxyOAuthService.IdentityAwareProxyOAuthServiceClient grpcClient, IdentityAwareProxyOAuthServiceSettings settings) { GrpcClient = grpcClient; IdentityAwareProxyOAuthServiceSettings effectiveSettings = settings ?? IdentityAwareProxyOAuthServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListBrands = clientHelper.BuildApiCall<ListBrandsRequest, ListBrandsResponse>(grpcClient.ListBrandsAsync, grpcClient.ListBrands, effectiveSettings.ListBrandsSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListBrands); Modify_ListBrandsApiCall(ref _callListBrands); _callCreateBrand = clientHelper.BuildApiCall<CreateBrandRequest, Brand>(grpcClient.CreateBrandAsync, grpcClient.CreateBrand, effectiveSettings.CreateBrandSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateBrand); Modify_CreateBrandApiCall(ref _callCreateBrand); _callGetBrand = clientHelper.BuildApiCall<GetBrandRequest, Brand>(grpcClient.GetBrandAsync, grpcClient.GetBrand, effectiveSettings.GetBrandSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetBrand); Modify_GetBrandApiCall(ref _callGetBrand); _callCreateIdentityAwareProxyClient = clientHelper.BuildApiCall<CreateIdentityAwareProxyClientRequest, IdentityAwareProxyClient>(grpcClient.CreateIdentityAwareProxyClientAsync, grpcClient.CreateIdentityAwareProxyClient, effectiveSettings.CreateIdentityAwareProxyClientSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateIdentityAwareProxyClient); Modify_CreateIdentityAwareProxyClientApiCall(ref _callCreateIdentityAwareProxyClient); _callListIdentityAwareProxyClients = clientHelper.BuildApiCall<ListIdentityAwareProxyClientsRequest, ListIdentityAwareProxyClientsResponse>(grpcClient.ListIdentityAwareProxyClientsAsync, grpcClient.ListIdentityAwareProxyClients, effectiveSettings.ListIdentityAwareProxyClientsSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListIdentityAwareProxyClients); Modify_ListIdentityAwareProxyClientsApiCall(ref _callListIdentityAwareProxyClients); _callGetIdentityAwareProxyClient = clientHelper.BuildApiCall<GetIdentityAwareProxyClientRequest, IdentityAwareProxyClient>(grpcClient.GetIdentityAwareProxyClientAsync, grpcClient.GetIdentityAwareProxyClient, effectiveSettings.GetIdentityAwareProxyClientSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetIdentityAwareProxyClient); Modify_GetIdentityAwareProxyClientApiCall(ref _callGetIdentityAwareProxyClient); _callResetIdentityAwareProxyClientSecret = clientHelper.BuildApiCall<ResetIdentityAwareProxyClientSecretRequest, IdentityAwareProxyClient>(grpcClient.ResetIdentityAwareProxyClientSecretAsync, grpcClient.ResetIdentityAwareProxyClientSecret, effectiveSettings.ResetIdentityAwareProxyClientSecretSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callResetIdentityAwareProxyClientSecret); Modify_ResetIdentityAwareProxyClientSecretApiCall(ref _callResetIdentityAwareProxyClientSecret); _callDeleteIdentityAwareProxyClient = clientHelper.BuildApiCall<DeleteIdentityAwareProxyClientRequest, wkt::Empty>(grpcClient.DeleteIdentityAwareProxyClientAsync, grpcClient.DeleteIdentityAwareProxyClient, effectiveSettings.DeleteIdentityAwareProxyClientSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteIdentityAwareProxyClient); Modify_DeleteIdentityAwareProxyClientApiCall(ref _callDeleteIdentityAwareProxyClient); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListBrandsApiCall(ref gaxgrpc::ApiCall<ListBrandsRequest, ListBrandsResponse> call); partial void Modify_CreateBrandApiCall(ref gaxgrpc::ApiCall<CreateBrandRequest, Brand> call); partial void Modify_GetBrandApiCall(ref gaxgrpc::ApiCall<GetBrandRequest, Brand> call); partial void Modify_CreateIdentityAwareProxyClientApiCall(ref gaxgrpc::ApiCall<CreateIdentityAwareProxyClientRequest, IdentityAwareProxyClient> call); partial void Modify_ListIdentityAwareProxyClientsApiCall(ref gaxgrpc::ApiCall<ListIdentityAwareProxyClientsRequest, ListIdentityAwareProxyClientsResponse> call); partial void Modify_GetIdentityAwareProxyClientApiCall(ref gaxgrpc::ApiCall<GetIdentityAwareProxyClientRequest, IdentityAwareProxyClient> call); partial void Modify_ResetIdentityAwareProxyClientSecretApiCall(ref gaxgrpc::ApiCall<ResetIdentityAwareProxyClientSecretRequest, IdentityAwareProxyClient> call); partial void Modify_DeleteIdentityAwareProxyClientApiCall(ref gaxgrpc::ApiCall<DeleteIdentityAwareProxyClientRequest, wkt::Empty> call); partial void OnConstruction(IdentityAwareProxyOAuthService.IdentityAwareProxyOAuthServiceClient grpcClient, IdentityAwareProxyOAuthServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC IdentityAwareProxyOAuthService client</summary> public override IdentityAwareProxyOAuthService.IdentityAwareProxyOAuthServiceClient GrpcClient { get; } partial void Modify_ListBrandsRequest(ref ListBrandsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateBrandRequest(ref CreateBrandRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetBrandRequest(ref GetBrandRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateIdentityAwareProxyClientRequest(ref CreateIdentityAwareProxyClientRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListIdentityAwareProxyClientsRequest(ref ListIdentityAwareProxyClientsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetIdentityAwareProxyClientRequest(ref GetIdentityAwareProxyClientRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ResetIdentityAwareProxyClientSecretRequest(ref ResetIdentityAwareProxyClientSecretRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteIdentityAwareProxyClientRequest(ref DeleteIdentityAwareProxyClientRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Lists the existing brands for the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ListBrandsResponse ListBrands(ListBrandsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListBrandsRequest(ref request, ref callSettings); return _callListBrands.Sync(request, callSettings); } /// <summary> /// Lists the existing brands for the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ListBrandsResponse> ListBrandsAsync(ListBrandsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListBrandsRequest(ref request, ref callSettings); return _callListBrands.Async(request, callSettings); } /// <summary> /// Constructs a new OAuth brand for the project if one does not exist. /// The created brand is "internal only", meaning that OAuth clients created /// under it only accept requests from users who belong to the same G Suite /// organization as the project. The brand is created in an un-reviewed status. /// NOTE: The "internal only" status can be manually changed in the Google /// Cloud console. Requires that a brand does not already exist for the /// project, and that the specified support email is owned by the caller. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Brand CreateBrand(CreateBrandRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateBrandRequest(ref request, ref callSettings); return _callCreateBrand.Sync(request, callSettings); } /// <summary> /// Constructs a new OAuth brand for the project if one does not exist. /// The created brand is "internal only", meaning that OAuth clients created /// under it only accept requests from users who belong to the same G Suite /// organization as the project. The brand is created in an un-reviewed status. /// NOTE: The "internal only" status can be manually changed in the Google /// Cloud console. Requires that a brand does not already exist for the /// project, and that the specified support email is owned by the caller. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Brand> CreateBrandAsync(CreateBrandRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateBrandRequest(ref request, ref callSettings); return _callCreateBrand.Async(request, callSettings); } /// <summary> /// Retrieves the OAuth brand of the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Brand GetBrand(GetBrandRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBrandRequest(ref request, ref callSettings); return _callGetBrand.Sync(request, callSettings); } /// <summary> /// Retrieves the OAuth brand of the project. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Brand> GetBrandAsync(GetBrandRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBrandRequest(ref request, ref callSettings); return _callGetBrand.Async(request, callSettings); } /// <summary> /// Creates an Identity Aware Proxy (IAP) OAuth client. The client is owned /// by IAP. Requires that the brand for the project exists and that it is /// set for internal-only use. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override IdentityAwareProxyClient CreateIdentityAwareProxyClient(CreateIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateIdentityAwareProxyClientRequest(ref request, ref callSettings); return _callCreateIdentityAwareProxyClient.Sync(request, callSettings); } /// <summary> /// Creates an Identity Aware Proxy (IAP) OAuth client. The client is owned /// by IAP. Requires that the brand for the project exists and that it is /// set for internal-only use. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<IdentityAwareProxyClient> CreateIdentityAwareProxyClientAsync(CreateIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateIdentityAwareProxyClientRequest(ref request, ref callSettings); return _callCreateIdentityAwareProxyClient.Async(request, callSettings); } /// <summary> /// Lists the existing clients for the brand. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="IdentityAwareProxyClient"/> resources.</returns> public override gax::PagedEnumerable<ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient> ListIdentityAwareProxyClients(ListIdentityAwareProxyClientsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListIdentityAwareProxyClientsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListIdentityAwareProxyClientsRequest, ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient>(_callListIdentityAwareProxyClients, request, callSettings); } /// <summary> /// Lists the existing clients for the brand. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="IdentityAwareProxyClient"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient> ListIdentityAwareProxyClientsAsync(ListIdentityAwareProxyClientsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListIdentityAwareProxyClientsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListIdentityAwareProxyClientsRequest, ListIdentityAwareProxyClientsResponse, IdentityAwareProxyClient>(_callListIdentityAwareProxyClients, request, callSettings); } /// <summary> /// Retrieves an Identity Aware Proxy (IAP) OAuth client. /// Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override IdentityAwareProxyClient GetIdentityAwareProxyClient(GetIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetIdentityAwareProxyClientRequest(ref request, ref callSettings); return _callGetIdentityAwareProxyClient.Sync(request, callSettings); } /// <summary> /// Retrieves an Identity Aware Proxy (IAP) OAuth client. /// Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<IdentityAwareProxyClient> GetIdentityAwareProxyClientAsync(GetIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetIdentityAwareProxyClientRequest(ref request, ref callSettings); return _callGetIdentityAwareProxyClient.Async(request, callSettings); } /// <summary> /// Resets an Identity Aware Proxy (IAP) OAuth client secret. Useful if the /// secret was compromised. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override IdentityAwareProxyClient ResetIdentityAwareProxyClientSecret(ResetIdentityAwareProxyClientSecretRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ResetIdentityAwareProxyClientSecretRequest(ref request, ref callSettings); return _callResetIdentityAwareProxyClientSecret.Sync(request, callSettings); } /// <summary> /// Resets an Identity Aware Proxy (IAP) OAuth client secret. Useful if the /// secret was compromised. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<IdentityAwareProxyClient> ResetIdentityAwareProxyClientSecretAsync(ResetIdentityAwareProxyClientSecretRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ResetIdentityAwareProxyClientSecretRequest(ref request, ref callSettings); return _callResetIdentityAwareProxyClientSecret.Async(request, callSettings); } /// <summary> /// Deletes an Identity Aware Proxy (IAP) OAuth client. Useful for removing /// obsolete clients, managing the number of clients in a given project, and /// cleaning up after tests. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override void DeleteIdentityAwareProxyClient(DeleteIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteIdentityAwareProxyClientRequest(ref request, ref callSettings); _callDeleteIdentityAwareProxyClient.Sync(request, callSettings); } /// <summary> /// Deletes an Identity Aware Proxy (IAP) OAuth client. Useful for removing /// obsolete clients, managing the number of clients in a given project, and /// cleaning up after tests. Requires that the client is owned by IAP. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task DeleteIdentityAwareProxyClientAsync(DeleteIdentityAwareProxyClientRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteIdentityAwareProxyClientRequest(ref request, ref callSettings); return _callDeleteIdentityAwareProxyClient.Async(request, callSettings); } } public partial class ListIdentityAwareProxyClientsRequest : gaxgrpc::IPageRequest { } public partial class ListIdentityAwareProxyClientsResponse : gaxgrpc::IPageResponse<IdentityAwareProxyClient> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<IdentityAwareProxyClient> GetEnumerator() => IdentityAwareProxyClients.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
#region Licence... //----------------------------------------------------------------------------- // Date: 17/10/04 Time: 2:33p // Module: GACHelper.cs // Classes: COM // InstallReference // InstallReferenceGuid // AssemblyCache // AssemblyEnum // // This module contains the definition of the GAC helper classes. // // Written by Oleg Shilo ([email protected]). Based on work by Junfeng Zhang // (Simple wrapper for GAC). // // Written by Oleg Shilo ([email protected]) // Copyright (c) 2004-2012. All rights reserved. // // Redistribution and use of this code WITHOUT MODIFICATIONS are permitted provided that // the following conditions are met: // 1. Redistributions must retain the above copyright notice, this list of conditions // and the following disclaimer. // 2. Neither the name of an author nor the names of the contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // Redistribution and use of this code WITH MODIFICATIONS are permitted provided that all // above conditions are met and software is not used or sold for profit. // // // 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. // // Caution: Bugs are expected! //---------------------------------------------- #endregion Licence... using System; using System.Runtime.InteropServices; using System.Text; /* * PSS ID Number: Q317540 * * Use the GAC API in the following scenarios: * When you install an assembly to the GAC. * When you remove an assembly from the GAC. * When you export an assembly from the GAC. * When you enumerate assemblies that are available in the GAC. * */ //#pragma warning disable 414 namespace csscript { /// <summary> /// COM HR checker: just to make code more compact; /// </summary> class COM { static public void CheckHR(int hr) { if (hr < 0) Marshal.ThrowExceptionForHR(hr); } } /// <summary> /// IAssemblyCache; COM import /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")] internal interface IAssemblyCache { //PreserveSig() Indicates that the HRESULT or retval signature transformation that takes place during COM interop calls should be suppressed [PreserveSig()] int UninstallAssembly(int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName, InstallReference refData, out AssemblyCacheUninstallDisposition disposition); [PreserveSig()] int QueryAssemblyInfo(int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName, ref AssemblyInfo assemblyInfo); [PreserveSig()] int Reserved(int flags, IntPtr pvReserved, out Object ppAsmItem, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName); [PreserveSig()] int Reserved(out Object ppAsmScavenger); [PreserveSig()] int InstallAssembly(int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyFilePath, InstallReference refData); } /// <summary> /// IAssemblyName; COM import /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] internal interface IAssemblyName { [PreserveSig()] int SetProperty(int PropertyId, IntPtr pvProperty, int cbProperty); [PreserveSig()] int GetProperty(int PropertyId, IntPtr pvProperty, ref int pcbProperty); [PreserveSig()] int Finalize(); [PreserveSig()] int GetDisplayName(StringBuilder pDisplayName, ref int pccDisplayName, int displayFlags); [PreserveSig()] int Reserved(ref Guid guid, Object o1, Object o2, string string1, Int64 llFlags, IntPtr pvReserved, int cbReserved, out IntPtr ppv); [PreserveSig()] int GetName(ref int pccBuffer, StringBuilder pwzName); [PreserveSig()] int GetVersion(out int versionHi, out int versionLow); [PreserveSig()] int IsEqual(IAssemblyName pAsmName, int cmpFlags); [PreserveSig()] int Clone(out IAssemblyName pAsmName); } /// <summary> /// IAssemblyEnum; COM import /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] internal interface IAssemblyEnum { [PreserveSig()] int GetNextAssembly(IntPtr pvReserved, out IAssemblyName ppName, int flags); [PreserveSig()] int Reset(); [PreserveSig()] int Clone(out IAssemblyEnum ppEnum); } /// <summary> /// AssemblyCommitFlags; Used by COM imported calls /// </summary> enum AssemblyCommitFlags { Default, Force } /// <summary> /// AssemblyCacheFlags; Used by COM imported calls /// </summary> [Flags] internal enum AssemblyCacheFlags { GAC = 2 } /// <summary> /// AssemblyCacheUninstallDisposition; Used by COM imported calls /// </summary> enum AssemblyCacheUninstallDisposition { Unknown, Uninstalled, StillInUse, AlreadyUninstalled, DeletePending, HasInstallReference, ReferenceNotFound, } /// <summary> /// CreateAssemblyNameObjectFlags; Used by COM imported calls /// </summary> internal enum CreateAssemblyNameObjectFlags { CANOF_DEFAULT, CANOF_PARSE_DISPLAY_NAME, CANOF_SET_DEFAULT_VALUES } /// <summary> /// AssemblyNameDisplayFlags; Used by COM imported calls /// </summary> [Flags] internal enum AssemblyNameDisplayFlags { VERSION = 0x01, CULTURE = 0x02, PUBLIC_KEY_TOKEN = 0x04, PROCESSORARCHITECTURE = 0x20, RETARGETABLE = 0x80, ALL = VERSION | CULTURE | PROCESSORARCHITECTURE | PUBLIC_KEY_TOKEN | RETARGETABLE } /// <summary> /// InstallReference + struct initialization; Used by COM imported calls /// </summary> [StructLayout(LayoutKind.Sequential)] class InstallReference { int cbSize; int flags; Guid guidScheme; [MarshalAs(UnmanagedType.LPWStr)] string identifier; [MarshalAs(UnmanagedType.LPWStr)] string nonCannonicalData; public InstallReference(Guid guid, string id, string data) { cbSize = (int)(2 * IntPtr.Size + 16 + (id.Length + data.Length) * 2); flags = 0; guidScheme = guid; identifier = id; nonCannonicalData = data; } public Guid GuidScheme { get { return guidScheme; } } } /// <summary> /// AssemblyInfo; Used by COM imported calls /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct AssemblyInfo { public int cbAssemblyInfo; public int assemblyFlags; public long assemblySizeInKB; [MarshalAs(UnmanagedType.LPWStr)] public string currentAssemblyPath; public int cchBuf; } /// <summary> /// InstallReferenceGuid; Used by COM imported calls /// </summary> [ComVisible(false)] class InstallReferenceGuid { public static bool IsValidGuidScheme(Guid guid) { return (guid.Equals(UninstallSubkeyGuid) || guid.Equals(FilePathGuid) || guid.Equals(OpaqueStringGuid) || guid.Equals(Guid.Empty)); } public readonly static Guid UninstallSubkeyGuid = new Guid("8cedc215-ac4b-488b-93c0-a50a49cb2fb8"); public readonly static Guid FilePathGuid = new Guid("b02f9d65-fb77-4f7a-afa5-b391309f11c9"); public readonly static Guid OpaqueStringGuid = new Guid("2ec93463-b0c3-45e1-8364-327e96aea856"); } /// <summary> /// Helper calss for IAssemblyCache /// </summary> [ComVisible(false)] class AssemblyCache { // If you use this, fusion will do the streaming & commit public static void InstallAssembly(string assemblyPath, InstallReference reference, AssemblyCommitFlags flags) { if (reference != null) { if (!InstallReferenceGuid.IsValidGuidScheme(reference.GuidScheme)) throw new ArgumentException("Invalid argument( reference guid)."); } IAssemblyCache asmCache = null; COM.CheckHR(CreateAssemblyCache(out asmCache, 0)); COM.CheckHR(asmCache.InstallAssembly((int)flags, assemblyPath, reference)); } public static void UninstallAssembly(string assemblyName, InstallReference reference, out AssemblyCacheUninstallDisposition disp) { AssemblyCacheUninstallDisposition dispResult = AssemblyCacheUninstallDisposition.Uninstalled; if (reference != null) { if (!InstallReferenceGuid.IsValidGuidScheme(reference.GuidScheme)) throw new ArgumentException("Invalid argument (reference guid)."); } IAssemblyCache asmCache = null; COM.CheckHR(CreateAssemblyCache(out asmCache, 0)); COM.CheckHR(asmCache.UninstallAssembly(0, assemblyName, reference, out dispResult)); disp = dispResult; } public static string QueryAssemblyInfo(string assemblyName) { if (assemblyName == null) { throw new ArgumentException("Invalid argument (assemblyName)"); } AssemblyInfo aInfo = new AssemblyInfo(); aInfo.cchBuf = 1024; aInfo.currentAssemblyPath = "Path".PadLeft(aInfo.cchBuf); IAssemblyCache ac = null; COM.CheckHR(CreateAssemblyCache(out ac, 0)); COM.CheckHR(ac.QueryAssemblyInfo(0, assemblyName, ref aInfo)); return aInfo.currentAssemblyPath; } [DllImport("fusion.dll")] internal static extern int CreateAssemblyCache(out IAssemblyCache ppAsmCache, int reserved); } /// <summary> /// Helper calss for IAssemblyEnum /// </summary> [ComVisible(false)] class AssemblyEnum { public AssemblyEnum(string sAsmName) { IAssemblyName asmName = null; if (sAsmName != null) //if no name specified all assemblies will be returned { COM.CheckHR(CreateAssemblyNameObject(out asmName, sAsmName, CreateAssemblyNameObjectFlags.CANOF_PARSE_DISPLAY_NAME, IntPtr.Zero)); } COM.CheckHR(CreateAssemblyEnum(out m_assemblyEnum, IntPtr.Zero, asmName, AssemblyCacheFlags.GAC, IntPtr.Zero)); } public string GetNextAssembly() { string retval = null; if (!m_done) { IAssemblyName asmName = null; COM.CheckHR(m_assemblyEnum.GetNextAssembly((IntPtr)0, out asmName, 0)); if (asmName != null) retval = GetFullName(asmName); m_done = (retval == null); } return retval; } private string GetFullName(IAssemblyName asmName) { StringBuilder fullName = new StringBuilder(1024); int iLen = fullName.Capacity; COM.CheckHR(asmName.GetDisplayName(fullName, ref iLen, (int)AssemblyNameDisplayFlags.ALL)); return fullName.ToString(); } [DllImport("fusion.dll")] internal static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, IntPtr pUnkReserved, IAssemblyName pName, AssemblyCacheFlags flags, IntPtr pvReserved); [DllImport("fusion.dll")] internal static extern int CreateAssemblyNameObject(out IAssemblyName ppAssemblyNameObj, [MarshalAs(UnmanagedType.LPWStr)] string szAssemblyName, CreateAssemblyNameObjectFlags flags, IntPtr pvReserved); private bool m_done; private IAssemblyEnum m_assemblyEnum = null; } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class ContentTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { IContentType contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); IContent contentItem = MockedContent.CreateTextpageContent(contentType1, "Testing", -1); ServiceContext.ContentService.SaveAndPublishWithStatus(contentItem); var initProps = contentItem.Properties.Count; var initPropTypes = contentItem.PropertyTypes.Count(); //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); //re-load it from the db contentItem = ServiceContext.ContentService.GetById(contentItem.Id); Assert.AreEqual(initPropTypes - 1, contentItem.PropertyTypes.Count()); Assert.AreEqual(initProps - 1, contentItem.Properties.Count); } [Test] public void Rebuild_Content_Xml_On_Alias_Change() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); var contentType2 = MockedContentTypes.CreateTextpageContentType("test2", "Test2"); ServiceContext.ContentTypeService.Save(contentType1); ServiceContext.ContentTypeService.Save(contentType2); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); var contentItems2 = MockedContent.CreateTextpageContent(contentType2, -1, 5).ToArray(); contentItems2.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); //only update the contentType1 alias which will force an xml rebuild for all content of that type contentType1.Alias = "newAlias"; ServiceContext.ContentTypeService.Save(contentType1); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<newAlias")); } foreach (var c in contentItems2) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same } } [Test] public void Rebuild_Content_Xml_On_Property_Removal() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); var alias = contentType1.PropertyTypes.First().Alias; var elementToMatch = "<" + alias + ">"; foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); var reQueried = ServiceContext.ContentTypeService.GetContentType(contentType1.Id); var reContent = ServiceContext.ContentService.GetById(contentItems1.First().Id); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } } [Test] public void Get_Descendants() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.Descendants(); //Assert Assert.AreEqual(10, descendants.Count()); } [Test] public void Get_Descendants_And_Self() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.DescendantsAndSelf(); //Assert Assert.AreEqual(11, descendants.Count()); } [Test] public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); for (var i = 0; i < hierarchy.Count(); i++) { if (i == 0) continue; Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } [Test] public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange var cs = ServiceContext.ContentService; var cts = ServiceContext.ContentTypeService; var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); var ctBase = new ContentType(-1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; ctBase.AddPropertyType(new PropertyType(dtdYesNo) { Name = "Hide From Navigation", Alias = Constants.Conventions.Content.NaviHide } /*,"Navigation"*/); cts.Save(ctBase); var ctHomePage = new ContentType(ctBase) { Name = "Home Page", Alias = "HomePage", Icon = "settingDomain.gif", Thumbnail = "folder.png", AllowedAsRoot = true }; ctHomePage.AddPropertyType(new PropertyType(dtdYesNo) { Name = "Some property", Alias = "someProperty" } /*,"Navigation"*/); cts.Save(ctHomePage); // Act var homeDoc = cs.CreateContent("Home Page", -1, "HomePage"); cs.SaveAndPublishWithStatus(homeDoc); // Assert Assert.That(ctBase.HasIdentity, Is.True); Assert.That(ctHomePage.HasIdentity, Is.True); Assert.That(homeDoc.HasIdentity, Is.True); Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); } [Test] public void Create_Content_Type_Ensures_Sort_Orders() { var service = ServiceContext.ContentTypeService; var contentType = new ContentType(-1) { Alias = "test", Name = "Test", Description = "ContentType used for simple text pages", Icon = ".sprTreeDoc3", Thumbnail = "doc2.png", SortOrder = 1, CreatorId = 0, Trashed = false }; contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", Mandatory = false, DataTypeDefinitionId = -88 }); contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TinyMCEAlias, DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", Mandatory = false, DataTypeDefinitionId = -87 }); contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", Mandatory = false, DataTypeDefinitionId = -88 }); service.Save(contentType); var sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); Assert.AreEqual(1, sortOrders.Count(x => x == 0)); Assert.AreEqual(1, sortOrders.Count(x => x == 1)); Assert.AreEqual(1, sortOrders.Count(x => x == 2)); } [Test] public void Can_Create_And_Save_ContentType_Composition() { /* * Global * - Components * - Category */ var service = ServiceContext.ContentTypeService; var global = MockedContentTypes.CreateSimpleContentType("global", "Global"); service.Save(global); var components = MockedContentTypes.CreateSimpleContentType("components", "Components", global); service.Save(components); var component = MockedContentTypes.CreateSimpleContentType("component", "Component", components); service.Save(component); var category = MockedContentTypes.CreateSimpleContentType("category", "Category", global); service.Save(category); var success = category.AddContentType(component); Assert.That(success, Is.False); } [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { //Test for U4-2234 var cts = ServiceContext.ContentTypeService; //Arrange var component = CreateComponent(); cts.Save(component); var banner = CreateBannerComponent(component); cts.Save(banner); var site = CreateSite(); cts.Save(site); var homepage = CreateHomepage(site); cts.Save(homepage); //Add banner to homepage var added = homepage.AddContentType(banner); cts.Save(homepage); //Assert composition var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); //Remove banner from homepage var removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); //Assert composition var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); } [Test] public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); service.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); var contentType = service.GetContentType(sut.Id); var category = service.GetContentType(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); Assert.AreEqual(contentType.Level, category.Level); Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); Assert.AreNotEqual(contentType.Id, category.Id); Assert.AreNotEqual(contentType.Key, category.Key); Assert.AreNotEqual(contentType.Path, category.Path); Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2"); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1); service.Save(simpleContentType); // Act var clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); clone.RemoveContentType("parent1"); clone.AddContentType(parentContentType2); clone.ParentId = parentContentType2.Id; service.Save(clone); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_With_Service_To_Root() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var clone = service.Copy(simpleContentType, "newcategory", "new category"); // Assert Assert.That(clone.HasIdentity, Is.True); var cloned = service.GetContentType(clone.Id); var original = service.GetContentType(categoryId); Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); //it's been copied to root Assert.AreEqual(cloned.ParentId, -1); Assert.AreEqual(cloned.Level, 1); Assert.AreEqual(cloned.PropertyTypes.Count(), original.PropertyTypes.Count()); Assert.AreEqual(cloned.PropertyGroups.Count(), original.PropertyGroups.Count()); for (int i = 0; i < cloned.PropertyGroups.Count; i++) { Assert.AreEqual(cloned.PropertyGroups[i].PropertyTypes.Count, original.PropertyGroups[i].PropertyTypes.Count); foreach (var propertyType in cloned.PropertyGroups[i].PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } } foreach (var propertyType in cloned.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } Assert.AreNotEqual(cloned.Id, original.Id); Assert.AreNotEqual(cloned.Key, original.Key); Assert.AreNotEqual(cloned.Path, original.Path); Assert.AreNotEqual(cloned.SortOrder, original.SortOrder); Assert.AreNotEqual(cloned.PropertyTypes.First(x => x.Alias.Equals("title")).Id, original.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(cloned.PropertyGroups.First(x => x.Name.Equals("Content")).Id, original.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_With_Service() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2"); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1); service.Save(simpleContentType); // Act var clone = service.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } private ContentType CreateComponent() { var component = new ContentType(-1) { Alias = "component", Name = "Component", Description = "ContentType used for Component grouping", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; } private ContentType CreateBannerComponent(ContentType parent) { var banner = new ContentType(parent) { Alias = "banner", Name = "Banner Component", Description = "ContentType used for Banner Component", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var propertyType = new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "bannerName", Name = "Banner Name", Description = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -88 }; banner.AddPropertyType(propertyType, "Component"); return banner; } private ContentType CreateSite() { var site = new ContentType(-1) { Alias = "site", Name = "Site", Description = "ContentType used for Site inheritence", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 2, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; } private ContentType CreateHomepage(ContentType parent) { var contentType = new ContentType(parent) { Alias = "homepage", Name = "Homepage", Description = "ContentType used for the Homepage", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); return contentType; } private IContentType[] CreateContentTypeHierarchy() { //create the master type var masterContentType = MockedContentTypes.CreateSimpleContentType("masterContentType", "MasterContentType"); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ServiceContext.ContentTypeService.Save(masterContentType); //add the one we just created var list = new List<IContentType> { masterContentType }; for (var i = 0; i < 10; i++) { var contentType = MockedContentTypes.CreateSimpleContentType("childType" + i, "ChildType" + i, //make the last entry in the list, this one's parent list.Last()); list.Add(contentType); } return list.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx2.IsSupported) { { byte* inBuffer = stackalloc byte[64]; int* inArray = (int*)Align(inBuffer, 32); int* outArray = stackalloc int[8]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 8; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on int:"); for (var n = 0; n < 8; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; long* inArray = (long*)Align(inBuffer, 32); long* outArray = stackalloc long[4]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 4; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on long:"); for (var n = 0; n < 4; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; uint* inArray = (uint*)Align(inBuffer, 32); uint* outArray = stackalloc uint[8]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 8; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on uint:"); for (var n = 0; n < 8; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; ulong* inArray = (ulong*)Align(inBuffer, 32); ulong* outArray = stackalloc ulong[4]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 4; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on ulong:"); for (var n = 0; n < 4; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; short* inArray = (short*)Align(inBuffer, 32); short* outArray = stackalloc short[16]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 16; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on short:"); for (var n = 0; n < 16; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; ushort* inArray = (ushort*)Align(inBuffer, 32); ushort* outArray = stackalloc ushort[16]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 16; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on ushort:"); for (var n = 0; n < 16; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; sbyte* inArray = (sbyte*)Align(inBuffer, 32); sbyte* outArray = stackalloc sbyte[32]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 32; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on sbyte:"); for (var n = 0; n < 32; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } { byte* inBuffer = stackalloc byte[64]; byte* inArray = (byte*)Align(inBuffer, 32); byte* outArray = stackalloc byte[32]; var vf = Avx2.LoadAlignedVector256NonTemporal(inArray); Unsafe.Write(outArray, vf); for (var i = 0; i < 32; i++) { if (inArray[i] != outArray[i]) { Console.WriteLine("Avx2 LoadAlignedVector256NonTemporal failed on byte:"); for (var n = 0; n < 32; n++) { Console.Write(outArray[n] + ", "); } Console.WriteLine(); testResult = Fail; break; } } } } return testResult; } static unsafe void* Align(byte* buffer, byte expectedAlignment) { // Compute how bad the misalignment is, which is at most (expectedAlignment - 1). // Then subtract that from the expectedAlignment and add it to the original address // to compute the aligned address. var misalignment = expectedAlignment - ((ulong)(buffer) % expectedAlignment); return (void*)(buffer + misalignment); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Dialog { public class DialogModule : IRegionModule, IDialogModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Scene m_scene; public void Initialise(Scene scene, IConfigSource source) { m_scene = scene; m_scene.RegisterModuleInterface<IDialogModule>(this); m_scene.AddCommand( this, "alert", "alert <first> <last> <message>", "Send an alert to a user", HandleAlertConsoleCommand); m_scene.AddCommand( this, "alert general", "alert general <message>", "Send an alert to everyone", HandleAlertConsoleCommand); } public void PostInitialise() {} public void Close() {} public string Name { get { return "Dialog Module"; } } public bool IsSharedModule { get { return false; } } public void SendAlertToUser(IClientAPI client, string message) { SendAlertToUser(client, message, false); } public void SendAlertToUser(IClientAPI client, string message, bool modal) { client.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(UUID agentID, string message) { SendAlertToUser(agentID, message, false); } public void SendAlertToUser(UUID agentID, string message, bool modal) { ScenePresence sp = m_scene.GetScenePresence(agentID); if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(string firstName, string lastName, string message, bool modal) { ScenePresence presence = m_scene.GetScenePresence(firstName, lastName); if (presence != null && !presence.IsChildAgent) presence.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendGeneralAlert(string message) { m_scene.ForEachScenePresence(delegate(ScenePresence presence) { if (!presence.IsChildAgent) presence.ControllingClient.SendAlertMessage(message); }); } public void SendDialogToUser( UUID avatarID, string objectName, UUID objectID, UUID ownerID, string message, UUID textureID, int ch, string[] buttonlabels) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerID); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } ScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendDialog(objectName, objectID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels); } public void SendUrlToUser( UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { ScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); } public void SendTextBoxToUser(UUID avatarid, string message, int chatChannel, string name, UUID objectid, UUID ownerid) { UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, ownerid); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } ScenePresence sp = m_scene.GetScenePresence(avatarid); if (sp != null && !sp.IsChildAgent) sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectid); } public void SendNotificationToUsersInRegion( UUID fromAvatarID, string fromAvatarName, string message) { m_scene.ForEachScenePresence(delegate(ScenePresence presence) { if (!presence.IsChildAgent) presence.ControllingClient.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message); }); } /// <summary> /// Handle an alert command from the console. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> public void HandleAlertConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() != null && m_scene.ConsoleScene() != m_scene) return; if (cmdparams[1] == "general") { string message = CombineParams(cmdparams, 2); m_log.InfoFormat( "[DIALOG]: Sending general alert in region {0} with message {1}", m_scene.RegionInfo.RegionName, message); SendGeneralAlert(message); } else { string firstName = cmdparams[1]; string lastName = cmdparams[2]; string message = CombineParams(cmdparams, 3); m_log.InfoFormat( "[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}", m_scene.RegionInfo.RegionName, firstName, lastName, message); SendAlertToUser(firstName, lastName, message, false); } } private string CombineParams(string[] commandParams, int pos) { string result = string.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } return result; } } }
using System; using System.Linq.Expressions; using System.Reflection; using Nop.Core; using Nop.Core.Domain.Localization; using Nop.Core.Domain.Security; using Nop.Core.Infrastructure; using Nop.Core.Plugins; namespace Nop.Services.Localization { public static class LocalizationExtensions { /// <summary> /// Get localized property of an entity /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="entity">Entity</param> /// <param name="keySelector">Key selector</param> /// <returns>Localized property</returns> public static string GetLocalized<T>(this T entity, Expression<Func<T, string>> keySelector) where T : BaseEntity, ILocalizedEntity { var workContext = EngineContext.Current.Resolve<IWorkContext>(); return GetLocalized(entity, keySelector, workContext.WorkingLanguage.Id); } /// <summary> /// Get localized property of an entity /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="entity">Entity</param> /// <param name="keySelector">Key selector</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <param name="ensureTwoPublishedLanguages">A value indicating whether to ensure that we have at least two published languages; otherwise, load only default value</param> /// <returns>Localized property</returns> public static string GetLocalized<T>(this T entity, Expression<Func<T, string>> keySelector, int languageId, bool returnDefaultValue = true, bool ensureTwoPublishedLanguages = true) where T : BaseEntity, ILocalizedEntity { return GetLocalized<T, string>(entity, keySelector, languageId, returnDefaultValue, ensureTwoPublishedLanguages); } /// <summary> /// Get localized property of an entity /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="TPropType">Property type</typeparam> /// <param name="entity">Entity</param> /// <param name="keySelector">Key selector</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <param name="ensureTwoPublishedLanguages">A value indicating whether to ensure that we have at least two published languages; otherwise, load only default value</param> /// <returns>Localized property</returns> public static TPropType GetLocalized<T, TPropType>(this T entity, Expression<Func<T, TPropType>> keySelector, int languageId, bool returnDefaultValue = true, bool ensureTwoPublishedLanguages = true) where T : BaseEntity, ILocalizedEntity { if (entity == null) throw new ArgumentNullException("entity"); var member = keySelector.Body as MemberExpression; if (member == null) { throw new ArgumentException(string.Format( "Expression '{0}' refers to a method, not a property.", keySelector)); } var propInfo = member.Member as PropertyInfo; if (propInfo == null) { throw new ArgumentException(string.Format( "Expression '{0}' refers to a field, not a property.", keySelector)); } TPropType result = default(TPropType); string resultStr = string.Empty; //load localized value string localeKeyGroup = typeof(T).Name; string localeKey = propInfo.Name; if (languageId > 0) { //ensure that we have at least two published languages bool loadLocalizedValue = true; if (ensureTwoPublishedLanguages) { var lService = EngineContext.Current.Resolve<ILanguageService>(); var totalPublishedLanguages = lService.GetAllLanguages().Count; loadLocalizedValue = totalPublishedLanguages >= 2; } //localized value if (loadLocalizedValue) { var leService = EngineContext.Current.Resolve<ILocalizedEntityService>(); resultStr = leService.GetLocalizedValue(languageId, entity.Id, localeKeyGroup, localeKey); if (!String.IsNullOrEmpty(resultStr)) result = CommonHelper.To<TPropType>(resultStr); } } //set default value if required if (String.IsNullOrEmpty(resultStr) && returnDefaultValue) { var localizer = keySelector.Compile(); result = localizer(entity); } return result; } /// <summary> /// Get localized value of enum /// </summary> /// <typeparam name="T">Enum</typeparam> /// <param name="enumValue">Enum value</param> /// <param name="localizationService">Localization service</param> /// <param name="workContext">Work context</param> /// <returns>Localized value</returns> public static string GetLocalizedEnum<T>(this T enumValue, ILocalizationService localizationService, IWorkContext workContext) where T : struct { if (workContext == null) throw new ArgumentNullException("workContext"); return GetLocalizedEnum<T>(enumValue, localizationService, workContext.WorkingLanguage.Id); } /// <summary> /// Get localized value of enum /// </summary> /// <typeparam name="T">Enum</typeparam> /// <param name="enumValue">Enum value</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <returns>Localized value</returns> public static string GetLocalizedEnum<T>(this T enumValue, ILocalizationService localizationService, int languageId) where T : struct { if (localizationService == null) throw new ArgumentNullException("localizationService"); if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); //localized value string resourceName = string.Format("Enums.{0}.{1}", typeof(T).ToString(), //Convert.ToInt32(enumValue) enumValue.ToString()); string result = localizationService.GetResource(resourceName, languageId, false, "", true); //set default value if required if (String.IsNullOrEmpty(result)) result = CommonHelper.ConvertEnum(enumValue.ToString()); return result; } /// <summary> /// Get localized value of permission /// We don't have UI to manage permission localizable name. That's why we're using this extension method /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="workContext">Work context</param> /// <returns>Localized value</returns> public static string GetLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, IWorkContext workContext) { if (workContext == null) throw new ArgumentNullException("workContext"); return GetLocalizedPermissionName(permissionRecord, localizationService, workContext.WorkingLanguage.Id); } /// <summary> /// Get localized value of enum /// We don't have UI to manage permission localizable name. That's why we're using this extension method /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <returns>Localized value</returns> public static string GetLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, int languageId) { if (permissionRecord == null) throw new ArgumentNullException("permissionRecord"); if (localizationService == null) throw new ArgumentNullException("localizationService"); //localized value string resourceName = string.Format("Permission.{0}", permissionRecord.SystemName); string result = localizationService.GetResource(resourceName, languageId, false, "", true); //set default value if required if (String.IsNullOrEmpty(result)) result = permissionRecord.Name; return result; } /// <summary> /// Save localized name of a permission /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> public static void SaveLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, ILanguageService languageService) { if (permissionRecord == null) throw new ArgumentNullException("permissionRecord"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); string resourceName = string.Format("Permission.{0}", permissionRecord.SystemName); string resourceValue = permissionRecord.Name; foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr == null) { lsr = new LocaleStringResource() { LanguageId = lang.Id, ResourceName = resourceName, ResourceValue = resourceValue }; localizationService.InsertLocaleStringResource(lsr); } else { lsr.ResourceValue = resourceValue; localizationService.UpdateLocaleStringResource(lsr); } } } /// <summary> /// Delete a localized name of a permission /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> public static void DeleteLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, ILanguageService languageService) { if (permissionRecord == null) throw new ArgumentNullException("permissionRecord"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); string resourceName = string.Format("Permission.{0}", permissionRecord.SystemName); foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr != null) localizationService.DeleteLocaleStringResource(lsr); } } /// <summary> /// Delete a locale resource /// </summary> /// <param name="plugin">Plugin</param> /// <param name="resourceName">Resource name</param> public static void DeletePluginLocaleResource(this BasePlugin plugin, string resourceName) { var localizationService = EngineContext.Current.Resolve<ILocalizationService>(); var languageService = EngineContext.Current.Resolve<ILanguageService>(); DeletePluginLocaleResource(plugin, localizationService, languageService, resourceName); } /// <summary> /// Delete a locale resource /// </summary> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> /// <param name="resourceName">Resource name</param> public static void DeletePluginLocaleResource(this BasePlugin plugin, ILocalizationService localizationService, ILanguageService languageService, string resourceName) { //actually plugin instance is not required if (plugin == null) throw new ArgumentNullException("plugin"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr != null) localizationService.DeleteLocaleStringResource(lsr); } } /// <summary> /// Add a locale resource (if new) or update an existing one /// </summary> /// <param name="plugin">Plugin</param> /// <param name="resourceName">Resource name</param> /// <param name="resourceValue">Resource value</param> public static void AddOrUpdatePluginLocaleResource(this BasePlugin plugin, string resourceName, string resourceValue) { var localizationService = EngineContext.Current.Resolve<ILocalizationService>(); var languageService = EngineContext.Current.Resolve<ILanguageService>(); AddOrUpdatePluginLocaleResource(plugin, localizationService, languageService, resourceName, resourceValue); } /// <summary> /// Add a locale resource (if new) or update an existing one /// </summary> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> /// <param name="resourceName">Resource name</param> /// <param name="resourceValue">Resource value</param> public static void AddOrUpdatePluginLocaleResource(this BasePlugin plugin, ILocalizationService localizationService, ILanguageService languageService, string resourceName, string resourceValue) { //actually plugin instance is not required if (plugin == null) throw new ArgumentNullException("plugin"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr == null) { lsr = new LocaleStringResource() { LanguageId = lang.Id, ResourceName = resourceName, ResourceValue = resourceValue }; localizationService.InsertLocaleStringResource(lsr); } else { lsr.ResourceValue = resourceValue; localizationService.UpdateLocaleStringResource(lsr); } } } /// <summary> /// Get localized friendly name of a plugin /// </summary> /// <typeparam name="T">Plugin</typeparam> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <returns>Localized value</returns> public static string GetLocalizedFriendlyName<T>(this T plugin, ILocalizationService localizationService, int languageId, bool returnDefaultValue = true) where T : IPlugin { if (localizationService == null) throw new ArgumentNullException("localizationService"); if (plugin == null) throw new ArgumentNullException("plugin"); if (plugin.PluginDescriptor == null) throw new ArgumentException("Plugin descriptor cannot be loaded"); string systemName = plugin.PluginDescriptor.SystemName; //localized value string resourceName = string.Format("Plugins.FriendlyName.{0}", systemName); string result = localizationService.GetResource(resourceName, languageId, false, "", true); //set default value if required if (String.IsNullOrEmpty(result) && returnDefaultValue) result = plugin.PluginDescriptor.FriendlyName; return result; } /// <summary> /// Save localized friendly name of a plugin /// </summary> /// <typeparam name="T">Plugin</typeparam> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <param name="localizedFriendlyName">Localized friendly name</param> public static void SaveLocalizedFriendlyName<T>(this T plugin, ILocalizationService localizationService, int languageId, string localizedFriendlyName) where T : IPlugin { if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageId == 0) throw new ArgumentOutOfRangeException("languageId", "Language ID should not be 0"); if (plugin == null) throw new ArgumentNullException("plugin"); if (plugin.PluginDescriptor == null) throw new ArgumentException("Plugin descriptor cannot be loaded"); string systemName = plugin.PluginDescriptor.SystemName; //localized value string resourceName = string.Format("Plugins.FriendlyName.{0}", systemName); var resource = localizationService.GetLocaleStringResourceByName(resourceName, languageId, false); if (resource != null) { if (string.IsNullOrWhiteSpace(localizedFriendlyName)) { //delete localizationService.DeleteLocaleStringResource(resource); } else { //update resource.ResourceValue = localizedFriendlyName; localizationService.UpdateLocaleStringResource(resource); } } else { if (!string.IsNullOrWhiteSpace(localizedFriendlyName)) { //insert resource = new LocaleStringResource() { LanguageId = languageId, ResourceName = resourceName, ResourceValue = localizedFriendlyName, }; localizationService.InsertLocaleStringResource(resource); } } } } }
//#define TRACEPTW using System; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System.Windows.Threading; using System.Windows.Media; using System.Threading; using System.Security; using System.Security.Permissions; using MS.Internal; using MS.Internal.PresentationCore; // SecurityHelper using System.Collections.Generic; using System.Collections.ObjectModel; using MS.Win32.Penimc; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Input { ///////////////////////////////////////////////////////////////////////// internal sealed class PenThreadWorker { /// <summary>List of constants for PenImc</summary> const int PenEventNone = 0; const int PenEventTimeout = 1; const int PenEventPenInRange = 707; const int PenEventPenOutOfRange = 708; const int PenEventPenDown = 709; const int PenEventPenUp = 710; const int PenEventPackets = 711; const int PenEventSystem = 714; const int MaxContextPerThread = 31; // (64 - 1) / 2 = 31. Max handle limit for MsgWaitForMultipleMessageEx() const int EventsFrequency = 8; /// <SecurityNote> /// Critical - Marked critical to prevent inadvertant code from modifying this. /// </SecurityNote> [SecurityCritical] IntPtr [] _handles = new IntPtr[0]; /// <SecurityNote> /// Critical - Marked critical to prevent inadvertant code from modifying this. /// </SecurityNote> [SecurityCritical] WeakReference [] _penContexts = new WeakReference[0]; /// <SecurityNote> /// Critical - Marked critical to prevent inadvertant code from modifying this. /// </SecurityNote> [SecurityCritical] IPimcContext [] _pimcContexts = new IPimcContext[0]; /// <SecurityNote> /// SecurityCritical - This is got under an elevation and is hence critical. /// </SecurityNote> private SecurityCriticalData<IntPtr> _pimcResetHandle; private volatile bool __disposed; private List <WorkerOperation> _workerOperation = new List<WorkerOperation>(); private object _workerOperationLock = new Object(); // For caching move events. /// <SecurityNote> /// Critical to prevent accidental spread to transparent code /// </SecurityNote> [SecurityCritical] private PenContext _cachedMovePenContext; private int _cachedMoveStylusPointerId; private int _cachedMoveStartTimestamp; private int [] _cachedMoveData; ///////////////////////////////////////////////////////////////////// // // Here's a bunch of helper classes to manage marshalling the calls // over to the worker thread to be executed synchronously. // ///////////////////////////////////////////////////////////////////// // Base class for all worker operations private abstract class WorkerOperation { AutoResetEvent _doneEvent; internal WorkerOperation() { _doneEvent = new AutoResetEvent(false); } /// <summary> /// Critical - Calls SecurityCritical code OnDoWork which is differred based on the various derived class. /// Called by PenThreadWorker.ThreadProc(). /// </summary> [SecurityCritical] internal void DoWork() { try { OnDoWork(); } finally { _doneEvent.Set(); } } /// <summary> /// Critical - Calls SecurityCritical code OnDoWork which is differred based on the various derived class. /// Called by WorkerOperation.DoWork(). /// </summary> [SecurityCritical] protected abstract void OnDoWork(); internal AutoResetEvent DoneEvent { get { return _doneEvent;} } } // Class that handles getting the current rect for a tablet device. private class WorkerOperationThreadStart : WorkerOperation { ///////////////////////////////////////////////////////////////////////// /// <summary> /// Used to signal when the thread has started up. /// </summary> protected override void OnDoWork() { // We don't need to do anything. Just have event signal we've executed. } } // Class that handles getting the tablet device info for all tablets on the system. private class WorkerOperationGetTabletsInfo : WorkerOperation { internal TabletDeviceInfo[] TabletDevicesInfo { get { return _tabletDevicesInfo;} } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the list of TabletDeviceInfo structs that contain information /// about all of the TabletDevices on the system. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - returns security critical data _pimcTablet /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { try { // create new collection of tablets MS.Win32.Penimc.IPimcManager pimcManager = MS.Win32.Penimc.UnsafeNativeMethods.PimcManager; uint cTablets; pimcManager.GetTabletCount(out cTablets); TabletDeviceInfo[] tablets = new TabletDeviceInfo[cTablets]; for ( uint iTablet = 0; iTablet < cTablets; iTablet++ ) { MS.Win32.Penimc.IPimcTablet pimcTablet; pimcManager.GetTablet(iTablet, out pimcTablet); tablets[iTablet] = PenThreadWorker.GetTabletInfoHelper(pimcTablet); } // Set result data and signal we are done. _tabletDevicesInfo = tablets; } catch ( System.Runtime.InteropServices.COMException ) { // result will not be initialized if we fail due to a COM exception. Debug.WriteLine("WorkerOperationGetTabletsInfo.OnDoWork failed due to a COMException"); // return no devices found on error. _tabletDevicesInfo = new TabletDeviceInfo[0]; } catch ( System.ArgumentException ) { // result will not be initialized if we fail due to an ArgumentException. Debug.WriteLine("WorkerOperationGetTabletsInfo.OnDoWork failed due to an ArgumentException"); // return no devices found on error. _tabletDevicesInfo = new TabletDeviceInfo[0]; } catch ( System.UnauthorizedAccessException ) { // result will not be initialized if we fail due to an UnauthorizedAccessException. Debug.WriteLine("WorkerOperationGetTabletsInfo.OnDoWork failed due to an UnauthorizedAccessException"); // return no devices found on error. _tabletDevicesInfo = new TabletDeviceInfo[0]; } } TabletDeviceInfo[] _tabletDevicesInfo; } // Class that handles creating a context for a particular tablet device. private class WorkerOperationCreateContext : WorkerOperation { /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] internal WorkerOperationCreateContext(IntPtr hwnd, IPimcTablet pimcTablet) { _hwnd = hwnd; _pimcTablet = pimcTablet; } internal PenContextInfo Result { get { return _result;} } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Creates a new context for this a window and given tablet device and /// returns a new PenContext in the workOperation class. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - handle security critical data _hwnd, _pimcTablet. /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { IPimcContext pimcContext; int id; Int64 commHandle; try { _pimcTablet.CreateContext(_hwnd, true, 250, out pimcContext, out id, out commHandle); // Set result data and signal we are done. PenContextInfo result; result.ContextId = id; result.PimcContext = new SecurityCriticalDataClass<IPimcContext>(pimcContext); // commHandle cannot be a IntPtr by itself because its native counterpart cannot be a // INT_PTR. The reason being that INT_PTR (__int3264) always gets marshalled as a // 32 bit value, which means in a 64 bit process we would lose the first half of the pointer. // Instead with this we always get a 64 bit value and then instantiate the IntPtr appropriately // so that nothing gets lost during marshalling. The cast from Int64 to Int32 below // should be lossless cast because both COM server and client are expected // to be of same bitness (they are in the same process). result.CommHandle = new SecurityCriticalDataClass<IntPtr>((IntPtr.Size == 4 ? new IntPtr((int)commHandle) : new IntPtr(commHandle))); _result = result; } catch ( System.Runtime.InteropServices.COMException ) { // result will not be initialized if we fail due to a COM exception. Debug.WriteLine("WorkerOperationCreateContext.OnDoWork failed due to a COMException"); // set with uninitialized PenContextInfo (all zero). _result = new PenContextInfo(); } catch ( System.ArgumentException ) { // result will not be initialized if we fail due to an ArgumentException. Debug.WriteLine("WorkerOperationCreateContext.OnDoWork failed due to an ArgumentException"); // set with uninitialized PenContextInfo (all zero). _result = new PenContextInfo(); } catch ( System.UnauthorizedAccessException ) { // result will not be initialized if we fail due to an UnauthorizedAccessException. Debug.WriteLine("WorkerOperationCreateContext.OnDoWork failed due to an UnauthorizedAccessException"); // set with uninitialized PenContextInfo (all zero). _result = new PenContextInfo(); } } /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] IntPtr _hwnd; /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] IPimcTablet _pimcTablet; PenContextInfo _result; } // Class that handles refreshing the cursor devices for a particular tablet device. private class WorkerOperationRefreshCursorInfo : WorkerOperation { /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] internal WorkerOperationRefreshCursorInfo(IPimcTablet pimcTablet) { _pimcTablet = pimcTablet; } internal StylusDeviceInfo[] StylusDevicesInfo { get { return _stylusDevicesInfo; } } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Causes the stylus devices info (cursors) in penimc to be refreshed /// for the passed in IPimcTablet. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - handle security critical data _pimcTablet. /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { try { _pimcTablet.RefreshCursorInfo(); _stylusDevicesInfo = PenThreadWorker.GetStylusDevicesInfo(_pimcTablet); } catch ( System.Runtime.InteropServices.COMException ) { // result will not be initialized if we fail due to a COM exception. Debug.WriteLine("WorkerOperationRefreshCursorInfo.OnDoWork failed due to a COMException"); } catch ( System.ArgumentException ) { // result will not be initialized if we fail due to a ArgumentException. Debug.WriteLine("WorkerOperationRefreshCursorInfo.OnDoWork failed due to an ArgumentException"); } catch ( System.UnauthorizedAccessException ) { // result will not be initialized if we fail due to an UnauthorizedAccessException. Debug.WriteLine("WorkerOperationRefreshCursorInfo.OnDoWork failed due to an UnauthorizedAccessException"); } } /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] IPimcTablet _pimcTablet; StylusDeviceInfo[] _stylusDevicesInfo; } // Class that handles getting info about a specific tablet device. private class WorkerOperationGetTabletInfo : WorkerOperation { internal WorkerOperationGetTabletInfo(uint index) { _index = index; } internal TabletDeviceInfo TabletDeviceInfo { get { return _tabletDeviceInfo;} } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Fills in a struct containing the list of TabletDevice properties for /// a given tablet device index. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - returns security critical data _pimcTablet /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { try { // create new collection of tablets MS.Win32.Penimc.IPimcManager pimcManager = MS.Win32.Penimc.UnsafeNativeMethods.PimcManager; MS.Win32.Penimc.IPimcTablet pimcTablet; pimcManager.GetTablet(_index, out pimcTablet); // Set result data and signal we are done. _tabletDeviceInfo = PenThreadWorker.GetTabletInfoHelper(pimcTablet); } catch ( System.Runtime.InteropServices.COMException ) { // result will not be initialized if we fail due to a COM exception. Debug.WriteLine("WorkerOperationGetTabletInfo.OnDoWork failed due to COMException"); // set to uninitialized TabletDeviceInfo struct (all zeros) to signal failure. _tabletDeviceInfo = new TabletDeviceInfo(); } catch ( System.ArgumentException ) { // result will not be initialized if we fail due to an ArgumentException. Debug.WriteLine("WorkerOperationGetTabletInfo.OnDoWork failed due to an ArgumentException"); // set to uninitialized TabletDeviceInfo struct (all zeros) to signal failure. _tabletDeviceInfo = new TabletDeviceInfo(); } catch ( System.UnauthorizedAccessException ) { // result will not be initialized if we fail due to an UnauthorizedAccessException. Debug.WriteLine("WorkerOperationGetTabletInfo.OnDoWork failed due to an UnauthorizedAccessException"); // set to uninitialized TabletDeviceInfo struct (all zeros) to signal failure. _tabletDeviceInfo = new TabletDeviceInfo(); } } uint _index; TabletDeviceInfo _tabletDeviceInfo; } // Class that handles getting the current rect for a tablet device. private class WorkerOperationWorkerGetUpdatedSizes : WorkerOperation { /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] internal WorkerOperationWorkerGetUpdatedSizes(IPimcTablet pimcTablet) { _pimcTablet = pimcTablet; } internal TabletDeviceSizeInfo TabletDeviceSizeInfo { get { return _tabletDeviceSizeInfo;} } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Gets the current rectangle for a tablet device and returns in workOperation class. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - handles security critical data _pimcTablet /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { try { int displayWidth, displayHeight, tabletWidth, tabletHeight; _pimcTablet.GetTabletAndDisplaySize(out tabletWidth, out tabletHeight, out displayWidth, out displayHeight); // Set result data and signal we are done. _tabletDeviceSizeInfo = new TabletDeviceSizeInfo( new Size( tabletWidth, tabletHeight), new Size( displayWidth, displayHeight)); } catch ( System.Runtime.InteropServices.COMException ) { // result will not be initialized if we fail due to a COM exception. Debug.WriteLine("WorkerOperationWorkerGetUpdatedSizes.OnDoWork failed due to a COMException"); // Size structs will be 1x1 if a COM exception is thrown. Should be dead context anyway on exception. _tabletDeviceSizeInfo = new TabletDeviceSizeInfo(new Size( 1, 1), new Size( 1, 1)); } catch ( System.UnauthorizedAccessException ) { // result will not be initialized if we fail due to an UnauthorizedAccessException. Debug.WriteLine("WorkerOperationWorkerGetUpdatedSizes.OnDoWork failed due to an UnauthorizedAccessException"); // Size structs will be 1x1 if a COM exception is thrown. Should be dead context anyway on exception. _tabletDeviceSizeInfo = new TabletDeviceSizeInfo(new Size( 1, 1), new Size( 1, 1)); } } /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] IPimcTablet _pimcTablet; TabletDeviceSizeInfo _tabletDeviceSizeInfo; } // Class that handles getting the current rect for a tablet device. private class WorkerOperationAddContext : WorkerOperation { /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] internal WorkerOperationAddContext(PenContext penContext, PenThreadWorker penThreadWorker) { _newPenContext = penContext; _penThreadWorker = penThreadWorker; } internal bool Result { get { return _result;} } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Adds a PenContext to the list of contexts that events can be received /// from and returns whether it was successful in workOperation class. /// </summary> /// <SecurityNote> /// Critical: - handles security critical data _penContexts, _handles, _pimcContexts /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { _result = _penThreadWorker.AddPenContext(_newPenContext); } /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] PenContext _newPenContext; /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] PenThreadWorker _penThreadWorker; bool _result; } // Class that handles getting the current rect for a tablet device. private class WorkerOperationRemoveContext : WorkerOperation { /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] internal WorkerOperationRemoveContext(PenContext penContext, PenThreadWorker penThreadWorker) { _penContextToRemove = penContext; _penThreadWorker = penThreadWorker; } internal bool Result { get { return _result;} } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Adds a PenContext to the list of contexts that events can be received /// from and returns whether it was successful in workOperation class. /// </summary> /// <SecurityNote> /// Critical: - handles security critical data _penContexts, _handles, _pimcContexts /// </SecurityNote> [SecurityCritical] protected override void OnDoWork() { _result = _penThreadWorker.RemovePenContext(_penContextToRemove); } /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] PenContext _penContextToRemove; /// <SecurityNote> /// Critical - Critical data got under an elevation and is hence critical. /// </SecurityNote> [SecurityCritical] PenThreadWorker _penThreadWorker; bool _result; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code MS.Win32.Penimc.UnsafeNativeMethods.CreateResetEvent /// and handles SecurityCritical data resetHandle. /// Called by PenThread constructor. /// TreatAsSafe boundry is Stylus.EnableCore, Stylus.RegisterHwndForInput /// and HwndWrapperHook class (via HwndSource.InputFilterMessage). /// </SecurityNote> [SecurityCritical] internal PenThreadWorker() { IntPtr resetHandle; // Consider: We could use a AutoResetEvent handle instead and avoid the penimc.dll call. MS.Win32.Penimc.UnsafeNativeMethods.CreateResetEvent(out resetHandle); _pimcResetHandle = new SecurityCriticalData<IntPtr>(resetHandle); WorkerOperationThreadStart started = new WorkerOperationThreadStart(); lock(_workerOperationLock) { _workerOperation.Add((WorkerOperation)started); } Thread thread = new Thread(new ThreadStart(ThreadProc)); thread.IsBackground = true; // don't hold process open due to this thread. thread.Start(); // Wait for this work to be completed (ie thread is started up). started.DoneEvent.WaitOne(); started.DoneEvent.Close(); } /// <SecurityNote> /// Critical - Needs to call SupressUnmanagedCodeSecurity attributed /// code to free unmanaged resource handle. Needs to be /// SecurityCritical for that. Also references SecurityCriticalData. /// </SecurityNote> [SecurityCritical] internal void Dispose() { if(!__disposed) { __disposed = true; // Kick thread to wake up and see we are disposed. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Let it destroy the reset event. } GC.KeepAlive(this); } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle and handles SecurityCritical data penContext. /// Called by PenThread.AddPenContext. /// </SecurityNote> [SecurityCritical] internal bool WorkerAddPenContext(PenContext penContext) { if (__disposed) { throw new ObjectDisposedException(null, SR.Get(SRID.Penservice_Disposed)); } Debug.Assert(penContext != null); WorkerOperationAddContext addContextOperation = new WorkerOperationAddContext(penContext, this); lock(_workerOperationLock) { _workerOperation.Add(addContextOperation); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. addContextOperation.DoneEvent.WaitOne(); addContextOperation.DoneEvent.Close(); return addContextOperation.Result; } /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle and handles SecurityCritical data penContext. /// Called by PenThread.Disable. /// </SecurityNote> [SecurityCritical] internal bool WorkerRemovePenContext(PenContext penContext) { if (__disposed) { return true; } Debug.Assert(penContext != null); WorkerOperationRemoveContext removeContextOperation = new WorkerOperationRemoveContext(penContext, this); lock(_workerOperationLock) { _workerOperation.Add(removeContextOperation); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. removeContextOperation.DoneEvent.WaitOne(); removeContextOperation.DoneEvent.Close(); return removeContextOperation.Result; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle. /// Called by PenThreadPool.WorkerGetTabletsInfo. /// </SecurityNote> [SecurityCritical] internal TabletDeviceInfo[] WorkerGetTabletsInfo() { // Set data up for this call WorkerOperationGetTabletsInfo getTablets = new WorkerOperationGetTabletsInfo(); lock(_workerOperationLock) { _workerOperation.Add(getTablets); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. getTablets.DoneEvent.WaitOne(); getTablets.DoneEvent.Close(); return getTablets.TabletDevicesInfo; } /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle and handles SecurityCritical data /// (hwnd, pimcTablet). /// Called by PenThreadPool.WorkerCreateContext. /// TreatAsSafe boundry is Stylus.EnableCore and HwndWrapperHook class /// (via HwndSource.InputFilterMessage). /// </SecurityNote> [SecurityCritical] internal PenContextInfo WorkerCreateContext(IntPtr hwnd, IPimcTablet pimcTablet) { WorkerOperationCreateContext createContextOperation = new WorkerOperationCreateContext( hwnd, pimcTablet); lock(_workerOperationLock) { _workerOperation.Add(createContextOperation); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. createContextOperation.DoneEvent.WaitOne(); createContextOperation.DoneEvent.Close(); return createContextOperation.Result; } /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle and handles SecurityCritical data pimcTablet. /// Called by PenThreadPool.WorkerRefreshCursorInfo. /// </SecurityNote> [SecurityCritical] internal StylusDeviceInfo[] WorkerRefreshCursorInfo(IPimcTablet pimcTablet) { WorkerOperationRefreshCursorInfo refreshCursorInfo = new WorkerOperationRefreshCursorInfo( pimcTablet); lock(_workerOperationLock) { _workerOperation.Add(refreshCursorInfo); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. refreshCursorInfo.DoneEvent.WaitOne(); refreshCursorInfo.DoneEvent.Close(); return refreshCursorInfo.StylusDevicesInfo; } /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle. /// Called by PenThreadPool.WorkerGetTabletInfo. /// </SecurityNote> [SecurityCritical] internal TabletDeviceInfo WorkerGetTabletInfo(uint index) { // Set up data for call WorkerOperationGetTabletInfo getTabletInfo = new WorkerOperationGetTabletInfo( index); lock(_workerOperationLock) { _workerOperation.Add(getTabletInfo); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. getTabletInfo.DoneEvent.WaitOne(); getTabletInfo.DoneEvent.Close(); return getTabletInfo.TabletDeviceInfo; } /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent), /// accesses SecurityCriticalData _pimcResetHandle and pimcTablet. /// Called by PenThreadPool.WorkerGetUpdatedTabletRect. /// </SecurityNote> [SecurityCritical] internal TabletDeviceSizeInfo WorkerGetUpdatedSizes(IPimcTablet pimcTablet) { // Set data up for call WorkerOperationWorkerGetUpdatedSizes getUpdatedSizes = new WorkerOperationWorkerGetUpdatedSizes(pimcTablet); lock(_workerOperationLock) { _workerOperation.Add(getUpdatedSizes); } // Kick thread to do this work. MS.Win32.Penimc.UnsafeNativeMethods.RaiseResetEvent(_pimcResetHandle.Value); // Wait for this work to be completed. getUpdatedSizes.DoneEvent.WaitOne(); getUpdatedSizes.DoneEvent.Close(); return getUpdatedSizes.TabletDeviceSizeInfo; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code PenContext.FirePenInRange and PenContext.FirePackets. /// Called by FireEvent and ThreadProc. /// TreatAsSafe boundry is ThreadProc. /// </SecurityNote> [SecurityCritical] void FlushCache(bool goingOutOfRange) { // Force any cached move/inairmove data to be flushed if we have any. if (_cachedMoveData != null) { // If we are going out of range and this stylus id is not currently in range // then eat these cached events (keeps from going in and out of range quickly) if (!goingOutOfRange || _cachedMovePenContext.IsInRange(_cachedMoveStylusPointerId)) { _cachedMovePenContext.FirePenInRange(_cachedMoveStylusPointerId, _cachedMoveData, _cachedMoveStartTimestamp); _cachedMovePenContext.FirePackets(_cachedMoveStylusPointerId, _cachedMoveData, _cachedMoveStartTimestamp); } _cachedMoveData = null; _cachedMovePenContext = null; _cachedMoveStylusPointerId = 0; } } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// SecurityCritical: Accesses SecurityCritical data _cachedMovePenContext. /// </SecurityNote> [SecurityCritical] bool DoCacheEvent(int evt, PenContext penContext, int stylusPointerId, int [] data, int timestamp) { // NOTE: Big assumption is that we always get other events between packets (ie don't get move // down position followed by move in up position). We don't account for that here but it should // never happen. if (evt == PenEventPackets) { // If no cache then just cache it. if (_cachedMoveData == null) { _cachedMovePenContext = penContext; _cachedMoveStylusPointerId = stylusPointerId; _cachedMoveStartTimestamp = timestamp; _cachedMoveData = data; return true; } else if (_cachedMovePenContext == penContext && stylusPointerId == _cachedMoveStylusPointerId) { int sinceBeginning = timestamp - _cachedMoveStartTimestamp; if (timestamp < _cachedMoveStartTimestamp) sinceBeginning = (Int32.MaxValue - _cachedMoveStartTimestamp) + timestamp; if (EventsFrequency > sinceBeginning) { // Add to cache data int[] data0 = _cachedMoveData; _cachedMoveData = new int [data0.Length + data.Length]; data0.CopyTo(_cachedMoveData, 0); data.CopyTo(_cachedMoveData, data0.Length); return true; } } } return false; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code FlushCache, PenContext.FirePenDown, PenContext.FirePenUp, /// PenContext.FirePenInRange, PenContext.FirePackets, PenContext.FirePenOutOfRange, PenContext.FireSystemGesture. /// Called by ThreadProc. /// TreatAsSafe boundry is ThreadProc. /// </SecurityNote> [SecurityCritical] internal void FireEvent(PenContext penContext, int evt, int stylusPointerId, int cPackets, int cbPacket, IntPtr pPackets) { // disposed? if (__disposed) { return; // Don't process this event if we're in the process of shutting down. } // marshal the data to our cache if (cbPacket % 4 != 0) { throw new InvalidOperationException(SR.Get(SRID.PenService_InvalidPacketData)); } int cItems = cPackets * (cbPacket / 4); int[] data = null; if (0 < cItems) { data = new int [cItems]; // GetDataArray(cItems); // see comment on GetDataArray Marshal.Copy(pPackets, data, 0, cItems); penContext.CheckForRectMappingChanged(data, cPackets); } else { data = null; } int timestamp = Environment.TickCount; // Deal with caching packet data. if (DoCacheEvent(evt, penContext, stylusPointerId, data, timestamp)) { return; } else { FlushCache(false); // make sure we flush cache if not caching. } // // fire it // switch (evt) { case PenEventPenDown: penContext.FirePenInRange(stylusPointerId, data, timestamp); penContext.FirePenDown(stylusPointerId, data, timestamp); break; case PenEventPenUp: penContext.FirePenInRange(stylusPointerId, data, timestamp); penContext.FirePenUp(stylusPointerId, data, timestamp); break; case PenEventPackets: penContext.FirePenInRange(stylusPointerId, data, timestamp); penContext.FirePackets(stylusPointerId, data, timestamp); break; case PenEventPenInRange: // We fire this special event just to give the app thread an early peak at // the inrange to filter out mouse moves before we get our first stylus event. penContext.FirePenInRange(stylusPointerId, null, timestamp); break; case PenEventPenOutOfRange: penContext.FirePenOutOfRange(stylusPointerId, timestamp); break; case PenEventSystem: penContext.FireSystemGesture(stylusPointerId, timestamp); break; } } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Returns a struct containing the list of TabletDevice properties for /// a given tablet device (pimcTablet). /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - handles security critical data pimcTablet /// </SecurityNote> [SecurityCritical] private static TabletDeviceInfo GetTabletInfoHelper(IPimcTablet pimcTablet) { TabletDeviceInfo tabletInfo = new TabletDeviceInfo(); tabletInfo.PimcTablet = new SecurityCriticalDataClass<IPimcTablet>(pimcTablet); pimcTablet.GetKey(out tabletInfo.Id); pimcTablet.GetName(out tabletInfo.Name); pimcTablet.GetPlugAndPlayId(out tabletInfo.PlugAndPlayId); int iTabletWidth, iTabletHeight, iDisplayWidth, iDisplayHeight; pimcTablet.GetTabletAndDisplaySize(out iTabletWidth, out iTabletHeight, out iDisplayWidth, out iDisplayHeight); tabletInfo.SizeInfo = new TabletDeviceSizeInfo(new Size(iTabletWidth, iTabletHeight), new Size(iDisplayWidth, iDisplayHeight)); int caps; pimcTablet.GetHardwareCaps(out caps); tabletInfo.HardwareCapabilities = (TabletHardwareCapabilities)caps; int deviceType; pimcTablet.GetDeviceType(out deviceType); tabletInfo.DeviceType = (TabletDeviceType)(deviceType -1); // NTRAID:WINDOWSOS#1679154-2006/06/09-WAYNEZEN, // REENTRANCY NOTE: Let a PenThread do this work to avoid reentrancy! // The IPimcTablet object is created in the pen thread. If we access it from the UI thread, // COM will set up message pumping which will cause reentrancy here. InitializeSupportedStylusPointProperties(pimcTablet, tabletInfo); tabletInfo.StylusDevicesInfo = GetStylusDevicesInfo(pimcTablet); return tabletInfo; } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Initializing the supported stylus point properties. and returns in workOperation class. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - handles security critical data pimcTablet /// </SecurityNote> [SecurityCritical] private static void InitializeSupportedStylusPointProperties(IPimcTablet pimcTablet, TabletDeviceInfo tabletInfo) { int cProps; int cButtons; int pressureIndex = -1; pimcTablet.GetPacketDescriptionInfo(out cProps, out cButtons); // Calls Unmanaged code - SecurityCritical with SUC. List<StylusPointProperty> properties = new List<StylusPointProperty>(cProps + cButtons + 3); for ( int i = 0; i < cProps; i++ ) { Guid guid; int min, max; int units; float res; pimcTablet.GetPacketPropertyInfo(i, out guid, out min, out max, out units, out res); // Calls Unmanaged code - SecurityCritical with SUC. if ( pressureIndex == -1 && guid == StylusPointPropertyIds.NormalPressure ) { pressureIndex = i; } StylusPointProperty property = new StylusPointProperty(guid, false); properties.Add(property); } for ( int i = 0; i < cButtons; i++ ) { Guid buttonGuid; pimcTablet.GetPacketButtonInfo(i, out buttonGuid); // Calls Unmanaged code - SecurityCritical with SUC. StylusPointProperty buttonProperty = new StylusPointProperty(buttonGuid, true); properties.Add(buttonProperty); } //validate we can never get X, Y at index != 0, 1 Debug.Assert(properties[StylusPointDescription.RequiredXIndex /*0*/].Id == StylusPointPropertyIds.X, "X isn't where we expect it! Fix PenImc to ask for X at index 0"); Debug.Assert(properties[StylusPointDescription.RequiredYIndex /*1*/].Id == StylusPointPropertyIds.Y, "Y isn't where we expect it! Fix PenImc to ask for Y at index 1"); // NOTE: We can't force pressure since touch digitizers may not provide this info. The following assert is bogus. //Debug.Assert(pressureIndex == -1 || pressureIndex == StylusPointDescription.RequiredPressureIndex /*2*/, // "Fix PenImc to ask for NormalPressure at index 2!"); if ( pressureIndex == -1 ) { //pressure wasn't found. Add it properties.Insert(StylusPointDescription.RequiredPressureIndex /*2*/, System.Windows.Input.StylusPointProperties.NormalPressure); } else { //this device supports pressure tabletInfo.HardwareCapabilities |= TabletHardwareCapabilities.SupportsPressure; } tabletInfo.StylusPointProperties = new ReadOnlyCollection<StylusPointProperty>(properties); tabletInfo.PressureIndex = pressureIndex; } ///////////////////////////////////////////////////////////////////////// /// <summary> /// Getting the cursor info of the stylus devices. /// </summary> /// <SecurityNote> /// Critical: - calls into unmanaged code that is SecurityCritical with SUC attribute. /// - handles security critical data pimcTablet /// </SecurityNote> [SecurityCritical] private static StylusDeviceInfo[] GetStylusDevicesInfo(IPimcTablet pimcTablet) { int cCursors; pimcTablet.GetCursorCount(out cCursors); // Calls Unmanaged code - SecurityCritical with SUC. StylusDeviceInfo[] stylusDevicesInfo = new StylusDeviceInfo[cCursors]; for ( int iCursor = 0; iCursor < cCursors; iCursor++ ) { string sCursorName; int cursorId; bool fCursorInverted; pimcTablet.GetCursorInfo(iCursor, out sCursorName, out cursorId, out fCursorInverted); // Calls Unmanaged code - SecurityCritical with SUC. int cButtons; pimcTablet.GetCursorButtonCount(iCursor, out cButtons); // Calls Unmanaged code - SecurityCritical with SUC. StylusButton[] buttons = new StylusButton[cButtons]; for ( int iButton = 0; iButton < cButtons; iButton++ ) { string sButtonName; Guid buttonGuid; pimcTablet.GetCursorButtonInfo(iCursor, iButton, out sButtonName, out buttonGuid); // Calls Unmanaged code - SecurityCritical with SUC. buttons[iButton] = new StylusButton(sButtonName, buttonGuid); } StylusButtonCollection buttonCollection = new StylusButtonCollection(buttons); stylusDevicesInfo[iCursor].CursorName = sCursorName; stylusDevicesInfo[iCursor].CursorId = cursorId; stylusDevicesInfo[iCursor].CursorInverted = fCursorInverted; stylusDevicesInfo[iCursor].ButtonCollection = buttonCollection; } return stylusDevicesInfo; } /// <SecurityNote> /// Critical - Accesses SecurityCriticalData (penContext, _penContexts, PenContext.CommHandle, /// _pimcContexts, and _handles). /// </SecurityNote> [SecurityCritical] internal bool AddPenContext(PenContext penContext) { List <PenContext> penContextRefs = new List<PenContext>(); // keep them alive while processing! int i; bool result = false; // Now go through and figure out the good entries // Need to clean up the list for gc'd references. for (i=0; i<_penContexts.Length; i++) { if (_penContexts[i].IsAlive) { PenContext pc = _penContexts[i].Target as PenContext; // We only need to ref if we have a penContext. if (pc != null) { penContextRefs.Add(pc); } } } // Now try again to see if we have room. if (penContextRefs.Count < MaxContextPerThread) { penContextRefs.Add(penContext); // add the new one to our list. // Now build up the handle array and PimcContext ref array. _pimcContexts = new IPimcContext[penContextRefs.Count]; _penContexts = new WeakReference[penContextRefs.Count]; _handles = new IntPtr[penContextRefs.Count]; for (i=0; i < penContextRefs.Count; i++) { PenContext pc = penContextRefs[i]; // We'd have hole in our array if this ever happened. Debug.Assert(pc != null && pc.CommHandle != IntPtr.Zero); _handles[i] = pc.CommHandle; // Add to array. _pimcContexts[i] = pc._pimcContext.Value; _penContexts[i] = new WeakReference(pc); pc = null; } result = true; } // Now clean up old refs and assign new array. penContextRefs.Clear(); // Make sure we remove refs! penContextRefs = null; return result; } /// <SecurityNote> /// Critical - Accesses SecurityCriticalData (penContext, _penContexts, PenContext.CommHandle, /// _pimcContexts, and _handles). /// </SecurityNote> [SecurityCritical] internal bool RemovePenContext(PenContext penContext) { List <PenContext> penContextRefs = new List<PenContext>(); // keep them alive while processing! int i; bool removed = false; // Now go through and figure out the good entries // Need to clean up the list for gc'd references. for (i=0; i<_penContexts.Length; i++) { if (_penContexts[i].IsAlive) { PenContext pc = _penContexts[i].Target as PenContext; // See if we should keep this PenContext. // We keep if not GC'd and not the removing one (except if it is // in range where we need to wait till it goes out of range). if (pc != null && (pc != penContext || pc.IsInRange(0))) { penContextRefs.Add(pc); } } } removed = !penContextRefs.Contains(penContext); // Now build up the handle array and PimcContext ref array. _pimcContexts = new IPimcContext[penContextRefs.Count]; _penContexts = new WeakReference[penContextRefs.Count]; _handles = new IntPtr[penContextRefs.Count]; for (i=0; i < penContextRefs.Count; i++) { PenContext pc = penContextRefs[i]; // We'd have hole in our array if this ever happened. Debug.Assert(pc != null && pc.CommHandle != IntPtr.Zero); _handles[i] = pc.CommHandle; // Add to array. _pimcContexts[i] = pc._pimcContext.Value; _penContexts[i] = new WeakReference(pc); pc = null; } // Now clean up old refs and assign new array. penContextRefs.Clear(); // Make sure we remove refs! penContextRefs = null; return removed; } ///////////////////////////////////////////////////////////////////// /// <SecurityNote> /// Critical - Calls SecurityCritical code (MS.Win32.Penimc.UnsafeNativeMethods.GetPenEvent, /// MS.Win32.Penimc.UnsafeNativeMethods.GetPenEventMultiple, /// MS.Win32.Penimc.UnsafeNativeMethods.DestroyResetEvent, FireEvent and FlushCache) and /// accesses SecurityCriticalData (PenContext.CommHandle and _pimcResetHandle.Value). /// It is a thread proc so it is top of stack and is created by PenThreadWorker constructor. /// </SecurityNote> [SecurityCritical] internal void ThreadProc() { Thread.CurrentThread.Name = "Stylus Input"; try { // // the rarely iterated loop // while (!__disposed) { #if TRACEPTW Debug.WriteLine(String.Format("PenThreadWorker::ThreadProc(): Update __penContextWeakRefList loop")); #endif WorkerOperation [] workerOps = null; lock(_workerOperationLock) { if (_workerOperation.Count > 0) { workerOps = _workerOperation.ToArray(); _workerOperation.Clear(); } } if (workerOps != null) { for (int j=0; j<workerOps.Length; j++) { workerOps[j].DoWork(); } workerOps = null; } // // the intense loop of dispatching events // while (true) { #if TRACEPTW Debug.WriteLine (String.Format("PenThreadWorker::ThreadProc - handle event loop")); #endif // get next event int evt; int stylusPointerId; int cPackets, cbPacket; IntPtr pPackets; int iHandleEvt; if (_handles.Length == 1) { if (!MS.Win32.Penimc.UnsafeNativeMethods.GetPenEvent( _handles[0], _pimcResetHandle.Value, out evt, out stylusPointerId, out cPackets, out cbPacket, out pPackets)) { break; } iHandleEvt = 0; } else { if (!MS.Win32.Penimc.UnsafeNativeMethods.GetPenEventMultiple( _handles.Length, _handles, _pimcResetHandle.Value, out iHandleEvt, out evt, out stylusPointerId, out cPackets, out cbPacket, out pPackets)) { break; } } if (evt != PenEventTimeout) { // dispatch the event #if TRACEPTW Debug.WriteLine (String.Format("PenThreadWorker::ThreadProc - FireEvent [evt={0}, stylusId={1}]", evt, stylusPointerId)); #endif PenContext penContext = _penContexts[iHandleEvt].Target as PenContext; // If we get an event from a GC'd PenContext then just ignore. if (penContext != null) { FireEvent(penContext, evt, stylusPointerId, cPackets, cbPacket, pPackets); penContext = null; } } else { #if TRACEPTW Debug.WriteLine (String.Format("PenThreadWorker::ThreadProc - FlushInput")); #endif FlushCache(true); // we hit the timeout, make sure that all our devices are in the correct out-of-range state // we are doing this to compinsate for drivers that send a move after they send a outofrange for (int i = 0; i < _penContexts.Length; i++) { PenContext penContext = _penContexts[i].Target as PenContext; if (penContext != null) { // we send 0 as the stulyspointerId to trigger code in PenContext::FirePenOutOfRange penContext.FirePenOutOfRange(0, Environment.TickCount); penContext = null; } } } } } } finally { // Make sure we are marked as disposed now. This keeps the // Dispose() method from doing any work. __disposed = true; // We've been disposed or hit thread abort. Release this handle before exiting. MS.Win32.Penimc.UnsafeNativeMethods.DestroyResetEvent(_pimcResetHandle.Value); // Make sure the _pimcResetHandle is still valid after Dispose is called and before // our thread exits. GC.KeepAlive(this); } } } }
using System.Collections.Generic; /* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.google.zxing.pdf417 { using BarcodeFormat = com.google.zxing.BarcodeFormat; using BinaryBitmap = com.google.zxing.BinaryBitmap; using ChecksumException = com.google.zxing.ChecksumException; using DecodeHintType = com.google.zxing.DecodeHintType; using FormatException = com.google.zxing.FormatException; using NotFoundException = com.google.zxing.NotFoundException; using Reader = com.google.zxing.Reader; using Result = com.google.zxing.Result; using ResultPoint = com.google.zxing.ResultPoint; using BitMatrix = com.google.zxing.common.BitMatrix; using DecoderResult = com.google.zxing.common.DecoderResult; using DetectorResult = com.google.zxing.common.DetectorResult; using Decoder = com.google.zxing.pdf417.decoder.Decoder; using Detector = com.google.zxing.pdf417.detector.Detector; /// <summary> /// This implementation can detect and decode PDF417 codes in an image. /// /// @author SITA Lab ([email protected]) /// </summary> public sealed class PDF417Reader : com.google.zxing.Reader { private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; private readonly Decoder decoder = new Decoder(); /// <summary> /// Locates and decodes a PDF417 code in an image. /// </summary> /// <returns> a String representing the content encoded by the PDF417 code </returns> /// <exception cref="NotFoundException"> if a PDF417 code cannot be found, </exception> /// <exception cref="FormatException"> if a PDF417 cannot be decoded </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException, com.google.zxing.ChecksumException public Result decode(BinaryBitmap image) { return decode(image, null); } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException, com.google.zxing.ChecksumException public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { DecoderResult decoderResult; ResultPoint[] points; if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.BlackMatrix); decoderResult = decoder.decode(bits); points = NO_POINTS; } else { DetectorResult detectorResult = (new Detector(image)).detect(); decoderResult = decoder.decode(detectorResult.Bits); points = detectorResult.Points; } return new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.PDF_417); } public void reset() { // do nothing } /// <summary> /// This method detects a code in a "pure" image -- that is, pure monochrome image /// which contains only an unrotated, unskewed, image of a code, with some white border /// around it. This is a specialized method that works exceptionally fast in this special /// case. /// </summary> /// <seealso cref= com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) </seealso> /// <seealso cref= com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix) </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static com.google.zxing.common.BitMatrix extractPureBits(com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException private static BitMatrix extractPureBits(BitMatrix image) { int[] leftTopBlack = image.TopLeftOnBit; int[] rightBottomBlack = image.BottomRightOnBit; if (leftTopBlack == null || rightBottomBlack == null) { throw NotFoundException.NotFoundInstance; } int moduleSize = getModuleSize(leftTopBlack, image); int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = findPatternStart(leftTopBlack[0], top, image); int right = findPatternEnd(leftTopBlack[0], top, image); int matrixWidth = (right - left + 1) / moduleSize; int matrixHeight = (bottom - top + 1) / moduleSize; if (matrixWidth <= 0 || matrixHeight <= 0) { throw NotFoundException.NotFoundInstance; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = moduleSize >> 1; top += nudge; left += nudge; // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + y * moduleSize; for (int x = 0; x < matrixWidth; x++) { if (image.get(left + x * moduleSize, iOffset)) { bits.set(x, y); } } } return bits; } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static int moduleSize(int[] leftTopBlack, com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException private static int getModuleSize(int[] leftTopBlack, BitMatrix image) { int x = leftTopBlack[0]; int y = leftTopBlack[1]; int width = image.Width; while (x < width && image.get(x, y)) { x++; } if (x == width) { throw NotFoundException.NotFoundInstance; } int moduleSize = (int)((uint)(x - leftTopBlack[0]) >> 3); // We've crossed left first bar, which is 8x if (moduleSize == 0) { throw NotFoundException.NotFoundInstance; } return moduleSize; } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static int findPatternStart(int x, int y, com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException private static int findPatternStart(int x, int y, BitMatrix image) { int width = image.Width; int start = x; // start should be on black int transitions = 0; bool black = true; while (start < width - 1 && transitions < 8) { start++; bool newBlack = image.get(start, y); if (black != newBlack) { transitions++; } black = newBlack; } if (start == width - 1) { throw NotFoundException.NotFoundInstance; } return start; } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static int findPatternEnd(int x, int y, com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException private static int findPatternEnd(int x, int y, BitMatrix image) { int width = image.Width; int end = width - 1; // end should be on black while (end > x && !image.get(end, y)) { end--; } int transitions = 0; bool black = true; while (end > x && transitions < 9) { end--; bool newBlack = image.get(end, y); if (black != newBlack) { transitions++; } black = newBlack; } if (end == x) { throw NotFoundException.NotFoundInstance; } return end; } } }
// 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! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedTargetHttpProxiesClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListTargetHttpProxiesRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) AggregatedListTargetHttpProxiesRequest request = new AggregatedListTargetHttpProxiesRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<TargetHttpProxyAggregatedList, KeyValuePair<string, TargetHttpProxiesScopedList>> response = targetHttpProxiesClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (TargetHttpProxyAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, TargetHttpProxiesScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListTargetHttpProxiesRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) AggregatedListTargetHttpProxiesRequest request = new AggregatedListTargetHttpProxiesRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<TargetHttpProxyAggregatedList, KeyValuePair<string, TargetHttpProxiesScopedList>> response = targetHttpProxiesClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, TargetHttpProxiesScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetHttpProxyAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, TargetHttpProxiesScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<TargetHttpProxyAggregatedList, KeyValuePair<string, TargetHttpProxiesScopedList>> response = targetHttpProxiesClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (TargetHttpProxyAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, TargetHttpProxiesScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<TargetHttpProxyAggregatedList, KeyValuePair<string, TargetHttpProxiesScopedList>> response = targetHttpProxiesClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, TargetHttpProxiesScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetHttpProxyAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, TargetHttpProxiesScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, TargetHttpProxiesScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteTargetHttpProxyRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) DeleteTargetHttpProxyRequest request = new DeleteTargetHttpProxyRequest { RequestId = "", TargetHttpProxy = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteTargetHttpProxyRequest, CallSettings) // Additional: DeleteAsync(DeleteTargetHttpProxyRequest, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) DeleteTargetHttpProxyRequest request = new DeleteTargetHttpProxyRequest { RequestId = "", TargetHttpProxy = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.Delete(project, targetHttpProxy); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.DeleteAsync(project, targetHttpProxy); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetTargetHttpProxyRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) GetTargetHttpProxyRequest request = new GetTargetHttpProxyRequest { TargetHttpProxy = "", Project = "", }; // Make the request TargetHttpProxy response = targetHttpProxiesClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetTargetHttpProxyRequest, CallSettings) // Additional: GetAsync(GetTargetHttpProxyRequest, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) GetTargetHttpProxyRequest request = new GetTargetHttpProxyRequest { TargetHttpProxy = "", Project = "", }; // Make the request TargetHttpProxy response = await targetHttpProxiesClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; // Make the request TargetHttpProxy response = targetHttpProxiesClient.Get(project, targetHttpProxy); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; // Make the request TargetHttpProxy response = await targetHttpProxiesClient.GetAsync(project, targetHttpProxy); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertTargetHttpProxyRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) InsertTargetHttpProxyRequest request = new InsertTargetHttpProxyRequest { TargetHttpProxyResource = new TargetHttpProxy(), RequestId = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertTargetHttpProxyRequest, CallSettings) // Additional: InsertAsync(InsertTargetHttpProxyRequest, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) InsertTargetHttpProxyRequest request = new InsertTargetHttpProxyRequest { TargetHttpProxyResource = new TargetHttpProxy(), RequestId = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, TargetHttpProxy, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; TargetHttpProxy targetHttpProxyResource = new TargetHttpProxy(); // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.Insert(project, targetHttpProxyResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, TargetHttpProxy, CallSettings) // Additional: InsertAsync(string, TargetHttpProxy, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; TargetHttpProxy targetHttpProxyResource = new TargetHttpProxy(); // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.InsertAsync(project, targetHttpProxyResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListTargetHttpProxiesRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) ListTargetHttpProxiesRequest request = new ListTargetHttpProxiesRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<TargetHttpProxyList, TargetHttpProxy> response = targetHttpProxiesClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (TargetHttpProxy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (TargetHttpProxyList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListTargetHttpProxiesRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) ListTargetHttpProxiesRequest request = new ListTargetHttpProxiesRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<TargetHttpProxyList, TargetHttpProxy> response = targetHttpProxiesClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TargetHttpProxy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetHttpProxyList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<TargetHttpProxyList, TargetHttpProxy> response = targetHttpProxiesClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (TargetHttpProxy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (TargetHttpProxyList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<TargetHttpProxyList, TargetHttpProxy> response = targetHttpProxiesClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TargetHttpProxy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((TargetHttpProxyList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TargetHttpProxy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TargetHttpProxy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TargetHttpProxy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchTargetHttpProxyRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) PatchTargetHttpProxyRequest request = new PatchTargetHttpProxyRequest { TargetHttpProxyResource = new TargetHttpProxy(), RequestId = "", TargetHttpProxy = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchTargetHttpProxyRequest, CallSettings) // Additional: PatchAsync(PatchTargetHttpProxyRequest, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) PatchTargetHttpProxyRequest request = new PatchTargetHttpProxyRequest { TargetHttpProxyResource = new TargetHttpProxy(), RequestId = "", TargetHttpProxy = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, TargetHttpProxy, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; TargetHttpProxy targetHttpProxyResource = new TargetHttpProxy(); // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.Patch(project, targetHttpProxy, targetHttpProxyResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, TargetHttpProxy, CallSettings) // Additional: PatchAsync(string, string, TargetHttpProxy, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; TargetHttpProxy targetHttpProxyResource = new TargetHttpProxy(); // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.PatchAsync(project, targetHttpProxy, targetHttpProxyResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMap</summary> public void SetUrlMapRequestObject() { // Snippet: SetUrlMap(SetUrlMapTargetHttpProxyRequest, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) SetUrlMapTargetHttpProxyRequest request = new SetUrlMapTargetHttpProxyRequest { RequestId = "", TargetHttpProxy = "", Project = "", UrlMapReferenceResource = new UrlMapReference(), }; // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.SetUrlMap(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOnceSetUrlMap(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMapAsync</summary> public async Task SetUrlMapRequestObjectAsync() { // Snippet: SetUrlMapAsync(SetUrlMapTargetHttpProxyRequest, CallSettings) // Additional: SetUrlMapAsync(SetUrlMapTargetHttpProxyRequest, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) SetUrlMapTargetHttpProxyRequest request = new SetUrlMapTargetHttpProxyRequest { RequestId = "", TargetHttpProxy = "", Project = "", UrlMapReferenceResource = new UrlMapReference(), }; // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.SetUrlMapAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOnceSetUrlMapAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMap</summary> public void SetUrlMap() { // Snippet: SetUrlMap(string, string, UrlMapReference, CallSettings) // Create client TargetHttpProxiesClient targetHttpProxiesClient = TargetHttpProxiesClient.Create(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; UrlMapReference urlMapReferenceResource = new UrlMapReference(); // Make the request lro::Operation<Operation, Operation> response = targetHttpProxiesClient.SetUrlMap(project, targetHttpProxy, urlMapReferenceResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = targetHttpProxiesClient.PollOnceSetUrlMap(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for SetUrlMapAsync</summary> public async Task SetUrlMapAsync() { // Snippet: SetUrlMapAsync(string, string, UrlMapReference, CallSettings) // Additional: SetUrlMapAsync(string, string, UrlMapReference, CancellationToken) // Create client TargetHttpProxiesClient targetHttpProxiesClient = await TargetHttpProxiesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string targetHttpProxy = ""; UrlMapReference urlMapReferenceResource = new UrlMapReference(); // Make the request lro::Operation<Operation, Operation> response = await targetHttpProxiesClient.SetUrlMapAsync(project, targetHttpProxy, urlMapReferenceResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await targetHttpProxiesClient.PollOnceSetUrlMapAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } } }
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace Elasticsearch.Client { public partial class ElasticsearchClient { ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGetString(string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetStringAsync(string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPostString(string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostStringAsync(string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = "/_validate/query"; if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(string index, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(string index, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(string index, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(string index, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(string index, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(string index, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGetString(string index, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetStringAsync(string index, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(string index, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(string index, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(string index, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(string index, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(string index, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(string index, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPostString(string index, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostStringAsync(string index, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/_validate/query", index); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(string index, string type, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(string index, string type, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(string index, string type, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(string index, string type, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGet(string index, string type, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetAsync(string index, string type, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryGetString(string index, string type, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryGetStringAsync(string index, string type, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("GET", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(string index, string type, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(string index, string type, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(string index, string type, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(string index, string type, Stream body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPost(string index, string type, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostAsync(string index, string type, byte[] body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public HttpResponseMessage IndicesValidateQueryPostString(string index, string type, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return mConnection.Execute("POST", uri, body); } ///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html"/></summary> ///<param name="index">A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices</param> ///<param name="type">A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types</param> ///<param name="body">The query definition specified with the Query DSL</param> ///<param name="options">The function to set optional url parameters.</param> public async Task<HttpResponseMessage> IndicesValidateQueryPostStringAsync(string index, string type, string body, Func<IndicesValidateQueryParameters, IndicesValidateQueryParameters> options = null) { var uri = string.Format("/{0}/{1}/_validate/query", index, type); if (options != null) { uri = options.Invoke(new IndicesValidateQueryParameters()).GetUri(uri); } return await mConnection.ExecuteAsync("POST", uri, body); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using Newtonsoft.Json; using NinjaBotCore.Models.Wow; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using NinjaBotCore.Database; using Discord; using Discord.Net; using Discord.WebSocket; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using NodaTime.TimeZones; using NinjaBotCore.Services; namespace NinjaBotCore.Modules.Wow { public class WarcraftLogs { private static CancellationTokenSource _tokenSource; private static List<Zones> _zones; private static List<Zones> _classicZones; private static List<CharClasses> _charClasses; private readonly IConfigurationRoot _config; private DiscordShardedClient _client; private readonly WclApiRequestor _api; private readonly WclApiRequestor _apiCmd; private readonly WclApiRequestor _apiClassicCmd; private readonly ILogger _logger; private static CurrentRaidTier _currentRaidTier; private readonly WclApiRequestor _apiClassic; private readonly WowApi _wowApi; public WarcraftLogs(IServiceProvider services) { _logger = services.GetRequiredService<ILogger<WarcraftLogs>>(); _client = services.GetRequiredService<DiscordShardedClient>(); _config = services.GetRequiredService<IConfigurationRoot>(); _wowApi = services.GetRequiredService<WowApi>(); try { _api = new ApiRequestorThrottle(_config["WarcraftLogsApiCmd"], baseUrl: "https://www.warcraftlogs.com:443/v1/", services.GetRequiredService<IHttpClientFactory>().CreateClient()); _apiCmd = new ApiRequestorThrottle(_config["WarcraftLogsApiCmd"], baseUrl: "https://www.warcraftlogs.com:443/v1/", services.GetRequiredService<IHttpClientFactory>().CreateClient()); _apiClassic = new ApiRequestorThrottle(_config["WarcraftLogsApi"], baseUrl: "https://classic.warcraftlogs.com:443/v1/" , services.GetRequiredService<IHttpClientFactory>().CreateClient()); _apiClassicCmd = new ApiRequestorThrottle(_config["WarcraftLogsApiCmd"], baseUrl: "https://classic.warcraftlogs.com:443/v1/", services.GetRequiredService<IHttpClientFactory>().CreateClient()); CharClasses = this.GetCharClasses().Result; Zones = this.GetZones().Result; ClassicZones = this.GetClassicZones().Result; _currentRaidTier = this.SetCurrentTier(); this.MigrateOldReports(); this.StartTimer(); } catch (Exception ex) { _logger.LogError($"Error performing class setup for WCL: {ex.Message}"); } } public static List<Zones> Zones { get { return _zones; } private set { _zones = value; } } public static List<Zones> ClassicZones { get { return _classicZones; } private set { _classicZones = value; } } public static CancellationTokenSource TokenSource { get { return _tokenSource; } set { _tokenSource = value; } } public static List<CharClasses> CharClasses { get { return _charClasses; } private set { _charClasses = value; } } public static CurrentRaidTier CurrentRaidTier { get { return _currentRaidTier; } set { _currentRaidTier = value; } } public async Task<List<CharClasses>> GetCharClasses() { return await _api.Get<List<CharClasses>>("classes?"); } public async Task<List<Zones>> GetZones() { string url = string.Empty; url = $"zones?"; return await _api.Get<List<Zones>>(url); } public async Task<List<Zones>> GetClassicZones() { string url = string.Empty; url = $"zones?"; return await _apiClassic.Get<List<Zones>>(url); } public async Task<List<Reports>> GetReportsFromGuildClassic(string guildName, string realm, string region, bool isList = false, bool flip = false) { string url = string.Empty; url = $"reports/guild/{guildName.Replace(" ", "%20")}/{realm}/{region.ToLower()}?"; if (flip) { return await _apiClassic.Get<List<Reports>>(url); } else { return await _apiClassicCmd.Get<List<Reports>>(url); } } public async Task<List<Reports>> GetReportsFromGuild(string guildName, string realm, string region, bool isList = false, bool flip = false) { string url = string.Empty; string realmSlug = string.Empty; switch (region.ToLower()) { case "us": { realmSlug = WowApi.RealmInfo.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realm.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "eu": { realmSlug = WowApi.RealmInfoEu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realm.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } } url = $"reports/guild/{guildName.Replace(" ", "%20")}/{realmSlug}/{region}?"; if (flip) { return await _api.Get<List<Reports>>(url); } else { return await _apiCmd.Get<List<Reports>>(url); } } public async Task<List<Reports>> GetReportsFromGuild(string guildName, string realm, string locale, string region, bool isList = false, bool flip = false) { string url = string.Empty; string realmSlug = string.Empty; switch (locale) { case "en_US": { realmSlug = WowApi.RealmInfo.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realm.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "ru_RU": { realmSlug = WowApi.RealmInfoRu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realm.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "en_GB": { realmSlug = WowApi.RealmInfoEu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realm.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } } url = $"reports/guild/{guildName.Replace(" ", "%20")}/{realmSlug}/{region}?"; if (flip) { return await _api.Get<List<Reports>>(url); } else { return await _apiCmd.Get<List<Reports>>(url); } } public async Task<List<Reports>> GetReportsFromGuild(string guildName, string realm, string locale, string region, string realmSlug , bool isList = false, bool flip = false) { string url = string.Empty; url = $"reports/guild/{guildName.Replace(" ", "%20")}/{realmSlug}/{region}?"; if (flip) { return await _api.Get<List<Reports>>(url); } else { return await _apiCmd.Get<List<Reports>>(url); } } public async Task<List<Reports>> GetReportsFromUser(string userName) { string url = string.Empty; url = $"reports/user/{userName.Replace(" ", "%20")}?"; return await _api.Get<List<Reports>>(url); } public async Task<List<CharParses>> GetParsesFromCharacterName(string charName, string realm, string region = "us") { string url = string.Empty; url = $"parses/character/{charName}/{realm}/{region}?"; return await _apiCmd.Get<List<CharParses>>(url); } public async Task<List<LogCharRankings>> GetRankingFromCharName(string charName, string realm, string region = "us") { string url = string.Empty; url = $"rankings/character/{charName}/{realm}/{region}?"; return await _apiCmd.Get<List<LogCharRankings>>(url); } public async Task<List<LogCharRankings>> GetRankingFromCharName(string charName, string realm, string zone, string region = "us") { string url = string.Empty; int zoneID = 0; string findString = string.Empty; switch (zone) { case "en": { findString = "Emerald Nightmare"; break; } case "tov": { findString = "Trial of Valor"; break; } case "nh": { findString = "The Nighthold"; break; } case "tos": { findString = "Tomb of Sargeras"; break; } } zoneID = Zones.Where(z => z.name == findString).Select(z => z.id).FirstOrDefault(); url = $"rankings/character/{charName}/{realm}/{region}?zone={zoneID}&"; return await _apiCmd.Get<List<LogCharRankings>>(url); } public async Task<Fights> GetFights(string code) { string url = string.Empty; url = $"report/fights/{code}?"; return await _apiCmd.Get<Fights>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounter(int encounterID, string realmName, string page = "1", string metric = "dps", int difficulty = 4, string regionName = "us") { string realmSlug = string.Empty; switch (regionName.ToLower()) { case "us": { realmSlug = WowApi.RealmInfo.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "eu": { realmSlug = WowApi.RealmInfoEu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } } string url = $"rankings/encounter/{encounterID}?metric={metric}&server={realmSlug}&region={regionName}&difficulty={difficulty}&page={page}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounter(int encounterID, string realmName, string partition, string realmSlug, string page = "1",string metric = "dps", int difficulty = 4, string regionName = "us") { WarcraftlogRankings.RankingObject l = new WarcraftlogRankings.RankingObject(); string url = $"rankings/encounter/{encounterID}?metric={metric}&server={realmSlug}&region={regionName}&difficulty={difficulty}&page={page}&partition={partition}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounterSlug(int encounterID, string realmSlug, string page = "1", string metric = "dps", int difficulty = 4, string regionName = "us") { WarcraftlogRankings.RankingObject l = new WarcraftlogRankings.RankingObject(); string url = $"rankings/encounter/{encounterID}?metric={metric}&server={realmSlug}&region={regionName}&difficulty={difficulty}&page={page}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounterSlug(int encounterID, string realmSlug, string partition, string page = "1" ,string metric = "dps", int difficulty = 4, string regionName = "us") { string url = $"rankings/encounter/{encounterID}?metric={metric}&server={realmSlug}&region={regionName}&difficulty={difficulty}&page={page}&partition={partition}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounterGuild(int encounterID, string realmName, string guildName, string partition, string page = "1", string metric = "dps", int difficulty = 4, string regionName = "us") { guildName = guildName.Replace(" ", "%20"); string realmSlug = string.Empty; switch (regionName.ToLower()) { case "us": { realmSlug = WowApi.RealmInfo.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "eu": { realmSlug = WowApi.RealmInfoEu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } } string url = $"rankings/encounter/{encounterID}?guild={guildName}&server={realmSlug}&region={regionName}&metric={metric}&difficulty={difficulty}&page={page}&partition={partition}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounterGuild(int encounterID, string realmName, string guildName, string page = "1",string metric = "dps", int difficulty = 4, string regionName = "us") { guildName = guildName.Replace(" ", "%20"); string realmSlug = string.Empty; switch (regionName.ToLower()) { case "us": { realmSlug = WowApi.RealmInfo.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "eu": { realmSlug = WowApi.RealmInfoEu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } } string url = $"rankings/encounter/{encounterID}?guild={guildName}&server={realmSlug}&region={regionName}&metric={metric}&difficulty={difficulty}&page={page}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounterGuildSlug(int encounterID, string realmSlug, string guildName, string page = "1", string metric = "dps", int difficulty = 4, string regionName = "us") { guildName = guildName.Replace(" ", "%20"); string url = $"rankings/encounter/{encounterID}?guild={guildName}&server={realmSlug}&region={regionName}&metric={metric}&difficulty={difficulty}&page={page}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounterGuildSlug(int encounterID, string realmSlug, string partition, string guildName, string page = "1", string metric = "dps", int difficulty = 4, string regionName = "us") { guildName = guildName.Replace(" ", "%20"); string url = $"rankings/encounter/{encounterID}?guild={guildName}&server={realmSlug}&region={regionName}&metric={metric}&difficulty={difficulty}&page={page}&partition={partition}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public async Task<WarcraftlogRankings.RankingObject> GetRankingsByEncounter(int encounterID, string realmName, string partition, string page = "1", string metric = "dps", int difficulty = 4, string regionName = "us") { string realmSlug = string.Empty; switch (regionName.ToLower()) { case "us": { realmSlug = WowApi.RealmInfo.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } case "eu": { realmSlug = WowApi.RealmInfoEu.realms.Where(r => r.name.Replace("'","").ToLower().Contains(realmName.ToLower())).Select(s => s.slug).FirstOrDefault(); break; } } string url = $"rankings/encounter/{encounterID}?metric={metric}&server={realmSlug}&region={regionName}&difficulty={difficulty}&page={page}&partition={partition}&"; return await _apiCmd.Get<WarcraftlogRankings.RankingObject>(url); } public DateTime UnixTimeStampToDateTime(long unixTimeStamp) { // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToUniversalTime(); return dtDateTime; } public DateTime ConvTimeToLocalTimezone(DateTime time, string timezone = "America/Los_Angeles") { TimeZoneInfo tzInfo; DateTime date = new DateTime(); try { tzInfo = TimeZoneInfo.FindSystemTimeZoneById(timezone); date = TimeZoneInfo.ConvertTimeFromUtc(time, tzInfo); } catch (TimeZoneNotFoundException) { var map = TzdbDateTimeZoneSource.Default.WindowsMapping.MapZones.FirstOrDefault(x => x.TzdbIds.Any(z => z.Equals(timezone, StringComparison.OrdinalIgnoreCase))); date = TimeZoneInfo.ConvertTimeFromUtc(time, TimeZoneInfo.FindSystemTimeZoneById(map.WindowsId)); } finally { if (date == DateTime.MinValue) { date = TimeZoneInfo.ConvertTimeFromUtc(time, TimeZoneInfo.Local); } } return date; } public async Task WarcraftLogsTimer(Action action, CancellationToken token) { try { while (!token.IsCancellationRequested) { action(); await Task.Delay(TimeSpan.FromSeconds(1800),token); } } catch (TaskCanceledException ex) { } } public async Task StartTimer() { TokenSource = new CancellationTokenSource(); var timerAction = new Action(CheckForNewLogs); await WarcraftLogsTimer(timerAction, TokenSource.Token); } public async Task StopTimer() { TokenSource.Cancel(); } async void CheckForNewLogs() { var _ = Task.Run(async () => { try { System.Console.WriteLine("Checking for logs..."); List<WowGuildAssociations> guildList = null; List<LogMonitoring> logWatchList = null; List<WowClassicGuild> cGuildList = null; bool flip = true; try { using (var db = new NinjaBotEntities()) { guildList = db.WowGuildAssociations.ToList(); logWatchList = db.LogMonitoring.ToList(); cGuildList = db.WowClassicGuild.ToList(); } } catch (Exception ex) { _logger.LogInformation($"Error getting guild/logwatch list -> [{ex.Message}]"); } if (guildList != null) { _logger.LogInformation("Starting WCL Auto Posting..."); foreach (var guild in guildList) { await PerformLogCheck(logWatchList, flip, guild).ConfigureAwait(false); } foreach (var guild in cGuildList) { await PerformLogCheck(logWatchList, flip, guild).ConfigureAwait(false); } _logger.LogInformation("Finished WCL Auto Posting..."); } } finally { System.Console.WriteLine("done checking for logs"); await this.StopTimer(); Thread.Sleep(TimeSpan.FromSeconds(130)); await this.StartTimer(); } }); } private async Task PerformLogCheck(List<LogMonitoring> logWatchList, bool flip, WowGuildAssociations guild) { try { var watchGuild = logWatchList.Where(w => w.ServerId == guild.ServerId).FirstOrDefault(); if (watchGuild != null) { if (watchGuild.MonitorLogs) { List<Reports> logs = null; if (!string.IsNullOrEmpty(guild.LocalRealmSlug)) { logs = await GetReportsFromGuild(guildName: guild.WowGuild, locale: guild.Locale, realm: guild.WowRealm.Replace("'", ""), realmSlug: guild.LocalRealmSlug, region: guild.WowRegion, isList: true, flip: flip); } else if (!string.IsNullOrEmpty(guild.Locale)) { logs = await GetReportsFromGuild(guildName: guild.WowGuild, realm: guild.WowRealm.Replace("'", ""), region: guild.WowRegion, isList: true, locale: guild.Locale, flip: flip); } else { logs = await GetReportsFromGuild(guildName: guild.WowGuild, realm: guild.WowRealm.Replace("'", ""), region: guild.WowRegion, isList: true, flip: flip); } if (flip) { flip = false; } else { flip = true; } if (logs != null && logs.Count > 0) { var latestLog = logs[0]; DateTime startTime = UnixTimeStampToDateTime(latestLog.start); //System.Console.WriteLine($"local id [{watchGuild.RetailReportId}] -> remote id [{latestLog.id}] for [{guild.WowGuild}] on [{guild.WowRealm}]."); if (latestLog.id != watchGuild.RetailReportId) { using (var db = new NinjaBotEntities()) { var latestForGuild = db.LogMonitoring.Where(l => l.ServerId == guild.ServerId).FirstOrDefault(); latestForGuild.LatestLogRetail = startTime; latestForGuild.RetailReportId = latestLog.id; await db.SaveChangesAsync(); } ISocketMessageChannel channel = _client.GetChannel((ulong)watchGuild.ChannelId) as ISocketMessageChannel; if (channel != null) { var tz = GetLocalTz(guild); DateTime logStart = GetLocalTime(latestLog, tz); _logger.LogInformation($"Posting log for [{guild.WowGuild}] on [{guild.WowRealm}] for server [{guild.ServerName}]"); var embed = new EmbedBuilder(); embed.Title = $"New log found for [{guild.WowGuild}]!"; StringBuilder sb = new StringBuilder(); sb.AppendLine($"[__**{latestLog.title}** **/** **{latestLog.zoneName}**__]({latestLog.reportURL})"); sb.AppendLine($"\t:timer: Start time: **{logStart}**"); sb.AppendLine($"\t:mag: [WoWAnalyzer](https://wowanalyzer.com/report/{latestLog.id}) | :sob: [WipeFest](https://www.wipefest.net/report/{latestLog.id}) "); sb.AppendLine($"\t:pencil2: Created by [**{latestLog.owner}**]"); sb.AppendLine(); embed.Description = sb.ToString(); embed.WithColor(new Color(0, 0, 255)); await channel.SendMessageAsync("", false, embed.Build()); } } } } } } catch (Exception ex) { //_logger.LogError($"Error checking for logs [{guild.WowGuild}]:[{guild.WowRealm}]:[{guild.WowRealm}]! -> [{ex.Message}]"); } } private DateTime GetLocalTime(Reports latestLog, string tz = null) { DateTime logStart = DateTime.UtcNow; if (!string.IsNullOrEmpty(tz)) { logStart = ConvTimeToLocalTimezone(UnixTimeStampToDateTime(latestLog.start), tz); } else { logStart = ConvTimeToLocalTimezone(UnixTimeStampToDateTime(latestLog.start)); } return logStart; } private string GetLocalTz(WowGuildAssociations guild) { var locale = guild.Locale; var realmInfo = new WowRealm.Realm(); var tz = string.Empty; if (!string.IsNullOrEmpty(locale)) { switch (locale) { case "en_US": { realmInfo = WowApi.RealmInfo.realms.FirstOrDefault(r => r.name == guild.WowRealm); break; } case "en_GB": { realmInfo = WowApi.RealmInfoEu.realms.FirstOrDefault(r => r.name == guild.WowRealm); break; } case "ru_RU": { realmInfo = WowApi.RealmInfoRu.realms.FirstOrDefault(r => r.name == guild.WowRealm); break; } } } if (realmInfo != null && !string.IsNullOrEmpty(realmInfo.timezone)) { tz = realmInfo.timezone; } return tz; } private async Task PerformLogCheck(List<LogMonitoring> logWatchList, bool flip, WowClassicGuild guild) { try { var watchGuild = logWatchList.Where(w => w.ServerId == guild.ServerId).FirstOrDefault(); if (watchGuild != null) { if (watchGuild.MonitorLogs) { List<Reports> logs = null; logs = await GetReportsFromGuildClassic(guildName: guild.WowGuild, realm: guild.WowRealm.Replace("'", ""), region: guild.WowRegion, isList: true, flip: flip); if (flip) { flip = false; } else { flip = true; } if (logs != null) { var latestLog = logs[0]; DateTime startTime = UnixTimeStampToDateTime(latestLog.start); //System.Console.WriteLine($"local id [{watchGuild.ClassicReportId}] -> remote id [{latestLog.id}] for [{guild.WowGuild}] on [{guild.WowRealm}]."); if (latestLog.id != watchGuild.ClassicReportId) { using (var db = new NinjaBotEntities()) { var latestForGuild = db.LogMonitoring.Where(l => l.ServerId == guild.ServerId).FirstOrDefault(); latestForGuild.LatestLogClassic = startTime; latestForGuild.ClassicReportId = latestLog.id; await db.SaveChangesAsync(); } ISocketMessageChannel channel = _client.GetChannel((ulong)watchGuild.ChannelId) as ISocketMessageChannel; if (channel != null) { _logger.LogInformation($"Posting log for [{guild.WowGuild}] on [{guild.WowRealm}] for server [{guild.ServerName}]"); var embed = new EmbedBuilder(); embed.Title = $"New log found for [{guild.WowGuild}]!"; StringBuilder sb = new StringBuilder(); sb.AppendLine($"[__**{latestLog.title}** **/** **{latestLog.zoneName}**__]({latestLog.reportURL})"); sb.AppendLine($"\t:timer: Start time: **{UnixTimeStampToDateTime(latestLog.start).ToLocalTime()}**"); sb.AppendLine($"\t:pencil2: Created by [**{latestLog.owner}**]"); sb.AppendLine(); embed.Description = sb.ToString(); embed.WithColor(new Color(0, 0, 255)); await channel.SendMessageAsync("", false, embed.Build()); } } } } } } catch (Exception ex) { //_logger.LogError($"Error checking for logs [{guild.WowGuild}]:[{guild.WowRealm}]:[{guild.WowRealm}]! -> [{ex.Message}]"); } } private CurrentRaidTier SetCurrentTier() { var currentTier = new CurrentRaidTier(); using (var db = new NinjaBotEntities()) { var tierFromDb = db.CurrentRaidTier.FirstOrDefault(); if (tierFromDb != null) { currentTier = tierFromDb; } } return currentTier; } private void MigrateOldReports() { List<LogMonitoring> logWatchList = null; try { using (var db = new NinjaBotEntities()) { logWatchList = db.LogMonitoring.ToList(); foreach (var entry in logWatchList.Where(r => !string.IsNullOrEmpty(r.ReportId))) { var oldReportId = entry.ReportId; var oldLatestDate = entry.LatestLog; entry.LatestLogRetail = oldLatestDate; entry.RetailReportId = oldReportId; entry.ReportId = string.Empty; System.Console.WriteLine($"Updating [{entry.ServerName}]..."); db.SaveChanges(); } } } catch (Exception ex) { //_logger.LogError($"Error getting log watch list -> [{ex.Message}]"); } } } }
using System; using System.Collections; using System.ComponentModel; using System.Security; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using umbraco.BusinessLogic.Actions; using umbraco.presentation.LiveEditing.Modules.ItemEditing; namespace umbraco.presentation.templateControls { /// <summary> /// Control that renders an Umbraco item on a page. /// </summary> [DefaultProperty("Field")] [ToolboxData("<{0}:Item runat=\"server\"></{0}:Item>")] [Designer("umbraco.presentation.templateControls.ItemDesigner, umbraco")] public class Item : CompositeControl { #region Private Fields /// <summary>The item's unique ID on the page.</summary> private readonly int m_ItemId; public AttributeCollectionAdapter LegacyAttributes; #endregion #region Public Control Properties /// <summary> /// Gets or sets the field name. /// </summary> /// <value>The field name.</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string Field { get { return (string)ViewState["Field"] ?? String.Empty; } set { ViewState["Field"] = value; } } /// <summary> /// Gets or sets the node id expression. /// </summary> /// <value>The node id expression.</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string NodeId { get { return (string)ViewState["NodeId"] ?? String.Empty; } set { ViewState["NodeId"] = value; } } /// <summary> /// Gets or sets the text to display if the control is empty. /// </summary> /// <value>The text to display if the control is empty.</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string TextIfEmpty { get { return (string)ViewState["TextIfEmpty"] ?? String.Empty; } set { ViewState["TextIfEmpty"] = value; } } /// <summary> /// Gets or sets the XPath expression used for the inline XSLT transformation. /// </summary> /// <value> /// The XPath expression, or an empty string to disable XSLT transformation. /// The code <c>{0}</c> is used as a placeholder for the rendered field contents. /// </value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public string Xslt { get { return (string)ViewState["Xslt"] ?? String.Empty; } set { ViewState["Xslt"] = value; } } /// <summary> /// Gets or sets a value indicating whether XML entity escaping of the XSLT transformation output is disabled. /// </summary> /// <value><c>true</c> HTML escaping is disabled; otherwise, <c>false</c> (default).</value> /// <remarks> /// This corresponds value to the <c>disable-output-escaping</c> parameter /// of the XSLT <c>value-of</c> element. /// </remarks> [Bindable(true)] [Category("Umbraco")] [DefaultValue(false)] [Localizable(true)] public bool XsltDisableEscaping { get { return ViewState["XsltEscape"] == null ? false : (bool)ViewState["XsltEscape"]; } set { ViewState["XsltEscape"] = value; } } [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public bool DebugMode { get { return ((ViewState["DebugMode"] == null) ? false : (bool)ViewState["DebugMode"]); } set { ViewState["DebugMode"] = value; } } /// <summary> /// Gets or sets a value indicating whether Live Editing is disabled for this field. /// </summary> /// <value><c>true</c> if you manually wish to disable Live Editing for this field; otherwise, <c>false</c> (default is false).</value> [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] [Localizable(true)] public bool LiveEditingDisabled { get { return ((ViewState["LiveEditingDisabled"] == null) ? false : (bool)ViewState["LiveEditingDisabled"]); } set { ViewState["LiveEditingDisabled"] = value; } } public ItemRenderer Renderer { get; set; } #endregion #region Public Readonly Properties /// <summary> /// Gets the item's unique ID on the page. /// </summary> /// <value>The item id.</value> public int ItemId { get { return m_ItemId; } } /// <summary> /// Gets a value indicating whether this control can be used in Live Editing mode. /// Checks whether live editing has not been disabled, /// the control is inside a form tag, /// the field is editable /// and the user has sufficient permissions. /// </summary> /// <value><c>true</c> if live editing is useLiveEditing; otherwise, <c>false</c>.</value> public bool CanUseLiveEditing { get { return !LiveEditingDisabled && IsInsideFormTag() && FieldSupportsLiveEditing() && FieldEditableWithUserPermissions(); } } /// <summary> /// Gets the Umbraco page elements. /// </summary> /// <value>The Umbraco page elements.</value> public Hashtable PageElements { get { return Context.Items["pageElements"] as Hashtable; } } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="Item"/> class. /// </summary> public Item() { // create page unique ID for this item object lastItemId = HttpContext.Current.Items["LiveEditing_LastItemId"]; m_ItemId = (lastItemId != null ? (int)lastItemId + 1 : 1); HttpContext.Current.Items["LiveEditing_LastItemId"] = m_ItemId; Renderer = !UmbracoContext.Current.LiveEditingContext.Enabled ? ItemRenderer.Instance : LiveEditingItemRenderer.Instance; } #endregion #region Overriden Control Methods /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnInit(EventArgs e) { Attributes.Add("field", Field); LegacyAttributes = new AttributeCollectionAdapter(Attributes); Renderer.Init(this); base.OnInit(e); } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { Renderer.Load(this); base.OnLoad(e); } /// <summary> /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl"/> content /// to the specified <see cref="T:System.Web.UI.HtmlTextWriter"/> object, for display on the client. /// </summary> /// <param name="writer"> /// An <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents /// the output stream to render HTML content on the client. /// </param> protected override void Render(HtmlTextWriter writer) { Renderer.Render(this, writer); } #endregion #region Helper Functions /// <summary> /// Gets the parsed node id. As a nodeid on a item element can be null, an integer or even a squarebracket syntax, this helper method /// is handy for getting the exact parsed nodeid back. /// </summary> /// <returns>The parsed nodeid, the id of the current page OR null if it's not specified</returns> public int? GetParsedNodeId() { if (!String.IsNullOrEmpty(NodeId)) { string tempNodeId = helper.parseAttribute(PageElements, NodeId); int nodeIdInt = 0; if (int.TryParse(tempNodeId, out nodeIdInt)) { return nodeIdInt; } } else if (PageElements["pageID"] != null) { return int.Parse(PageElements["pageID"].ToString()); } return null; } /// <summary> /// Gets a value indicating whether this control is inside the form tag. /// </summary> /// <returns><c>true</c> if this control is inside the form tag; otherwise, <c>false</c>.</returns> protected virtual bool IsInsideFormTag() { // check if this control has an ancestor that is the page form for (Control parent = this.Parent; parent != null; parent = parent.Parent) if (parent == Page.Form) return true; return false; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return String.Format("Item {0} (NodeId '{1}' : {2})", ItemId, NodeId, Field); } #endregion #region Field Information Functions // 27/08/2008 Ruben Verborgh: This functionality should really be inside some kind of super Field class, // which could be anything from a property to a dictionary item. // However, I don't think we should do this in the current Umbraco generation. /// <summary> /// Gets a value indicating whether Live Editing is useLiveEditing on this field. /// Certain functionalities of the item field makes it hard to /// support Live Editing, like dictionary items and recursive values. /// </summary> /// <value> /// <c>true</c> if Live Editing is useLiveEditing; otherwise, <c>false</c>. /// </value> protected virtual bool FieldSupportsLiveEditing() { return !(FieldIsRercursive() || FieldIsDictionaryItem()); } /// <summary> /// Determines whether the field is a dictionary item. /// </summary> /// <returns><c>true</c> if the field is a dictionary item; otherwise, <c>false</c>.</returns> protected virtual bool FieldIsDictionaryItem() { return helper.FindAttribute(new AttributeCollectionAdapter(Attributes), "field").StartsWith("#"); } /// <summary> /// Determines whether the field is recursive. /// </summary> /// <returns><c>true</c> if the field is recursive; otherwise, <c>false</c>.</returns> protected virtual bool FieldIsRercursive() { return helper.FindAttribute(new AttributeCollectionAdapter(Attributes), "recursive") == "true"; } /// <summary> /// Determines whether field uses the API to lookup the value /// (if a NodeId attribute is specified and is different from the current page id). /// </summary> /// <returns><c>true</c> if API lookup is used; otherwise, <c>false</c>.</returns> [Obsolete("Method never implemented", true)] protected virtual bool FieldIsApiLookup() { // TODO: remove false and add security return false; } /// <summary> /// Gets a value indicating whether the current item is editable by the current user. /// </summary> /// <value><c>true</c> if the current item is editable by the current user; otherwise, <c>false</c>.</value> protected virtual bool FieldEditableWithUserPermissions() { BusinessLogic.User u = helper.GetCurrentUmbracoUser(); return u != null && u.GetPermissions(PageElements["path"].ToString()).Contains(ActionUpdate.Instance.Letter.ToString()); } #endregion } public class ItemDesigner : System.Web.UI.Design.ControlDesigner { private Item m_control; public override string GetDesignTimeHtml() { m_control = this.Component as Item; return returnMarkup(String.Format("Getting '{0}'", m_control.Field)); } private string returnMarkup(string message) { return "<span style=\"background-color: #DDD; padding: 2px;\">" + message + "</span>"; } protected override string GetErrorDesignTimeHtml(Exception e) { if (this.Component != null) { m_control = this.Component as Item; } if (m_control != null && !String.IsNullOrEmpty(m_control.Field)) { return returnMarkup(String.Format("Getting '{0}'", m_control.Field)); } else { return returnMarkup("<em>Please add a Field property</em>"); } } } }
// 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.Net.Http; using System.Net; using System.Collections.Generic; namespace System.Net.Http { internal sealed class HttpEnvironmentProxyCredentials : ICredentials { // Wrapper class for cases when http and https has different authentication. private readonly NetworkCredential _httpCred; private readonly NetworkCredential _httpsCred; private readonly Uri _httpProxy; private readonly Uri _httpsProxy; public HttpEnvironmentProxyCredentials(Uri httpProxy, NetworkCredential httpCred, Uri httpsProxy, NetworkCredential httpsCred) { _httpCred = httpCred; _httpsCred = httpsCred; _httpProxy = httpProxy; _httpsProxy = httpsProxy; } public NetworkCredential GetCredential(Uri uri, string authType) { if (uri == null) { return null; } return uri.Equals(_httpProxy) ? _httpCred : uri.Equals(_httpsProxy) ? _httpsCred : null; } public static HttpEnvironmentProxyCredentials TryCreate(Uri httpProxy, Uri httpsProxy) { NetworkCredential httpCred = null; NetworkCredential httpsCred = null; if (httpProxy != null) { httpCred = GetCredentialsFromString(httpProxy.UserInfo); } if (httpsProxy != null) { httpsCred = GetCredentialsFromString(httpsProxy.UserInfo); } if (httpCred == null && httpsCred == null) { return null; } return new HttpEnvironmentProxyCredentials(httpProxy, httpCred, httpsProxy, httpsCred); } /// <summary> /// Converts string containing user:password to NetworkCredential object /// </summary> private static NetworkCredential GetCredentialsFromString(string value) { if (string.IsNullOrWhiteSpace(value)) { return null; } value = Uri.UnescapeDataString(value); string password = ""; string domain = null; int idx = value.IndexOf(':'); if (idx != -1) { password = value.Substring(idx+1); value = value.Substring(0, idx); } idx = value.IndexOf('\\'); if (idx != -1) { domain = value.Substring(0, idx); value = value.Substring(idx+1); } return new NetworkCredential(value, password, domain); } } internal sealed class HttpEnvironmentProxy : IWebProxy { private const string EnvAllProxyUC = "ALL_PROXY"; private const string EnvAllProxyLC = "all_proxy"; private const string EnvHttpProxyLC = "http_proxy"; private const string EnvHttpsProxyLC = "https_proxy"; private const string EnvHttpsProxyUC = "HTTPS_PROXY"; private const string EnvNoProxyLC = "no_proxy"; private Uri _httpProxyUri; // String URI for HTTP requests private Uri _httpsProxyUri; // String URI for HTTPS requests private string[] _bypass = null;// list of domains not to proxy private ICredentials _credentials; public static bool TryCreate(out IWebProxy proxy) { // Get environmental variables. Protocol specific take precedence over // general all_*, lower case variable has precedence over upper case. // Note that curl uses HTTPS_PROXY but not HTTP_PROXY. // For http, only http_proxy and generic variables are used. Uri httpProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpProxyLC)); Uri httpsProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpsProxyLC)) ?? GetUriFromString(Environment.GetEnvironmentVariable(EnvHttpsProxyUC)); if (httpProxy == null || httpsProxy == null) { Uri allProxy = GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyLC)) ?? GetUriFromString(Environment.GetEnvironmentVariable(EnvAllProxyUC)); if (httpProxy == null) { httpProxy = allProxy; } if (httpsProxy == null) { httpsProxy = allProxy; } } // Do not instantiate if nothing is set. // Caller may pick some other proxy type. if (httpProxy == null && httpsProxy == null) { proxy = null; return false; } proxy = new HttpEnvironmentProxy(httpProxy, httpsProxy, Environment.GetEnvironmentVariable(EnvNoProxyLC)); return true; } private HttpEnvironmentProxy(Uri httpProxy, Uri httpsProxy, string bypassList) { _httpProxyUri = httpProxy; _httpsProxyUri = httpsProxy; _credentials = HttpEnvironmentProxyCredentials.TryCreate(httpProxy, httpsProxy); if (!string.IsNullOrWhiteSpace(bypassList)) { string[] list = bypassList.Split(','); List<string> tmpList = new List<string>(list.Length); foreach (string value in list) { string tmp = value.Trim(); if (tmp.Length > 0) { tmpList.Add(tmp); } } if (tmpList.Count > 0) { _bypass = tmpList.ToArray(); } } } /// <summary> /// This function will evaluate given string and it will try to convert /// it to Uri object. The string could contain URI fragment, IP address and port /// tuple or just IP address or name. It will return null if parsing fails. /// </summary> private static Uri GetUriFromString(string value) { if (string.IsNullOrEmpty(value)) { return null; } if (value.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { value = value.Substring(7); } string user = null; string password = null; ushort port = 80; string host = null; // Check if there is authentication part with user and possibly password. // Curl accepts raw text and that may break URI parser. int separatorIndex = value.LastIndexOf('@'); if (separatorIndex != -1) { string auth = value.Substring(0, separatorIndex); // The User and password may or may not be URL encoded. // Curl seems to accept both. To match that, // we do opportunistic decode and we use original string if it fails. try { auth = Uri.UnescapeDataString(auth); } catch { }; value = value.Substring(separatorIndex + 1); separatorIndex = auth.IndexOf(':'); if (separatorIndex == -1) { user = auth; } else { user = auth.Substring(0, separatorIndex); password = auth.Substring(separatorIndex + 1); } } int ipV6AddressEnd = value.IndexOf(']'); separatorIndex = value.LastIndexOf(':'); // No ':' or it is part of IPv6 address. if (separatorIndex == -1 || (ipV6AddressEnd != -1 && separatorIndex < ipV6AddressEnd)) { host = value; } else { host = value.Substring(0, separatorIndex); int endIndex = separatorIndex + 1; // Strip any trailing characters after port number. while (endIndex < value.Length) { if (!char.IsDigit(value[endIndex])) { break; } endIndex += 1; } if (!ushort.TryParse(value.AsSpan(separatorIndex + 1, endIndex - separatorIndex - 1), out port)) { return null; } } try { UriBuilder ub = new UriBuilder("http", host, port); if (user != null) { ub.UserName = Uri.EscapeDataString(user); } if (password != null) { ub.Password = Uri.EscapeDataString(password); } return ub.Uri; } catch { }; return null; } /// <summary> /// This function returns true if given Host match bypass list. /// Note, that the list is common for http and https. /// </summary> private bool IsMatchInBypassList(Uri input) { if (_bypass != null) { foreach (string s in _bypass) { if (s[0] == '.') { // This should match either domain it self or any subdomain or host // .foo.com will match foo.com it self or *.foo.com if ((s.Length - 1) == input.Host.Length && string.Compare(s, 1, input.Host, 0, input.Host.Length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } else if (input.Host.EndsWith(s, StringComparison.OrdinalIgnoreCase)) { return true; } } else { if (string.Equals(s, input.Host, StringComparison.OrdinalIgnoreCase)) { return true; } } } } return false; } /// <summary> /// Gets the proxy URI. (iWebProxy interface) /// </summary> public Uri GetProxy(Uri uri) { return uri.Scheme == Uri.UriSchemeHttp ? _httpProxyUri : _httpsProxyUri; } /// <summary> /// Checks if URI is subject to proxy or not. /// </summary> public bool IsBypassed(Uri uri) { return GetProxy(uri) == null ? true : IsMatchInBypassList(uri); } public ICredentials Credentials { get { return _credentials; } set { throw new NotSupportedException(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for EndpointsOperations. /// </summary> public static partial class EndpointsOperationsExtensions { /// <summary> /// Lists existing CDN endpoints. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> public static Microsoft.Rest.Azure.IPage<Endpoint> ListByProfile(this IEndpointsOperations operations, string resourceGroupName, string profileName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).ListByProfileAsync(resourceGroupName, profileName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists existing CDN endpoints. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Endpoint>> ListByProfileAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByProfileWithHttpMessagesAsync(resourceGroupName, profileName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an existing CDN endpoint with the specified endpoint name under the /// specified subscription, resource group and profile. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static Endpoint Get(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).GetAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets an existing CDN endpoint with the specified endpoint name under the /// specified subscription, resource group and profile. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> GetAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpoint'> /// Endpoint properties /// </param> public static Endpoint Create(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).CreateAsync(resourceGroupName, profileName, endpointName, endpoint), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpoint'> /// Endpoint properties /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> CreateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpoint, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpoint'> /// Endpoint properties /// </param> public static Endpoint BeginCreate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginCreateAsync(resourceGroupName, profileName, endpointName, endpoint), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpoint'> /// Endpoint properties /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> BeginCreateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, Endpoint endpoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpoint, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates an existing CDN endpoint with the specified parameters. Only tags /// and OriginHostHeader can be updated after creating an endpoint. To update /// origins, use the Update Origin operation. To update custom domains, use /// the Update Custom Domain operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpointUpdateProperties'> /// Endpoint update properties /// </param> public static Endpoint Update(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).UpdateAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates an existing CDN endpoint with the specified parameters. Only tags /// and OriginHostHeader can be updated after creating an endpoint. To update /// origins, use the Update Origin operation. To update custom domains, use /// the Update Custom Domain operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpointUpdateProperties'> /// Endpoint update properties /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> UpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates an existing CDN endpoint with the specified parameters. Only tags /// and OriginHostHeader can be updated after creating an endpoint. To update /// origins, use the Update Origin operation. To update custom domains, use /// the Update Custom Domain operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpointUpdateProperties'> /// Endpoint update properties /// </param> public static Endpoint BeginUpdate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginUpdateAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates an existing CDN endpoint with the specified parameters. Only tags /// and OriginHostHeader can be updated after creating an endpoint. To update /// origins, use the Update Origin operation. To update custom domains, use /// the Update Custom Domain operation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='endpointUpdateProperties'> /// Endpoint update properties /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> BeginUpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, EndpointUpdateParameters endpointUpdateProperties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, endpointUpdateProperties, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static void Delete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).DeleteAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes an existing CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static void BeginDelete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginDeleteAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing CDN endpoint with the specified parameters. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task BeginDeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Starts an existing stopped CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static Endpoint Start(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).StartAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Starts an existing stopped CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> StartAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.StartWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Starts an existing stopped CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static Endpoint BeginStart(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginStartAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Starts an existing stopped CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> BeginStartAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Stops an existing running CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static Endpoint Stop(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).StopAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stops an existing running CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> StopAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.StopWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Stops an existing running CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static Endpoint BeginStop(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginStopAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stops an existing running CDN endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Endpoint> BeginStopAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Forcibly purges CDN endpoint content. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be purged. Can describe a file path or a wild /// card directory. /// </param> public static void PurgeContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).PurgeContentAsync(resourceGroupName, profileName, endpointName, contentPaths), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Forcibly purges CDN endpoint content. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be purged. Can describe a file path or a wild /// card directory. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PurgeContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PurgeContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Forcibly purges CDN endpoint content. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be purged. Can describe a file path or a wild /// card directory. /// </param> public static void BeginPurgeContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginPurgeContentAsync(resourceGroupName, profileName, endpointName, contentPaths), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Forcibly purges CDN endpoint content. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be purged. Can describe a file path or a wild /// card directory. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task BeginPurgeContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.BeginPurgeContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Forcibly pre-loads CDN endpoint content. Available for Verizon Profiles. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be loaded. Should describe a file path. /// </param> public static void LoadContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).LoadContentAsync(resourceGroupName, profileName, endpointName, contentPaths), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Forcibly pre-loads CDN endpoint content. Available for Verizon Profiles. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be loaded. Should describe a file path. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task LoadContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.LoadContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Forcibly pre-loads CDN endpoint content. Available for Verizon Profiles. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be loaded. Should describe a file path. /// </param> public static void BeginLoadContent(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).BeginLoadContentAsync(resourceGroupName, profileName, endpointName, contentPaths), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Forcibly pre-loads CDN endpoint content. Available for Verizon Profiles. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='contentPaths'> /// The path to the content to be loaded. Should describe a file path. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task BeginLoadContentAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Collections.Generic.IList<string> contentPaths, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.BeginLoadContentWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, contentPaths, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Validates a custom domain mapping to ensure it maps to the correct CNAME /// in DNS. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> public static ValidateCustomDomainOutput ValidateCustomDomain(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, string hostName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).ValidateCustomDomainAsync(resourceGroupName, profileName, endpointName, hostName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Validates a custom domain mapping to ensure it maps to the correct CNAME /// in DNS. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='hostName'> /// The host name of the custom domain. Must be a domain name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ValidateCustomDomainOutput> ValidateCustomDomainAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointName, string hostName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ValidateCustomDomainWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, hostName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists existing CDN endpoints. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<Endpoint> ListByProfileNext(this IEndpointsOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IEndpointsOperations)s).ListByProfileNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists existing CDN endpoints. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<Endpoint>> ListByProfileNextAsync(this IEndpointsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByProfileNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * Copyright (c) 2006-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using OpenMetaverse.Packets; using OpenMetaverse.Interfaces; using OpenMetaverse.Messages.Linden; using System.Collections.Generic; namespace OpenMetaverse { /// <summary>Describes tasks returned in LandStatReply</summary> public class EstateTask { public Vector3 Position; public float Score; public float MonoScore; public UUID TaskID; public uint TaskLocalID; public string TaskName; public string OwnerName; } /// <summary> /// Estate level administration and utilities /// </summary> public class EstateTools { private GridClient Client; /// <summary>Textures for each of the four terrain height levels</summary> public GroundTextureSettings GroundTextures; /// <summary>Upper/lower texture boundaries for each corner of the sim</summary> public GroundTextureHeightSettings GroundTextureLimits; /// <summary> /// Constructor for EstateTools class /// </summary> /// <param name="client"></param> public EstateTools(GridClient client) { GroundTextures = new GroundTextureSettings(); GroundTextureLimits = new GroundTextureHeightSettings(); Client = client; Client.Network.RegisterCallback(PacketType.LandStatReply, LandStatReplyHandler); Client.Network.RegisterCallback(PacketType.EstateOwnerMessage, EstateOwnerMessageHandler); Client.Network.RegisterCallback(PacketType.EstateCovenantReply, EstateCovenantReplyHandler); Client.Network.RegisterEventCallback("LandStatReply", new Caps.EventQueueCallback(LandStatCapsReplyHandler)); } #region Enums /// <summary>Used in the ReportType field of a LandStatRequest</summary> public enum LandStatReportType { TopScripts = 0, TopColliders = 1 } /// <summary>Used by EstateOwnerMessage packets</summary> public enum EstateAccessDelta : uint { BanUser = 64, BanUserAllEstates = 66, UnbanUser = 128, UnbanUserAllEstates = 130, AddManager = 256, AddManagerAllEstates = 257, RemoveManager = 512, RemoveManagerAllEstates = 513, AddUserAsAllowed = 4, AddAllowedAllEstates = 6, RemoveUserAsAllowed = 8, RemoveUserAllowedAllEstates = 10, AddGroupAsAllowed = 16, AddGroupAllowedAllEstates = 18, RemoveGroupAsAllowed = 32, RemoveGroupAllowedAllEstates = 34 } /// <summary>Used by EstateOwnerMessage packets</summary> public enum EstateAccessReplyDelta : uint { AllowedUsers = 17, AllowedGroups = 18, EstateBans = 20, EstateManagers = 24 } /// <summary> /// /// </summary> [Flags] public enum EstateReturnFlags : uint { /// <summary>No flags set</summary> None = 2, /// <summary>Only return targets scripted objects</summary> ReturnScripted = 6, /// <summary>Only return targets objects if on others land</summary> ReturnOnOthersLand = 3, /// <summary>Returns target's scripted objects and objects on other parcels</summary> ReturnScriptedAndOnOthers = 7 } #endregion #region Structs /// <summary>Ground texture settings for each corner of the region</summary> // TODO: maybe move this class to the Simulator object and implement it there too public struct GroundTextureSettings { public UUID Low; public UUID MidLow; public UUID MidHigh; public UUID High; } /// <summary>Used by GroundTextureHeightSettings</summary> public struct GroundTextureHeight { public float Low; public float High; } /// <summary>The high and low texture thresholds for each corner of the sim</summary> public struct GroundTextureHeightSettings { public GroundTextureHeight SW; public GroundTextureHeight NW; public GroundTextureHeight SE; public GroundTextureHeight NE; } #endregion #region Event delegates, Raise Events /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<TopCollidersReplyEventArgs> m_TopCollidersReply; /// <summary>Raises the TopCollidersReply event</summary> /// <param name="e">A TopCollidersReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnTopCollidersReply(TopCollidersReplyEventArgs e) { EventHandler<TopCollidersReplyEventArgs> handler = m_TopCollidersReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_TopCollidersReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<TopCollidersReplyEventArgs> TopCollidersReply { add { lock (m_TopCollidersReply_Lock) { m_TopCollidersReply += value; } } remove { lock (m_TopCollidersReply_Lock) { m_TopCollidersReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<TopScriptsReplyEventArgs> m_TopScriptsReply; /// <summary>Raises the TopScriptsReply event</summary> /// <param name="e">A TopScriptsReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnTopScriptsReply(TopScriptsReplyEventArgs e) { EventHandler<TopScriptsReplyEventArgs> handler = m_TopScriptsReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_TopScriptsReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<TopScriptsReplyEventArgs> TopScriptsReply { add { lock (m_TopScriptsReply_Lock) { m_TopScriptsReply += value; } } remove { lock (m_TopScriptsReply_Lock) { m_TopScriptsReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<EstateUsersReplyEventArgs> m_EstateUsersReply; /// <summary>Raises the EstateUsersReply event</summary> /// <param name="e">A EstateUsersReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnEstateUsersReply(EstateUsersReplyEventArgs e) { EventHandler<EstateUsersReplyEventArgs> handler = m_EstateUsersReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EstateUsersReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<EstateUsersReplyEventArgs> EstateUsersReply { add { lock (m_EstateUsersReply_Lock) { m_EstateUsersReply += value; } } remove { lock (m_EstateUsersReply_Lock) { m_EstateUsersReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<EstateGroupsReplyEventArgs> m_EstateGroupsReply; /// <summary>Raises the EstateGroupsReply event</summary> /// <param name="e">A EstateGroupsReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnEstateGroupsReply(EstateGroupsReplyEventArgs e) { EventHandler<EstateGroupsReplyEventArgs> handler = m_EstateGroupsReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EstateGroupsReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<EstateGroupsReplyEventArgs> EstateGroupsReply { add { lock (m_EstateGroupsReply_Lock) { m_EstateGroupsReply += value; } } remove { lock (m_EstateGroupsReply_Lock) { m_EstateGroupsReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<EstateManagersReplyEventArgs> m_EstateManagersReply; /// <summary>Raises the EstateManagersReply event</summary> /// <param name="e">A EstateManagersReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnEstateManagersReply(EstateManagersReplyEventArgs e) { EventHandler<EstateManagersReplyEventArgs> handler = m_EstateManagersReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EstateManagersReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<EstateManagersReplyEventArgs> EstateManagersReply { add { lock (m_EstateManagersReply_Lock) { m_EstateManagersReply += value; } } remove { lock (m_EstateManagersReply_Lock) { m_EstateManagersReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<EstateBansReplyEventArgs> m_EstateBansReply; /// <summary>Raises the EstateBansReply event</summary> /// <param name="e">A EstateBansReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnEstateBansReply(EstateBansReplyEventArgs e) { EventHandler<EstateBansReplyEventArgs> handler = m_EstateBansReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EstateBansReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<EstateBansReplyEventArgs> EstateBansReply { add { lock (m_EstateBansReply_Lock) { m_EstateBansReply += value; } } remove { lock (m_EstateBansReply_Lock) { m_EstateBansReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<EstateCovenantReplyEventArgs> m_EstateCovenantReply; /// <summary>Raises the EstateCovenantReply event</summary> /// <param name="e">A EstateCovenantReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnEstateCovenantReply(EstateCovenantReplyEventArgs e) { EventHandler<EstateCovenantReplyEventArgs> handler = m_EstateCovenantReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EstateCovenantReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<EstateCovenantReplyEventArgs> EstateCovenantReply { add { lock (m_EstateCovenantReply_Lock) { m_EstateCovenantReply += value; } } remove { lock (m_EstateCovenantReply_Lock) { m_EstateCovenantReply -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<EstateUpdateInfoReplyEventArgs> m_EstateUpdateInfoReply; /// <summary>Raises the EstateUpdateInfoReply event</summary> /// <param name="e">A EstateUpdateInfoReplyEventArgs object containing the /// data returned from the data server</param> protected virtual void OnEstateUpdateInfoReply(EstateUpdateInfoReplyEventArgs e) { EventHandler<EstateUpdateInfoReplyEventArgs> handler = m_EstateUpdateInfoReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EstateUpdateInfoReply_Lock = new object(); /// <summary>Raised when the data server responds to a <see cref="LandStatRequest"/> request.</summary> public event EventHandler<EstateUpdateInfoReplyEventArgs> EstateUpdateInfoReply { add { lock (m_EstateUpdateInfoReply_Lock) { m_EstateUpdateInfoReply += value; } } remove { lock (m_EstateUpdateInfoReply_Lock) { m_EstateUpdateInfoReply -= value; } } } #endregion #region Public Methods /// <summary> /// Requests estate information such as top scripts and colliders /// </summary> /// <param name="parcelLocalID"></param> /// <param name="reportType"></param> /// <param name="requestFlags"></param> /// <param name="filter"></param> public void LandStatRequest(int parcelLocalID, LandStatReportType reportType, uint requestFlags, string filter) { LandStatRequestPacket p = new LandStatRequestPacket(); p.AgentData.AgentID = Client.Self.AgentID; p.AgentData.SessionID = Client.Self.SessionID; p.RequestData.Filter = Utils.StringToBytes(filter); p.RequestData.ParcelLocalID = parcelLocalID; p.RequestData.ReportType = (uint)reportType; p.RequestData.RequestFlags = requestFlags; Client.Network.SendPacket(p); } /// <summary>Requests estate settings, including estate manager and access/ban lists</summary> public void RequestInfo() { EstateOwnerMessage("getinfo", ""); } /// <summary>Requests the "Top Scripts" list for the current region</summary> public void RequestTopScripts() { //EstateOwnerMessage("scripts", ""); LandStatRequest(0, LandStatReportType.TopScripts, 0, ""); } /// <summary>Requests the "Top Colliders" list for the current region</summary> public void RequestTopColliders() { //EstateOwnerMessage("colliders", ""); LandStatRequest(0, LandStatReportType.TopColliders, 0, ""); } /// <summary> /// Set several estate specific configuration variables /// </summary> /// <param name="WaterHeight">The Height of the waterlevel over the entire estate. Defaults to 20</param> /// <param name="TerrainRaiseLimit">The maximum height change allowed above the baked terrain. Defaults to 4</param> /// <param name="TerrainLowerLimit">The minimum height change allowed below the baked terrain. Defaults to -4</param> /// <param name="UseEstateSun">true to use</param> /// <param name="FixedSun">if True forces the sun position to the position in SunPosition</param> /// <param name="SunPosition">The current position of the sun on the estate, or when FixedSun is true the static position /// the sun will remain. <remarks>6.0 = Sunrise, 30.0 = Sunset</remarks></param> public void SetTerrainVariables(float WaterHeight, float TerrainRaiseLimit, float TerrainLowerLimit, bool UseEstateSun, bool FixedSun, float SunPosition) { List<string> simVariables = new List<string>(); simVariables.Add(WaterHeight.ToString(Utils.EnUsCulture)); simVariables.Add(TerrainRaiseLimit.ToString(Utils.EnUsCulture)); simVariables.Add(TerrainLowerLimit.ToString(Utils.EnUsCulture)); simVariables.Add(UseEstateSun ? "Y" : "N"); simVariables.Add(FixedSun ? "Y" : "N"); simVariables.Add(SunPosition.ToString(Utils.EnUsCulture)); simVariables.Add("Y"); //Not used? simVariables.Add("N"); //Not used? simVariables.Add("0.00"); //Also not used? EstateOwnerMessage("setregionterrain", simVariables); } /// <summary> /// Request return of objects owned by specified avatar /// </summary> /// <param name="Target">The Agents <see cref="UUID"/> owning the primitives to return</param> /// <param name="flag">specify the coverage and type of objects to be included in the return</param> /// <param name="EstateWide">true to perform return on entire estate</param> public void SimWideReturn(UUID Target, EstateReturnFlags flag, bool EstateWide) { if (EstateWide) { List<string> param = new List<string>(); param.Add(flag.ToString()); param.Add(Target.ToString()); EstateOwnerMessage("estateobjectreturn", param); } else { SimWideDeletesPacket simDelete = new SimWideDeletesPacket(); simDelete.AgentData.AgentID = Client.Self.AgentID; simDelete.AgentData.SessionID = Client.Self.SessionID; simDelete.DataBlock.TargetID = Target; simDelete.DataBlock.Flags = (uint)flag; Client.Network.SendPacket(simDelete); } } /// <summary></summary> /// <param name="method"></param> /// <param name="param"></param> public void EstateOwnerMessage(string method, string param) { List<string> listParams = new List<string>(); listParams.Add(param); EstateOwnerMessage(method, listParams); } /// <summary> /// Used for setting and retrieving various estate panel settings /// </summary> /// <param name="method">EstateOwnerMessage Method field</param> /// <param name="listParams">List of parameters to include</param> public void EstateOwnerMessage(string method, List<string> listParams) { EstateOwnerMessagePacket estate = new EstateOwnerMessagePacket(); estate.AgentData.AgentID = Client.Self.AgentID; estate.AgentData.SessionID = Client.Self.SessionID; estate.AgentData.TransactionID = UUID.Zero; estate.MethodData.Invoice = UUID.Random(); estate.MethodData.Method = Utils.StringToBytes(method); estate.ParamList = new EstateOwnerMessagePacket.ParamListBlock[listParams.Count]; for (int i = 0; i < listParams.Count; i++) { estate.ParamList[i] = new EstateOwnerMessagePacket.ParamListBlock(); estate.ParamList[i].Parameter = Utils.StringToBytes(listParams[i]); } Client.Network.SendPacket((Packet)estate); } /// <summary> /// Kick an avatar from an estate /// </summary> /// <param name="userID">Key of Agent to remove</param> public void KickUser(UUID userID) { EstateOwnerMessage("kickestate", userID.ToString()); } /// <summary> /// Ban an avatar from an estate</summary> /// <param name="userID">Key of Agent to remove</param> /// <param name="allEstates">Ban user from this estate and all others owned by the estate owner</param> public void BanUser(UUID userID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.BanUserAllEstates : (uint)EstateAccessDelta.BanUser; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(userID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// <summary>Unban an avatar from an estate</summary> /// <param name="userID">Key of Agent to remove</param> /// /// <param name="allEstates">Unban user from this estate and all others owned by the estate owner</param> public void UnbanUser(UUID userID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.UnbanUserAllEstates : (uint)EstateAccessDelta.UnbanUser; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(userID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// <summary> /// Send a message dialog to everyone in an entire estate /// </summary> /// <param name="message">Message to send all users in the estate</param> public void EstateMessage(string message) { List<string> listParams = new List<string>(); listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName); listParams.Add(message); EstateOwnerMessage("instantmessage", listParams); } /// <summary> /// Send a message dialog to everyone in a simulator /// </summary> /// <param name="message">Message to send all users in the simulator</param> public void SimulatorMessage(string message) { List<string> listParams = new List<string>(); listParams.Add("-1"); listParams.Add("-1"); listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName); listParams.Add(message); EstateOwnerMessage("simulatormessage", listParams); } /// <summary> /// Send an avatar back to their home location /// </summary> /// <param name="pest">Key of avatar to send home</param> public void TeleportHomeUser(UUID pest) { List<string> listParams = new List<string>(); listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(pest.ToString()); EstateOwnerMessage("teleporthomeuser", listParams); } /// <summary> /// Begin the region restart process /// </summary> public void RestartRegion() { EstateOwnerMessage("restart", "120"); } /// <summary> /// Cancels a region restart /// </summary> public void CancelRestart() { EstateOwnerMessage("restart", "-1"); } /// <summary>Estate panel "Region" tab settings</summary> public void SetRegionInfo(bool blockTerraform, bool blockFly, bool allowDamage, bool allowLandResell, bool restrictPushing, bool allowParcelJoinDivide, float agentLimit, float objectBonus, bool mature) { List<string> listParams = new List<string>(); if (blockTerraform) listParams.Add("Y"); else listParams.Add("N"); if (blockFly) listParams.Add("Y"); else listParams.Add("N"); if (allowDamage) listParams.Add("Y"); else listParams.Add("N"); if (allowLandResell) listParams.Add("Y"); else listParams.Add("N"); listParams.Add(agentLimit.ToString()); listParams.Add(objectBonus.ToString()); if (mature) listParams.Add("21"); else listParams.Add("13"); //FIXME - enumerate these settings if (restrictPushing) listParams.Add("Y"); else listParams.Add("N"); if (allowParcelJoinDivide) listParams.Add("Y"); else listParams.Add("N"); EstateOwnerMessage("setregioninfo", listParams); } /// <summary>Estate panel "Debug" tab settings</summary> public void SetRegionDebug(bool disableScripts, bool disableCollisions, bool disablePhysics) { List<string> listParams = new List<string>(); if (disableScripts) listParams.Add("Y"); else listParams.Add("N"); if (disableCollisions) listParams.Add("Y"); else listParams.Add("N"); if (disablePhysics) listParams.Add("Y"); else listParams.Add("N"); EstateOwnerMessage("setregiondebug", listParams); } /// <summary>Used for setting the region's terrain textures for its four height levels</summary> /// <param name="low"></param> /// <param name="midLow"></param> /// <param name="midHigh"></param> /// <param name="high"></param> public void SetRegionTerrain(UUID low, UUID midLow, UUID midHigh, UUID high) { List<string> listParams = new List<string>(); listParams.Add("0 " + low.ToString()); listParams.Add("1 " + midLow.ToString()); listParams.Add("2 " + midHigh.ToString()); listParams.Add("3 " + high.ToString()); EstateOwnerMessage("texturedetail", listParams); EstateOwnerMessage("texturecommit", ""); } /// <summary>Used for setting sim terrain texture heights</summary> public void SetRegionTerrainHeights(float lowSW, float highSW, float lowNW, float highNW, float lowSE, float highSE, float lowNE, float highNE) { List<string> listParams = new List<string>(); listParams.Add("0 " + lowSW.ToString(Utils.EnUsCulture) + " " + highSW.ToString(Utils.EnUsCulture)); //SW low-high listParams.Add("1 " + lowNW.ToString(Utils.EnUsCulture) + " " + highNW.ToString(Utils.EnUsCulture)); //NW low-high listParams.Add("2 " + lowSE.ToString(Utils.EnUsCulture) + " " + highSE.ToString(Utils.EnUsCulture)); //SE low-high listParams.Add("3 " + lowNE.ToString(Utils.EnUsCulture) + " " + highNE.ToString(Utils.EnUsCulture)); //NE low-high EstateOwnerMessage("textureheights", listParams); EstateOwnerMessage("texturecommit", ""); } /// <summary>Requests the estate covenant</summary> public void RequestCovenant() { EstateCovenantRequestPacket req = new EstateCovenantRequestPacket(); req.AgentData.AgentID = Client.Self.AgentID; req.AgentData.SessionID = Client.Self.SessionID; Client.Network.SendPacket(req); } /// <summary> /// Upload a terrain RAW file /// </summary> /// <param name="fileData">A byte array containing the encoded terrain data</param> /// <param name="fileName">The name of the file being uploaded</param> /// <returns>The Id of the transfer request</returns> public UUID UploadTerrain(byte[] fileData, string fileName) { AssetUpload upload = new AssetUpload(); upload.AssetData = fileData; upload.AssetType = AssetType.Unknown; upload.Size = fileData.Length; upload.ID = UUID.Random(); // Tell the library we have a pending file to upload Client.Assets.SetPendingAssetUploadData(upload); // Create and populate a list with commands specific to uploading a raw terrain file List<String> paramList = new List<string>(); paramList.Add("upload filename"); paramList.Add(fileName); // Tell the simulator we have a new raw file to upload Client.Estate.EstateOwnerMessage("terrain", paramList); return upload.ID; } /// <summary> /// Teleports all users home in current Estate /// </summary> public void TeleportHomeAllUsers() { List<string> Params = new List<string>(); Params.Add(Client.Self.AgentID.ToString()); EstateOwnerMessage("teleporthomeallusers", Params); } /// <summary> /// Remove estate manager</summary> /// <param name="userID">Key of Agent to Remove</param> /// <param name="allEstates">removes manager to this estate and all others owned by the estate owner</param> public void RemoveEstateManager(UUID userID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.RemoveManagerAllEstates : (uint)EstateAccessDelta.RemoveManager; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(userID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// <summary> /// Add estate manager</summary> /// <param name="userID">Key of Agent to Add</param> /// <param name="allEstates">Add agent as manager to this estate and all others owned by the estate owner</param> public void AddEstateManager(UUID userID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.AddManagerAllEstates : (uint)EstateAccessDelta.AddManager; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(userID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// <summary> /// Add's an agent to the estate Allowed list</summary> /// <param name="userID">Key of Agent to Add</param> /// <param name="allEstates">Add agent as an allowed reisdent to All estates if true</param> public void AddAllowedUser(UUID userID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.AddAllowedAllEstates : (uint)EstateAccessDelta.AddUserAsAllowed; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(userID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// <summary> /// Removes an agent from the estate Allowed list</summary> /// <param name="userID">Key of Agent to Remove</param> /// <param name="allEstates">Removes agent as an allowed reisdent from All estates if true</param> public void RemoveAllowedUser(UUID userID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.RemoveUserAllowedAllEstates : (uint)EstateAccessDelta.RemoveUserAsAllowed; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(userID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// /// <summary> /// Add's a group to the estate Allowed list</summary> /// <param name="groupID">Key of Group to Add</param> /// <param name="allEstates">Add Group as an allowed group to All estates if true</param> public void AddAllowedGroup(UUID groupID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.AddGroupAllowedAllEstates : (uint)EstateAccessDelta.AddAllowedAllEstates; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(groupID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } /// /// <summary> /// Removes a group from the estate Allowed list</summary> /// <param name="groupID">Key of Group to Remove</param> /// <param name="allEstates">Removes Group as an allowed Group from All estates if true</param> public void RemoveAllowedGroup(UUID groupID, bool allEstates) { List<string> listParams = new List<string>(); uint flag = allEstates ? (uint)EstateAccessDelta.RemoveGroupAllowedAllEstates : (uint)EstateAccessDelta.RemoveGroupAsAllowed; listParams.Add(Client.Self.AgentID.ToString()); listParams.Add(flag.ToString()); listParams.Add(groupID.ToString()); EstateOwnerMessage("estateaccessdelta", listParams); } #endregion #region Packet Handlers /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void EstateCovenantReplyHandler(object sender, PacketReceivedEventArgs e) { EstateCovenantReplyPacket reply = (EstateCovenantReplyPacket)e.Packet; OnEstateCovenantReply(new EstateCovenantReplyEventArgs( reply.Data.CovenantID, reply.Data.CovenantTimestamp, Utils.BytesToString(reply.Data.EstateName), reply.Data.EstateOwnerID)); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void EstateOwnerMessageHandler(object sender, PacketReceivedEventArgs e) { EstateOwnerMessagePacket message = (EstateOwnerMessagePacket)e.Packet; uint estateID; string method = Utils.BytesToString(message.MethodData.Method); //List<string> parameters = new List<string>(); if (method == "estateupdateinfo") { string estateName = Utils.BytesToString(message.ParamList[0].Parameter); UUID estateOwner = new UUID(Utils.BytesToString(message.ParamList[1].Parameter)); estateID = Utils.BytesToUInt(message.ParamList[2].Parameter); /* foreach (EstateOwnerMessagePacket.ParamListBlock param in message.ParamList) { parameters.Add(Utils.BytesToString(param.Parameter)); } */ bool denyNoPaymentInfo; if (Utils.BytesToUInt(message.ParamList[8].Parameter) == 0) denyNoPaymentInfo = true; else denyNoPaymentInfo = false; OnEstateUpdateInfoReply(new EstateUpdateInfoReplyEventArgs(estateName, estateOwner, estateID, denyNoPaymentInfo)); } else if (method == "setaccess") { int count; estateID = Utils.BytesToUInt(message.ParamList[0].Parameter); if (message.ParamList.Length > 1) { //param comes in as a string for some reason uint param; if (!uint.TryParse(Utils.BytesToString(message.ParamList[1].Parameter), out param)) return; EstateAccessReplyDelta accessType = (EstateAccessReplyDelta)param; switch (accessType) { case EstateAccessReplyDelta.EstateManagers: //if (OnGetEstateManagers != null) { if (message.ParamList.Length > 5) { if (!int.TryParse(Utils.BytesToString(message.ParamList[5].Parameter), out count)) return; List<UUID> managers = new List<UUID>(); for (int i = 6; i < message.ParamList.Length; i++) { try { UUID managerID = new UUID(message.ParamList[i].Parameter, 0); managers.Add(managerID); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); } } OnEstateManagersReply(new EstateManagersReplyEventArgs(estateID, count, managers)); } } break; case EstateAccessReplyDelta.EstateBans: //if (OnGetEstateBans != null) { if (message.ParamList.Length > 5) { if (!int.TryParse(Utils.BytesToString(message.ParamList[4].Parameter), out count)) return; List<UUID> bannedUsers = new List<UUID>(); for (int i = 6; i < message.ParamList.Length; i++) { try { UUID bannedID = new UUID(message.ParamList[i].Parameter, 0); bannedUsers.Add(bannedID); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); } } OnEstateBansReply(new EstateBansReplyEventArgs(estateID, count, bannedUsers)); } } break; case EstateAccessReplyDelta.AllowedUsers: //if (OnGetAllowedUsers != null) { if (message.ParamList.Length > 5) { if (!int.TryParse(Utils.BytesToString(message.ParamList[2].Parameter), out count)) return; List<UUID> allowedUsers = new List<UUID>(); for (int i = 6; i < message.ParamList.Length; i++) { try { UUID allowedID = new UUID(message.ParamList[i].Parameter, 0); allowedUsers.Add(allowedID); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); } } OnEstateUsersReply(new EstateUsersReplyEventArgs(estateID, count, allowedUsers)); } } break; case EstateAccessReplyDelta.AllowedGroups: //if (OnGetAllowedGroups != null) { if (message.ParamList.Length > 5) { if (!int.TryParse(Utils.BytesToString(message.ParamList[3].Parameter), out count)) return; List<UUID> allowedGroups = new List<UUID>(); for (int i = 6; i < message.ParamList.Length; i++) { try { UUID groupID = new UUID(message.ParamList[i].Parameter, 0); allowedGroups.Add(groupID); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); } } OnEstateGroupsReply(new EstateGroupsReplyEventArgs(estateID, count, allowedGroups)); } } break; } } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void LandStatReplyHandler(object sender, PacketReceivedEventArgs e) { //if (OnLandStatReply != null || OnGetTopScripts != null || OnGetTopColliders != null) //if (OnGetTopScripts != null || OnGetTopColliders != null) { LandStatReplyPacket p = (LandStatReplyPacket)e.Packet; Dictionary<UUID, EstateTask> Tasks = new Dictionary<UUID, EstateTask>(); foreach (LandStatReplyPacket.ReportDataBlock rep in p.ReportData) { EstateTask task = new EstateTask(); task.Position = new Vector3(rep.LocationX, rep.LocationY, rep.LocationZ); task.Score = rep.Score; task.TaskID = rep.TaskID; task.TaskLocalID = rep.TaskLocalID; task.TaskName = Utils.BytesToString(rep.TaskName); task.OwnerName = Utils.BytesToString(rep.OwnerName); Tasks.Add(task.TaskID, task); } LandStatReportType type = (LandStatReportType)p.RequestData.ReportType; if (type == LandStatReportType.TopScripts) { OnTopScriptsReply(new TopScriptsReplyEventArgs((int)p.RequestData.TotalObjectCount, Tasks)); } else if (type == LandStatReportType.TopColliders) { OnTopCollidersReply(new TopCollidersReplyEventArgs((int) p.RequestData.TotalObjectCount, Tasks)); } /* if (OnGetTopColliders != null) { //FIXME - System.UnhandledExceptionEventArgs OnLandStatReply( type, p.RequestData.RequestFlags, (int)p.RequestData.TotalObjectCount, Tasks ); } */ } } private void LandStatCapsReplyHandler(string capsKey, IMessage message, Simulator simulator) { LandStatReplyMessage m = (LandStatReplyMessage)message; Dictionary<UUID, EstateTask> Tasks = new Dictionary<UUID, EstateTask>(); foreach (LandStatReplyMessage.ReportDataBlock rep in m.ReportDataBlocks) { EstateTask task = new EstateTask(); task.Position = rep.Location; task.Score = rep.Score; task.MonoScore = rep.MonoScore; task.TaskID = rep.TaskID; task.TaskLocalID = rep.TaskLocalID; task.TaskName = rep.TaskName; task.OwnerName = rep.OwnerName; Tasks.Add(task.TaskID, task); } LandStatReportType type = (LandStatReportType)m.ReportType; if (type == LandStatReportType.TopScripts) { OnTopScriptsReply(new TopScriptsReplyEventArgs((int)m.TotalObjectCount, Tasks)); } else if (type == LandStatReportType.TopColliders) { OnTopCollidersReply(new TopCollidersReplyEventArgs((int)m.TotalObjectCount, Tasks)); } } #endregion } #region EstateTools EventArgs Classes /// <summary>Raised on LandStatReply when the report type is for "top colliders"</summary> public class TopCollidersReplyEventArgs : EventArgs { private readonly int m_objectCount; private readonly Dictionary<UUID, EstateTask> m_Tasks; /// <summary> /// The number of returned items in LandStatReply /// </summary> public int ObjectCount { get { return m_objectCount; } } /// <summary> /// A Dictionary of Object UUIDs to tasks returned in LandStatReply /// </summary> public Dictionary<UUID, EstateTask> Tasks { get { return m_Tasks; } } /// <summary>Construct a new instance of the TopCollidersReplyEventArgs class</summary> /// <param name="objectCount">The number of returned items in LandStatReply</param> /// <param name="tasks">Dictionary of Object UUIDs to tasks returned in LandStatReply</param> public TopCollidersReplyEventArgs(int objectCount, Dictionary<UUID, EstateTask> tasks) { this.m_objectCount = objectCount; this.m_Tasks = tasks; } } /// <summary>Raised on LandStatReply when the report type is for "top Scripts"</summary> public class TopScriptsReplyEventArgs : EventArgs { private readonly int m_objectCount; private readonly Dictionary<UUID, EstateTask> m_Tasks; /// <summary> /// The number of scripts returned in LandStatReply /// </summary> public int ObjectCount { get { return m_objectCount; } } /// <summary> /// A Dictionary of Object UUIDs to tasks returned in LandStatReply /// </summary> public Dictionary<UUID, EstateTask> Tasks { get { return m_Tasks; } } /// <summary>Construct a new instance of the TopScriptsReplyEventArgs class</summary> /// <param name="objectCount">The number of returned items in LandStatReply</param> /// <param name="tasks">Dictionary of Object UUIDs to tasks returned in LandStatReply</param> public TopScriptsReplyEventArgs(int objectCount, Dictionary<UUID, EstateTask> tasks) { this.m_objectCount = objectCount; this.m_Tasks = tasks; } } /// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary> public class EstateBansReplyEventArgs : EventArgs { private readonly uint m_estateID; private readonly int m_count; private readonly List<UUID> m_banned; /// <summary> /// The identifier of the estate /// </summary> public uint EstateID { get { return m_estateID; } } /// <summary> /// The number of returned itmes /// </summary> public int Count { get { return m_count; } } /// <summary> /// List of UUIDs of Banned Users /// </summary> public List<UUID> Banned { get { return m_banned; } } /// <summary>Construct a new instance of the EstateBansReplyEventArgs class</summary> /// <param name="estateID">The estate's identifier on the grid</param> /// <param name="count">The number of returned items in LandStatReply</param> /// <param name="banned">User UUIDs banned</param> public EstateBansReplyEventArgs(uint estateID, int count, List<UUID> banned) { this.m_estateID = estateID; this.m_count = count; this.m_banned = banned; } } /// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary> public class EstateUsersReplyEventArgs : EventArgs { private readonly uint m_estateID; private readonly int m_count; private readonly List<UUID> m_allowedUsers; /// <summary> /// The identifier of the estate /// </summary> public uint EstateID { get { return m_estateID; } } /// <summary> /// The number of returned items /// </summary> public int Count { get { return m_count; } } /// <summary> /// List of UUIDs of Allowed Users /// </summary> public List<UUID> AllowedUsers { get { return m_allowedUsers; } } /// <summary>Construct a new instance of the EstateUsersReplyEventArgs class</summary> /// <param name="estateID">The estate's identifier on the grid</param> /// <param name="count">The number of users</param> /// <param name="allowedUsers">Allowed users UUIDs</param> public EstateUsersReplyEventArgs(uint estateID, int count, List<UUID> allowedUsers) { this.m_estateID = estateID; this.m_count = count; this.m_allowedUsers = allowedUsers; } } /// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary> public class EstateGroupsReplyEventArgs : EventArgs { private readonly uint m_estateID; private readonly int m_count; private readonly List<UUID> m_allowedGroups; /// <summary> /// The identifier of the estate /// </summary> public uint EstateID { get { return m_estateID; } } /// <summary> /// The number of returned items /// </summary> public int Count { get { return m_count; } } /// <summary> /// List of UUIDs of Allowed Groups /// </summary> public List<UUID> AllowedGroups { get { return m_allowedGroups; } } /// <summary>Construct a new instance of the EstateGroupsReplyEventArgs class</summary> /// <param name="estateID">The estate's identifier on the grid</param> /// <param name="count">The number of Groups</param> /// <param name="allowedGroups">Allowed Groups UUIDs</param> public EstateGroupsReplyEventArgs(uint estateID, int count, List<UUID> allowedGroups) { this.m_estateID = estateID; this.m_count = count; this.m_allowedGroups = allowedGroups; } } /// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary> public class EstateManagersReplyEventArgs : EventArgs { private readonly uint m_estateID; private readonly int m_count; private readonly List<UUID> m_Managers; /// <summary> /// The identifier of the estate /// </summary> public uint EstateID { get { return m_estateID; } } /// <summary> /// The number of returned items /// </summary> public int Count { get { return m_count; } } /// <summary> /// List of UUIDs of the Estate's Managers /// </summary> public List<UUID> Managers { get { return m_Managers; } } /// <summary>Construct a new instance of the EstateManagersReplyEventArgs class</summary> /// <param name="estateID">The estate's identifier on the grid</param> /// <param name="count">The number of Managers</param> /// <param name="managers"> Managers UUIDs</param> public EstateManagersReplyEventArgs(uint estateID, int count, List<UUID> managers) { this.m_estateID = estateID; this.m_count = count; this.m_Managers = managers; } } /// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary> public class EstateCovenantReplyEventArgs : EventArgs { private readonly UUID m_covenantID; private readonly long m_timestamp; private readonly string m_estateName; private readonly UUID m_estateOwnerID; /// <summary> /// The Covenant /// </summary> public UUID CovenantID { get { return m_covenantID; } } /// <summary> /// The timestamp /// </summary> public long Timestamp { get { return m_timestamp; } } /// <summary> /// The Estate name /// </summary> public String EstateName { get { return m_estateName; } } /// <summary> /// The Estate Owner's ID (can be a GroupID) /// </summary> public UUID EstateOwnerID { get { return m_estateOwnerID; } } /// <summary>Construct a new instance of the EstateCovenantReplyEventArgs class</summary> /// <param name="covenantID">The Covenant ID</param> /// <param name="timestamp">The timestamp</param> /// <param name="estateName">The estate's name</param> /// <param name="estateOwnerID">The Estate Owner's ID (can be a GroupID)</param> public EstateCovenantReplyEventArgs(UUID covenantID, long timestamp, string estateName, UUID estateOwnerID) { this.m_covenantID = covenantID; this.m_timestamp = timestamp; this.m_estateName = estateName; this.m_estateOwnerID = estateOwnerID; } } /// <summary>Returned, along with other info, upon a successful .RequestInfo()</summary> public class EstateUpdateInfoReplyEventArgs : EventArgs { private readonly uint m_estateID; private readonly bool m_denyNoPaymentInfo; private readonly string m_estateName; private readonly UUID m_estateOwner; /// <summary> /// The estate's name /// </summary> public String EstateName { get { return m_estateName; } } /// <summary> /// The Estate Owner's ID (can be a GroupID) /// </summary> public UUID EstateOwner { get { return m_estateOwner; } } /// <summary> /// The identifier of the estate on the grid /// </summary> public uint EstateID { get { return m_estateID; } } /// <summary></summary> public bool DenyNoPaymentInfo { get { return m_denyNoPaymentInfo; } } /// <summary>Construct a new instance of the EstateUpdateInfoReplyEventArgs class</summary> /// <param name="estateName">The estate's name</param> /// <param name="estateOwner">The Estate Owners ID (can be a GroupID)</param> /// <param name="estateID">The estate's identifier on the grid</param> /// <param name="denyNoPaymentInfo"></param> public EstateUpdateInfoReplyEventArgs(string estateName, UUID estateOwner, uint estateID, bool denyNoPaymentInfo) { this.m_estateName = estateName; this.m_estateOwner = estateOwner; this.m_estateID = estateID; this.m_denyNoPaymentInfo = denyNoPaymentInfo; } } #endregion }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.IO; using System.Collections; using System.Diagnostics; using System.Collections.Generic; namespace MSNPSharp.P2P { using MSNPSharp; using MSNPSharp.Core; /// <summary> /// Buffers incompleted P2PMessage SLP messages. /// </summary> public class P2PMessagePool { private Dictionary<uint, P2PMessage> incompletedP2PV1Messages = new Dictionary<uint, P2PMessage>(); private Dictionary<uint, P2PMessage> incompletedP2PV2Messages = new Dictionary<uint, P2PMessage>(); /// <summary> /// Buffers incompleted P2PMessage SLP messages. Ignores data and control messages. /// </summary> /// <param name="p2pMessage"></param> /// <returns> /// true if the P2PMessage is buffering (not completed) or invalid packet received; /// false if the p2p message fully buffered or no need to buffer. /// </returns> public bool BufferMessage(ref P2PMessage p2pMessage) { // P2PV1 and P2PV2 check if (p2pMessage.Header.MessageSize == 0 || // Ack message or Unsplitted p2pMessage.Header.SessionId > 0) // Data message { return false; // No need to buffer } // P2PV2 pooling if (p2pMessage.Version == P2PVersion.P2PV2) { if ((p2pMessage.V2Header.TFCombination == TFCombination.First && p2pMessage.V2Header.DataRemaining == 0) || // Unsplitted SLP message or data preparation message (p2pMessage.V2Header.TFCombination > TFCombination.First)) // Data message { return false; // No need to buffer } // First splitted SLP message. if (p2pMessage.V2Header.TFCombination == TFCombination.First && p2pMessage.V2Header.DataRemaining > 0) { P2PMessage totalMessage = new P2PMessage(p2pMessage); // Copy it ulong totalSize = (ulong)(p2pMessage.V2Header.MessageSize - p2pMessage.V2Header.DataPacketHeaderLength) + p2pMessage.V2Header.DataRemaining; totalMessage.InnerBody = new byte[totalSize]; // Allocate buffer as needed Array.Copy(p2pMessage.InnerBody, 0, totalMessage.InnerBody, (long)0, (long)p2pMessage.InnerBody.Length); lock (incompletedP2PV2Messages) incompletedP2PV2Messages[p2pMessage.V2Header.Identifier + p2pMessage.V2Header.MessageSize] = totalMessage; return true; // Buffering } // Other splitted SLP messages if (p2pMessage.V2Header.TFCombination == TFCombination.None) { lock (incompletedP2PV2Messages) { if (incompletedP2PV2Messages.ContainsKey(p2pMessage.V2Header.Identifier)) { if (incompletedP2PV2Messages[p2pMessage.V2Header.Identifier].V2Header.PackageNumber == p2pMessage.V2Header.PackageNumber) { P2PMessage totalMessage = incompletedP2PV2Messages[p2pMessage.V2Header.Identifier]; ulong dataSize = Math.Min(((ulong)(p2pMessage.V2Header.MessageSize - p2pMessage.V2Header.DataPacketHeaderLength)), totalMessage.V2Header.DataRemaining); ulong offSet = ((ulong)totalMessage.InnerBody.LongLength) - totalMessage.V2Header.DataRemaining; // Check range and buffer overflow... if (((p2pMessage.V2Header.DataRemaining + (ulong)dataSize) == totalMessage.V2Header.DataRemaining) && (ulong)(dataSize + offSet + p2pMessage.V2Header.DataRemaining) == (ulong)totalMessage.InnerBody.LongLength) { Array.Copy(p2pMessage.InnerBody, 0, totalMessage.InnerBody, (long)offSet, (long)dataSize); uint originalIdentifier = p2pMessage.V2Header.Identifier; uint newIdentifier = p2pMessage.V2Header.Identifier + p2pMessage.V2Header.MessageSize; totalMessage.V2Header.DataRemaining = p2pMessage.V2Header.DataRemaining; totalMessage.V2Header.Identifier = newIdentifier; if (originalIdentifier != newIdentifier) { incompletedP2PV2Messages.Remove(originalIdentifier); } // Don't debug p2p inner packet (SLP) here. Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, " Buffering splitted SLP message! DataRemaining:" + totalMessage.V2Header.DataRemaining + " NewIdentifier: " + newIdentifier); if (p2pMessage.V2Header.DataRemaining > 0) { // Don't debug p2p packet here. Because it hasn't completed yet and SLPMessage.Parse() fails... incompletedP2PV2Messages[newIdentifier] = totalMessage; return true; // Buffering } else // Last part { totalMessage.InnerBody = totalMessage.InnerBody; // Refresh... DataRemaining=0 deletes data headers. totalMessage.V2Header.Identifier = newIdentifier - totalMessage.Header.MessageSize; Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "A splitted message was combined :\r\n" + totalMessage.ToDebugString()); p2pMessage = totalMessage; return false; // We have the whole message } } } // Invalid packet received!!! Ignore and delete it... incompletedP2PV2Messages.Remove(p2pMessage.V2Header.Identifier); Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "INVALID P2PV2 PACKET received!!! Ignored and deleted:\r\n" + p2pMessage.ToDebugString()); } } } } else // P2PV1 pooling { if ((p2pMessage.V1Header.MessageSize == p2pMessage.V1Header.TotalSize) || // Whole data ((p2pMessage.V1Header.Flags & P2PFlag.Data) == P2PFlag.Data)) // Data message { return false; // No need to buffer } lock (incompletedP2PV1Messages) { if (false == incompletedP2PV1Messages.ContainsKey(p2pMessage.Header.Identifier)) { byte[] totalPayload = new byte[p2pMessage.V1Header.TotalSize]; Array.Copy(p2pMessage.InnerBody, 0, totalPayload, (long)p2pMessage.V1Header.Offset, (long)p2pMessage.V1Header.MessageSize); P2PMessage copyMessage = new P2PMessage(p2pMessage); copyMessage.InnerBody = totalPayload; copyMessage.V1Header.Offset = p2pMessage.V1Header.Offset + p2pMessage.V1Header.MessageSize; incompletedP2PV1Messages[p2pMessage.Header.Identifier] = copyMessage; return true; // Buffering } P2PMessage totalMessage = incompletedP2PV1Messages[p2pMessage.Header.Identifier]; if (p2pMessage.V1Header.TotalSize == totalMessage.V1Header.TotalSize && (p2pMessage.V1Header.Offset + p2pMessage.V1Header.MessageSize) <= totalMessage.Header.TotalSize) { Array.Copy(p2pMessage.InnerBody, 0, totalMessage.InnerBody, (long)p2pMessage.V1Header.Offset, (long)p2pMessage.V1Header.MessageSize); totalMessage.V1Header.Offset = p2pMessage.V1Header.Offset + p2pMessage.V1Header.MessageSize; // Last packet if (totalMessage.V1Header.Offset == p2pMessage.V1Header.TotalSize) { totalMessage.V1Header.Offset = 0; incompletedP2PV1Messages.Remove(p2pMessage.Header.Identifier); p2pMessage = totalMessage; return false; // We have the whole message } return true; // Buffering } // Invalid packet received!!! Ignore and delete it... incompletedP2PV1Messages.Remove(p2pMessage.Header.Identifier); Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "INVALID P2PV1 PACKET received!!! Ignored and deleted:\r\n" + p2pMessage.ToDebugString()); } } return true; // Invalid packet, don't kill me. } public void Clear() { lock (incompletedP2PV1Messages) incompletedP2PV1Messages.Clear(); lock (incompletedP2PV2Messages) incompletedP2PV2Messages.Clear(); } } };
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.ServiceModel; using System.ServiceModel.Channels; using System.Threading; namespace Alchemy4Tridion.Plugins.Clients.CoreService { [GeneratedCode("System.ServiceModel", "4.0.0.0"), DebuggerStepThrough] public class StreamUploadClient : ClientBase<IStreamUpload>, IStreamUpload, IDisposable { private ClientBase<IStreamUpload>.BeginOperationDelegate onBeginUploadBinaryContentDelegate; private ClientBase<IStreamUpload>.EndOperationDelegate onEndUploadBinaryContentDelegate; private SendOrPostCallback onUploadBinaryContentCompletedDelegate; private ClientBase<IStreamUpload>.BeginOperationDelegate onBeginUploadBinaryByteArrayDelegate; private ClientBase<IStreamUpload>.EndOperationDelegate onEndUploadBinaryByteArrayDelegate; private SendOrPostCallback onUploadBinaryByteArrayCompletedDelegate; [method: CompilerGenerated] [CompilerGenerated] public event EventHandler<UploadBinaryContentCompletedEventArgs> UploadBinaryContentCompleted; [method: CompilerGenerated] [CompilerGenerated] public event EventHandler<UploadBinaryByteArrayCompletedEventArgs> UploadBinaryByteArrayCompleted; public StreamUploadClient() { } public StreamUploadClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public StreamUploadClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public StreamUploadClient(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public StreamUploadClient(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } [EditorBrowsable(EditorBrowsableState.Advanced)] UploadResponse IStreamUpload.UploadBinaryContent(UploadRequest request) { return base.Channel.UploadBinaryContent(request); } public string UploadBinaryContent(AccessTokenData AccessToken, Stream UploadContent) { return ((IStreamUpload)this).UploadBinaryContent(new UploadRequest { AccessToken = AccessToken, UploadContent = UploadContent }).FilePath; } [EditorBrowsable(EditorBrowsableState.Advanced)] IAsyncResult IStreamUpload.BeginUploadBinaryContent(UploadRequest request, AsyncCallback callback, object asyncState) { return base.Channel.BeginUploadBinaryContent(request, callback, asyncState); } [EditorBrowsable(EditorBrowsableState.Advanced)] public IAsyncResult BeginUploadBinaryContent(AccessTokenData AccessToken, Stream UploadContent, AsyncCallback callback, object asyncState) { return ((IStreamUpload)this).BeginUploadBinaryContent(new UploadRequest { AccessToken = AccessToken, UploadContent = UploadContent }, callback, asyncState); } [EditorBrowsable(EditorBrowsableState.Advanced)] UploadResponse IStreamUpload.EndUploadBinaryContent(IAsyncResult result) { return base.Channel.EndUploadBinaryContent(result); } [EditorBrowsable(EditorBrowsableState.Advanced)] public string EndUploadBinaryContent(IAsyncResult result) { return ((IStreamUpload)this).EndUploadBinaryContent(result).FilePath; } private IAsyncResult OnBeginUploadBinaryContent(object[] inValues, AsyncCallback callback, object asyncState) { AccessTokenData accessToken = (AccessTokenData)inValues[0]; Stream uploadContent = (Stream)inValues[1]; return this.BeginUploadBinaryContent(accessToken, uploadContent, callback, asyncState); } private object[] OnEndUploadBinaryContent(IAsyncResult result) { string text = this.EndUploadBinaryContent(result); return new object[] { text }; } private void OnUploadBinaryContentCompleted(object state) { if (this.UploadBinaryContentCompleted != null) { ClientBase<IStreamUpload>.InvokeAsyncCompletedEventArgs invokeAsyncCompletedEventArgs = (ClientBase<IStreamUpload>.InvokeAsyncCompletedEventArgs)state; this.UploadBinaryContentCompleted(this, new UploadBinaryContentCompletedEventArgs(invokeAsyncCompletedEventArgs.Results, invokeAsyncCompletedEventArgs.Error, invokeAsyncCompletedEventArgs.Cancelled, invokeAsyncCompletedEventArgs.UserState)); } } public void UploadBinaryContentAsync(AccessTokenData AccessToken, Stream UploadContent) { this.UploadBinaryContentAsync(AccessToken, UploadContent, null); } public void UploadBinaryContentAsync(AccessTokenData AccessToken, Stream UploadContent, object userState) { if (this.onBeginUploadBinaryContentDelegate == null) { this.onBeginUploadBinaryContentDelegate = new ClientBase<IStreamUpload>.BeginOperationDelegate(this.OnBeginUploadBinaryContent); } if (this.onEndUploadBinaryContentDelegate == null) { this.onEndUploadBinaryContentDelegate = new ClientBase<IStreamUpload>.EndOperationDelegate(this.OnEndUploadBinaryContent); } if (this.onUploadBinaryContentCompletedDelegate == null) { this.onUploadBinaryContentCompletedDelegate = new SendOrPostCallback(this.OnUploadBinaryContentCompleted); } base.InvokeAsync(this.onBeginUploadBinaryContentDelegate, new object[] { AccessToken, UploadContent }, this.onEndUploadBinaryContentDelegate, this.onUploadBinaryContentCompletedDelegate, userState); } public string UploadBinaryByteArray(AccessTokenData accessToken, byte[] data) { return base.Channel.UploadBinaryByteArray(accessToken, data); } [EditorBrowsable(EditorBrowsableState.Advanced)] public IAsyncResult BeginUploadBinaryByteArray(AccessTokenData accessToken, byte[] data, AsyncCallback callback, object asyncState) { return base.Channel.BeginUploadBinaryByteArray(accessToken, data, callback, asyncState); } [EditorBrowsable(EditorBrowsableState.Advanced)] public string EndUploadBinaryByteArray(IAsyncResult result) { return base.Channel.EndUploadBinaryByteArray(result); } private IAsyncResult OnBeginUploadBinaryByteArray(object[] inValues, AsyncCallback callback, object asyncState) { AccessTokenData accessToken = (AccessTokenData)inValues[0]; byte[] data = (byte[])inValues[1]; return this.BeginUploadBinaryByteArray(accessToken, data, callback, asyncState); } private object[] OnEndUploadBinaryByteArray(IAsyncResult result) { string text = this.EndUploadBinaryByteArray(result); return new object[] { text }; } private void OnUploadBinaryByteArrayCompleted(object state) { if (this.UploadBinaryByteArrayCompleted != null) { ClientBase<IStreamUpload>.InvokeAsyncCompletedEventArgs invokeAsyncCompletedEventArgs = (ClientBase<IStreamUpload>.InvokeAsyncCompletedEventArgs)state; this.UploadBinaryByteArrayCompleted(this, new UploadBinaryByteArrayCompletedEventArgs(invokeAsyncCompletedEventArgs.Results, invokeAsyncCompletedEventArgs.Error, invokeAsyncCompletedEventArgs.Cancelled, invokeAsyncCompletedEventArgs.UserState)); } } public void UploadBinaryByteArrayAsync(AccessTokenData accessToken, byte[] data) { this.UploadBinaryByteArrayAsync(accessToken, data, null); } public void UploadBinaryByteArrayAsync(AccessTokenData accessToken, byte[] data, object userState) { if (this.onBeginUploadBinaryByteArrayDelegate == null) { this.onBeginUploadBinaryByteArrayDelegate = new ClientBase<IStreamUpload>.BeginOperationDelegate(this.OnBeginUploadBinaryByteArray); } if (this.onEndUploadBinaryByteArrayDelegate == null) { this.onEndUploadBinaryByteArrayDelegate = new ClientBase<IStreamUpload>.EndOperationDelegate(this.OnEndUploadBinaryByteArray); } if (this.onUploadBinaryByteArrayCompletedDelegate == null) { this.onUploadBinaryByteArrayCompletedDelegate = new SendOrPostCallback(this.OnUploadBinaryByteArrayCompleted); } base.InvokeAsync(this.onBeginUploadBinaryByteArrayDelegate, new object[] { accessToken, data }, this.onEndUploadBinaryByteArrayDelegate, this.onUploadBinaryByteArrayCompletedDelegate, userState); } public void Dispose() { ClientHelper.DisposeClient(this); } } }
namespace AngleSharp.Core.Tests.Html { using AngleSharp.Dom.Html; using AngleSharp.Extensions; using NUnit.Framework; /// <summary> /// Tests generated according to the W3C-Test.org page: /// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-checkValidity.html /// </summary> [TestFixture] public class ValidityCheckTests { [Test] public void GetSubmissionReturnsNullWithInvalidForm() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.SetAttribute("maxLength", "4"); element.Value = "abcde"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; Assert.IsNotNull(fm); fm.AppendChild(element); document.Body.AppendChild(fm); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); Assert.IsNull(fm.GetSubmission(element)); } [Test] public void TestCheckvalidityInputText1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("text", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputText2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputText3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputText4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("search", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("tel", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("password", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "20"); element.Value = "http://www.example.com"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "http://www.example.com"); element.Value = "http://www.example.net"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "10"); element.Value = "[email protected]"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[email protected]"); element.Value = "[email protected]"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00Z"); element.Value = "2001-01-01T12:00:00Z"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-01-01T12:00:00Z"); element.Value = "2000-01-01T12:00:00Z"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = "2001-01-01T12:03:00Z"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01"); element.Value = "2001-01-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-01-01"); element.Value = "2000-01-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "172800000"); element.Value = "2001-01-03"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01"); element.Value = "2001-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-01"); element.Value = "2000-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "3"); element.Value = "2001-03"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = "2001-W01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-W01"); element.Value = "2000-W01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "1209600000"); element.Value = "2001-W03"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = "13:00:00"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "12:00:00"); element.Value = "11:00:00"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = "12:03:00"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "5"); element.Value = "6"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "5"); element.Value = "4"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "3"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputCheckbox1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "checkbox"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("checkbox", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputCheckbox2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "checkbox"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.SetAttribute("checked", null); element.SetAttribute("name", "test1"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("checkbox", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputRadio1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "radio"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("radio", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputRadio2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "radio"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.SetAttribute("checked", null); element.SetAttribute("name", "test1"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("radio", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputFile1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "file"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("file", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputFile2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "file"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.SetAttribute("files", "null"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("file", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvaliditySelect1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("select") as HtmlSelectElement; Assert.IsNotNull(element); var option1 = document.CreateElement<IHtmlOptionElement>(); option1.Text = "test1"; option1.Value = ""; var option2 = document.CreateElement<IHtmlOptionElement>(); option2.Text = "test1"; option2.Value = "1"; element.AddOption(option1); element.AddOption(option2); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvaliditySelect2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("select") as HtmlSelectElement; Assert.IsNotNull(element); var option1 = document.CreateElement<IHtmlOptionElement>(); option1.Text = "test1"; option1.Value = ""; var option2 = document.CreateElement<IHtmlOptionElement>(); option2.Text = "test1"; option2.Value = "1"; element.AddOption(option1); element.AddOption(option2); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityTextarea1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("textarea") as HtmlTextAreaElement; Assert.IsNotNull(element); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityTextarea2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("textarea") as HtmlTextAreaElement; Assert.IsNotNull(element); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } } }
// 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.Linq; using Microsoft.Test.ModuleCore; using Xunit; namespace System.Xml.Linq.Tests { public class Annotations { [Theory] [MemberData(nameof(GetXObjects))] public void AddStringAnnotation(XObject xo) { const string expected = "test string"; xo.AddAnnotation(expected); ValidateAnnotations(xo, new string[] { expected }); Assert.Equal(expected, xo.Annotation<string>()); Assert.Equal(expected, (string)xo.Annotation(typeof(string))); Assert.Equal(expected, xo.Annotation(typeof(object))); Assert.Equal(expected, xo.Annotation<object>()); } [Theory] [MemberData(nameof(GetXObjects))] public void AddIntAnnotation(XObject xo) { const int expected = 123456; xo.AddAnnotation(expected); ValidateAnnotations(xo, new object[] { expected }); Assert.Equal(expected, xo.Annotation<object>()); Assert.Equal(expected, (int)xo.Annotation(typeof(int))); Assert.Equal(expected, xo.Annotation(typeof(object))); } [Theory] [MemberData(nameof(GetXObjects))] public void AddIntAndStringAnnotation(XObject xo) { const string expectedStr = "<!@@63784sgdh111>"; const int expectedNum = 123456; xo.AddAnnotation(expectedStr); xo.AddAnnotation(expectedNum); ValidateAnnotations(xo, new object[] { expectedStr, expectedNum }); ValidateAnnotations(xo, new string[] { expectedStr }); Assert.Equal(expectedNum, (int)xo.Annotation(typeof(int))); Assert.Equal(expectedStr, xo.Annotation<string>()); Assert.Equal(expectedStr, (string)xo.Annotation(typeof(string))); } [Theory] [MemberData(nameof(GetXObjects))] public void AddRemoveGetAnnotation(XObject xo) { string str1 = "<!@@63784sgdh111>"; string str2 = "<!@@63784sgdh222>"; int num = 123456; xo.AddAnnotation(str1); xo.AddAnnotation(str2); xo.AddAnnotation(num); ValidateAnnotations(xo, new object[] { str1, str2, num }); ValidateAnnotations(xo, new string[] { str1, str2 }); xo.RemoveAnnotations<string>(); ValidateAnnotations(xo, new object[] { num }); xo.RemoveAnnotations(typeof(int)); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveAnnotationWithoutAdding(XObject xo) { xo.RemoveAnnotations<string>(); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); xo.RemoveAnnotations(typeof(int)); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddIntRemoveStringGetIntAnnotation(XObject xo) { const int num = 123456; xo.AddAnnotation(num); xo.RemoveAnnotations<string>(); ValidateAnnotations(xo, new object[] { num }); } [Theory] [MemberData(nameof(GetXObjects))] public void AddMultipleStringAnnotations(XObject xo) { const string str1 = "<!@@63784sgdh111>"; const string str2 = "sdjverqjbe4 kjvweh342$$% "; xo.AddAnnotation(str1); xo.AddAnnotation(str2); ValidateAnnotations(xo, new string[] { str1, str2 }); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveAnnotationTwice(XObject xo) { xo.RemoveAnnotations<object>(); xo.RemoveAnnotations<object>(); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddGenericAnnotation(XObject xo) { Dictionary<string, string> d = new Dictionary<string, string>(); xo.AddAnnotation(d); ValidateAnnotations(xo, new Dictionary<string, string>[] { d }); Assert.Equal(d, xo.Annotation<Dictionary<string, string>>()); Assert.Equal(d, (Dictionary<string, string>)xo.Annotation(typeof(Dictionary<string, string>))); Assert.Equal(d, xo.Annotation<object>()); Assert.Equal(d, xo.Annotation(typeof(object))); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveGenericAnnotation(XObject xo) { Dictionary<string, string> d = new Dictionary<string, string>(); xo.AddAnnotation(d); xo.RemoveAnnotations<Dictionary<string, string>>(); Assert.Equal(expected: 0, actual: CountAnnotations<Dictionary<string, string>>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddInheritedAnnotation(XObject xo) { A a = new A(); B b = new B(); xo.AddAnnotation(a); xo.AddAnnotation(b); ValidateAnnotations(xo, new A[] { a, b }); ValidateAnnotations(xo, new B[] { b }); Assert.Equal(b, xo.Annotation<B>()); Assert.Equal(b, (B)xo.Annotation(typeof(B))); Assert.Equal(a, xo.Annotation<A>()); Assert.Equal(a, (A)xo.Annotation(typeof(A))); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveInheritedAnnotation(XObject xo) { A a = new A(); B b = new B(); xo.AddAnnotation(a); xo.AddAnnotation(b); xo.RemoveAnnotations<B>(); ValidateAnnotations(xo, new A[] { a }); Assert.Equal(a, xo.Annotation<A>()); Assert.Equal(a, (A)xo.Annotation(typeof(A))); Assert.Equal(a, xo.Annotation<object>()); Assert.Equal(a, xo.Annotation(typeof(object))); Assert.Equal(0, CountAnnotations<B>(xo)); xo.RemoveAnnotations(typeof(A)); Assert.Equal(0, CountAnnotations<A>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddNull(XObject xo) { AssertExtensions.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation(null)); Assert.Null(xo.Annotation<object>()); AssertExtensions.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation(null)); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveNull(XObject xo) { AssertExtensions.Throws<ArgumentNullException>("type", () => xo.RemoveAnnotations(null)); AssertExtensions.Throws<ArgumentNullException>("type", () => xo.RemoveAnnotations(null)); } [Theory] [MemberData(nameof(GetXObjects))] public void GetAllNull(XObject xo) { AssertExtensions.Throws<ArgumentNullException>("type", () => xo.Annotations(null)); AssertExtensions.Throws<ArgumentNullException>("type", () => xo.Annotations(null)); } [Theory] [MemberData(nameof(GetXObjects))] public void GetOneNull(XObject xo) { AssertExtensions.Throws<ArgumentNullException>("type", () => xo.Annotation(null)); AssertExtensions.Throws<ArgumentNullException>("type", () => xo.Annotation(null)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddNullString(XObject xo) { AssertExtensions.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation((string)null)); Assert.Null(xo.Annotation<object>()); AssertExtensions.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation((string)null)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddAnnotationWithSameClassNameButDifferentNamespace(XObject xo) { DifferentNamespace.A a1 = new DifferentNamespace.A(); A a2 = new A(); xo.AddAnnotation(a1); xo.AddAnnotation(a2); ValidateAnnotations(xo, new DifferentNamespace.A[] { a1 }); ValidateAnnotations(xo, new A[] { a2 }); Assert.Equal(a1, xo.Annotation<DifferentNamespace.A>()); Assert.Equal(a1, (DifferentNamespace.A)xo.Annotation(typeof(DifferentNamespace.A))); Assert.Equal(a2, xo.Annotation<A>()); Assert.Equal(a2, (A)xo.Annotation(typeof(A))); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveAnnotationWithSameClassNameButDifferentNamespace(XObject xo) { DifferentNamespace.A a1 = new DifferentNamespace.A(); A a2 = new A(); xo.AddAnnotation(a1); xo.AddAnnotation(a2); xo.RemoveAnnotations<DifferentNamespace.A>(); Assert.Equal(expected: 0, actual: CountAnnotations<DifferentNamespace.A>(xo)); ValidateAnnotations<A>(xo, new A[] { a2 }); Assert.Equal(a2, xo.Annotation<A>()); Assert.Equal(a2, (A)xo.Annotation(typeof(A))); xo.RemoveAnnotations(typeof(A)); Assert.Equal(expected: 0, actual: CountAnnotations<A>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo) { AddAnnotation(xo); foreach (Type type in GetTypes()) { RemoveAnnotations(xo, type); } Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveTwiceAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo) { foreach (Type type in GetTypes()) { RemoveAnnotations(xo, type); } foreach (Type type in GetTypes()) { RemoveAnnotations(xo, type); } Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void AddTwiceRemoveOnceAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo) { AddAnnotation(xo); int count = CountAnnotations<object>(xo) * 2; AddAnnotation(xo); Assert.Equal(expected: count, actual: CountAnnotations<object>(xo)); foreach (Type type in GetTypes()) { RemoveAnnotations(xo, type); } Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Fact] public void AddAnnotationAndClone() { // Add annotation to XElement, and clone this element to another subtree, get null annotation const string expected = "element1111"; XElement element1 = new XElement("e", new XAttribute("a", "value")); element1.AddAnnotation(expected); XElement element2 = new XElement(element1); ValidateAnnotations(element1, new string[] { expected }); Assert.Equal(expected, element1.Annotation<string>()); Assert.Equal(expected, element1.Annotation(typeof(string))); Assert.Equal(0, CountAnnotations<string>(element2)); } [Fact] public void AddAnnotationXElementRemoveAndGet() { // Add annotation to XElement, and remove this element, get annotation const string expected = "element1111"; XElement root = new XElement("root"); XElement element = new XElement("elem1"); root.Add(element); element.AddAnnotation(expected); element.Remove(); ValidateAnnotations(element, new string[] { expected }); Assert.Equal(expected, element.Annotation<string>()); Assert.Equal(expected, element.Annotation(typeof(string))); } [Fact] public void AddAnnotationToParentAndChildAndValIdate() { // Add annotation to parent and child, valIdate annotations for each XObjects string str1 = "root 1111"; string str2 = "element 1111"; XElement root = new XElement("root"); XElement element = new XElement("elem1"); root.Add(element); root.AddAnnotation(str1); element.AddAnnotation(str2); ValidateAnnotations(root, new string[] { str1 }); Assert.Equal(str1, root.Annotation<string>()); Assert.Equal(str1, root.Annotation(typeof(string))); ValidateAnnotations(element, new string[] { str2 }); Assert.Equal(str2, element.Annotation<string>()); Assert.Equal(str2, element.Annotation(typeof(string))); } [Theory] [MemberData(nameof(GetXObjects))] public void AddAnnotationsAndRemoveOfTypeObject(XObject xo) { AddAnnotation(xo); RemoveAnnotations(xo, typeof(object)); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void EnumerateAnnotationsWithoutAdding(XObject xo) { Assert.Null(xo.Annotation(typeof(object))); Assert.Null(xo.Annotation<object>()); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); Assert.Equal(expected: 0, actual: CountAnnotations<string>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveAnnotationsUsingTypeObject(XObject xo) { AddAnnotation(xo); RemoveAnnotations<object>(xo); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } [Theory] [MemberData(nameof(GetXObjects))] public void RemoveTwiceAnnotationsWithoutAddingUsingTypeObject(XObject xo) { RemoveAnnotations<object>(xo); RemoveAnnotations<object>(xo); Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo)); } // // helpers // public static IEnumerable<object[]> GetXObjects() { yield return new object[] { new XDocument() }; yield return new object[] { new XAttribute("attr", "val") }; yield return new object[] { new XElement("elem1") }; yield return new object[] { new XText("text1") }; yield return new object[] { new XComment("comment1") }; yield return new object[] { new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1") }; yield return new object[] { new XCData("cdata cdata") }; yield return new object[] { new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1dtd1", "dtd1dtd1dtd1dtd1") }; } public static object[] GetObjects() { object[] aObject = new object[] { new A(), new B(), new DifferentNamespace.A(), new DifferentNamespace.B(), "stringstring", 12345, new Dictionary<string, string>(), new XDocument(), new XAttribute("attr", "val"), new XElement("elem1"), new XText("text1 text1"), new XComment("comment1 comment1"), new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1"), new XCData("cdata cdata"), new XDeclaration("234", "UTF-8", "yes"), XNamespace.Xmlns, //new XStreamingElement("elementSequence"), new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1 dtd1", "dtd1 dtd1 dtd1 ") }; return aObject; } private static void ValidateAnnotations<T>(XObject xo, T[] values) where T : class { // // use inefficient n^2 algorithm, which is OK for our testing purposes // assumes that all items are unique // int count = CountAnnotations<T>(xo); TestLog.Compare(count, values.Length, "unexpected number of annotations"); foreach (T value in values) { // // use non-generics enum first // bool found = false; foreach (T annotation in xo.Annotations(typeof(T))) { if (annotation.Equals(value)) { found = true; break; } } TestLog.Compare(found, "didn't find value using non-generic enumeration"); // // now double check with generics one // found = false; foreach (T annotation in xo.Annotations<T>()) { if (annotation.Equals(value)) { found = true; break; } } TestLog.Compare(found, "didn't find value using generic enumeration"); } } private static int CountAnnotations<T>(XObject xo) where T : class { int count = xo.Annotations(typeof(T)).Count(); Assert.Equal(count, xo.Annotations<T>().Count()); // Generics and non-generics annotations enumerations returned different number of objects return count; } private static void AddAnnotation(XObject xo) { foreach (object o in GetObjects()) { xo.AddAnnotation(o); } } private static void RemoveAnnotations(XObject xo, Type type) { xo.RemoveAnnotations(type); } private static void RemoveAnnotations<T>(XObject xo) where T : class { xo.RemoveAnnotations<T>(); } private static Type[] GetTypes() { Type[] types = new Type[] { typeof(string), typeof(int), typeof(Dictionary<string, string>), typeof(A), typeof(B), typeof(DifferentNamespace.A), typeof(DifferentNamespace.B), typeof(XAttribute), typeof(XElement), typeof(Extensions), typeof(XDocument), typeof(XText), typeof(XName), typeof(XComment), typeof(XProcessingInstruction), typeof(XCData), typeof(XDeclaration), typeof(XNamespace), //typeof(XStreamingElement), typeof(XDocumentType) }; return types; } public class A { } public class B : A { } } namespace DifferentNamespace { public class A { } public class B : A { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Runtime; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal static class WebSocketHelper { internal const int OperationNotStarted = 0; internal const int OperationFinished = 1; internal const string SecWebSocketKey = "Sec-WebSocket-Key"; internal const string SecWebSocketVersion = "Sec-WebSocket-Version"; internal const string SecWebSocketProtocol = "Sec-WebSocket-Protocol"; internal const string SecWebSocketAccept = "Sec-WebSocket-Accept"; internal const string MaxPendingConnectionsString = "MaxPendingConnections"; internal const string WebSocketTransportSettingsString = "WebSocketTransportSettings"; internal const string CloseOperation = "CloseOperation"; internal const string SendOperation = "SendOperation"; internal const string ReceiveOperation = "ReceiveOperation"; internal static readonly char[] ProtocolSeparators = new char[] { ',' }; private const string WebSocketKeyPostString = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private const string SchemeWs = "ws"; private const string SchemeWss = "wss"; private static readonly int s_PropertyBufferSize = ((2 * Marshal.SizeOf<uint>()) + Marshal.SizeOf<bool>()) + IntPtr.Size; private static readonly HashSet<char> s_InvalidSeparatorSet = new HashSet<char>(new char[] { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ' }); private static string s_currentWebSocketVersion; internal static string ComputeAcceptHeader(string webSocketKey) { Fx.Assert(webSocketKey != null, "webSocketKey should not be null."); throw ExceptionHelper.PlatformNotSupported(); } internal static int ComputeClientBufferSize(long maxReceivedMessageSize) { return ComputeInternalBufferSize(maxReceivedMessageSize, false); } internal static int GetReceiveBufferSize(long maxReceivedMessageSize) { int effectiveMaxReceiveBufferSize = maxReceivedMessageSize <= WebSocketDefaults.BufferSize ? (int)maxReceivedMessageSize : WebSocketDefaults.BufferSize; return Math.Max(WebSocketDefaults.MinReceiveBufferSize, effectiveMaxReceiveBufferSize); } internal static bool UseWebSocketTransport(WebSocketTransportUsage transportUsage, bool isContractDuplex) { return transportUsage == WebSocketTransportUsage.Always || (transportUsage == WebSocketTransportUsage.WhenDuplex && isContractDuplex); } internal static Uri GetWebSocketUri(Uri httpUri) { Fx.Assert(httpUri != null, "RemoteAddress.Uri should not be null."); UriBuilder builder = new UriBuilder(httpUri); if (UriEx.UriSchemeHttp.Equals(httpUri.Scheme, StringComparison.OrdinalIgnoreCase)) { builder.Scheme = SchemeWs; } else { Fx.Assert( UriEx.UriSchemeHttps.Equals(httpUri.Scheme, StringComparison.OrdinalIgnoreCase), "httpUri.Scheme should be http or https."); builder.Scheme = SchemeWss; } return builder.Uri; } internal static bool IsWebSocketUri(Uri uri) { return uri != null && (WebSocketHelper.SchemeWs.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase) || WebSocketHelper.SchemeWss.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase)); } internal static Uri NormalizeWsSchemeWithHttpScheme(Uri uri) { Fx.Assert(uri != null, "RemoteAddress.Uri should not be null."); if (!IsWebSocketUri(uri)) { return uri; } UriBuilder builder = new UriBuilder(uri); switch (uri.Scheme.ToLowerInvariant()) { case SchemeWs: builder.Scheme = UriEx.UriSchemeHttp; break; case SchemeWss: builder.Scheme = UriEx.UriSchemeHttps; break; default: break; } return builder.Uri; } internal static bool TryParseSubProtocol(string subProtocolValue, out List<string> subProtocolList) { subProtocolList = new List<string>(); if (subProtocolValue != null) { string[] parsedTokens = subProtocolValue.Split(ProtocolSeparators, StringSplitOptions.RemoveEmptyEntries); string invalidChar; for (int i = 0; i < parsedTokens.Length; i++) { string token = parsedTokens[i]; if (!string.IsNullOrWhiteSpace(token)) { token = token.Trim(); if (!IsSubProtocolInvalid(token, out invalidChar)) { // Note that we could be adding a duplicate to this list. According to the specification the header should not include // duplicates but we aim to be "robust in what we receive" so we will allow it. The matching code that consumes this list // will take the first match so duplicates will not affect the outcome of the negotiation process. subProtocolList.Add(token); } else { FxTrace.Exception.AsWarning(new HttpRequestException( SR.Format(SR.WebSocketInvalidProtocolInvalidCharInProtocolString, token, invalidChar))); return false; } } } } return true; } internal static bool IsSubProtocolInvalid(string protocol, out string invalidChar) { Fx.Assert(protocol != null, "protocol should not be null"); char[] chars = protocol.ToCharArray(); for (int i = 0; i < chars.Length; i++) { char ch = chars[i]; if (ch < 0x21 || ch > 0x7e) { invalidChar = string.Format(CultureInfo.InvariantCulture, "[{0}]", (int)ch); return true; } if (s_InvalidSeparatorSet.Contains(ch)) { invalidChar = ch.ToString(); return true; } } invalidChar = null; return false; } internal static string GetCurrentVersion() { if (s_currentWebSocketVersion == null) { s_currentWebSocketVersion = string.Empty; throw ExceptionHelper.PlatformNotSupported(); } return s_currentWebSocketVersion; } internal static WebSocketTransportSettings GetRuntimeWebSocketSettings(WebSocketTransportSettings settings) { WebSocketTransportSettings runtimeSettings = settings.Clone(); return runtimeSettings; } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule, Justification = "The exceptions thrown here are already wrapped.")] internal static void ThrowCorrectException(Exception ex) { throw ConvertAndTraceException(ex); } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule, Justification = "The exceptions thrown here are already wrapped.")] internal static void ThrowCorrectException(Exception ex, TimeSpan timeout, string operation) { throw ConvertAndTraceException(ex, timeout, operation); } internal static Exception ConvertAndTraceException(Exception ex) { return ConvertAndTraceException( ex, TimeSpan.MinValue, // this is a dummy since operation type is null, so the timespan value won't be used null); } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103:ThrowWrappedExceptionsRule", Justification = "The exceptions wrapped here will be thrown out later.")] internal static Exception ConvertAndTraceException(Exception ex, TimeSpan timeout, string operation) { ObjectDisposedException objectDisposedException = ex as ObjectDisposedException; if (objectDisposedException != null) { CommunicationObjectAbortedException communicationObjectAbortedException = new CommunicationObjectAbortedException(ex.Message, ex); FxTrace.Exception.AsWarning(communicationObjectAbortedException); return communicationObjectAbortedException; } AggregateException aggregationException = ex as AggregateException; if (aggregationException != null) { Exception exception = FxTrace.Exception.AsError<OperationCanceledException>(aggregationException); OperationCanceledException operationCanceledException = exception as OperationCanceledException; if (operationCanceledException != null) { TimeoutException timeoutException = GetTimeoutException(exception, timeout, operation); FxTrace.Exception.AsWarning(timeoutException); return timeoutException; } else { Exception communicationException = ConvertAggregateExceptionToCommunicationException(aggregationException); if (communicationException is CommunicationObjectAbortedException) { FxTrace.Exception.AsWarning(communicationException); return communicationException; } else { return FxTrace.Exception.AsError(communicationException); } } } return FxTrace.Exception.AsError(ex); } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103", Justification = "The exceptions will be wrapped by the callers.")] internal static Exception ConvertAggregateExceptionToCommunicationException(AggregateException ex) { Exception exception = FxTrace.Exception.AsError<Exception>(ex); ObjectDisposedException objectDisposedException = exception as ObjectDisposedException; if (objectDisposedException != null) { return new CommunicationObjectAbortedException(exception.Message, exception); } return new CommunicationException(exception.Message, exception); } internal static void ThrowExceptionOnTaskFailure(Task task, TimeSpan timeout, string operation) { if (task.IsFaulted) { throw FxTrace.Exception.AsError<CommunicationException>(task.Exception); } if (task.IsCanceled) { throw FxTrace.Exception.AsError(GetTimeoutException(null, timeout, operation)); } } // TODO: Move to correct place alphabetically, it's here temporariliy to make editting easier internal static Exception CreateExceptionOnTaskFailure(Task task, TimeSpan timeout, string operation) { if (task.IsFaulted) { return FxTrace.Exception.AsError<CommunicationException>(task.Exception); } if (task.IsCanceled) { throw FxTrace.Exception.AsError(GetTimeoutException(null, timeout, operation)); } return null; } internal static TimeoutException GetTimeoutException(Exception innerException, TimeSpan timeout, string operation) { string errorMsg = string.Empty; if (operation != null) { switch (operation) { case WebSocketHelper.CloseOperation: errorMsg = SR.Format(SR.CloseTimedOut, timeout); break; case WebSocketHelper.SendOperation: errorMsg = SR.Format(SR.WebSocketSendTimedOut, timeout); break; case WebSocketHelper.ReceiveOperation: errorMsg = SR.Format(SR.WebSocketReceiveTimedOut, timeout); break; default: errorMsg = SR.Format(SR.WebSocketOperationTimedOut, operation, timeout); break; } } return innerException == null ? new TimeoutException(errorMsg) : new TimeoutException(errorMsg, innerException); } private static int ComputeInternalBufferSize(long maxReceivedMessageSize, bool isServerBuffer) { const int NativeOverheadBufferSize = 144; /* LAYOUT: | Native buffer | PayloadReceiveBuffer | PropertyBuffer | | RBS + SBS + 144 | RBS | PBS | | Only WSPC may modify | Only WebSocketBase may modify | *RBS = ReceiveBufferSize, *SBS = SendBufferSize *PBS = PropertyBufferSize (32-bit: 16, 64 bit: 20 bytes) */ int nativeSendBufferSize = isServerBuffer ? WebSocketDefaults.MinSendBufferSize : WebSocketDefaults.BufferSize; return (2 * GetReceiveBufferSize(maxReceivedMessageSize)) + nativeSendBufferSize + NativeOverheadBufferSize + s_PropertyBufferSize; } } }
using Microsoft.Win32; using Orangemile.Cy.Holder; using Orangemile.Cy.Param; using Orangemile.Cy.Util; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Orangemile.Cy { [Guid("4A4A7323-2901-46F9-AA0C-9DD84B2F37BC")] [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] [Description("Fabric Functions")] public class Functions : IFunctions { private TdsContainer tdsContainer = new TdsContainer(); private Dictionary<string, string> properties = new Dictionary<string, string>(); private string env; private string serviceUrl; public Functions() { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolver); loadProperties(); } public Functions(object ctrl) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolver); loadProperties(); if (ctrl != null) { this.fabSetEnv(ctrl); } } private void loadProperties() { string root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filepath = root + "/cy.properties"; if (File.Exists(filepath)) { foreach (var row in File.ReadAllLines(filepath)) { properties.Add(row.Split('=')[0].Trim().ToLower(), string.Join("=", row.Split('=').Skip(1).ToArray()).Trim() ); } } } private string getFunctionUrl(string funcname) { string url = null; // try with service url if (serviceUrl != null) { url = serviceUrl + '/' + funcname; } // try as environment if ( url == null && env != null ) { string key = ("env." + env + "." + funcname).ToLower(); if ( ! properties.TryGetValue(key, out url) ) { key = ("env." + env).ToLower(); if ( properties.TryGetValue(key, out url) ) { url += '/' + funcname; } } } // not found if (url == null) { throw new Exception( "Environment not set. Call =fabSetEnv('env') or =fabSetEnv('serviceUrl')"); } return url; } #region TDS public object tdsStat(string name, object ctrl = null, object flag = null) { try { if (name.StartsWith("#") || name.StartsWith("&")) { name = name.Substring(1); } Tds tds = tdsContainer.getTds(name, true); return "r: " + tds.getRowCount() + ", c: " + tds.getColumnCount(); } catch (Exception e) { return "#error: " + e.ToString(); } } public object tdsGet(string name, object ctrl = null, object flag = null) { try { if (name.StartsWith("#") || name.StartsWith("&")) { name = name.Substring(1); } object[,] data = tdsContainer.getTdsData(name, true); return data; } catch (Exception e) { return "#error: " + e.ToString(); } } public object tds(string name, object ctrl = null, object flag = null) { try { Params ctrlParams = ParamBuilder.buildParams(ctrl, tdsContainer); object[,] data = ctrlParams.asTds(); tdsContainer.add(new InMemoryTds(name, data)); return name; } catch (Exception e) { return "#error: " + e.Message; } } public object tdsFile(string name, object ctrl = null, object flag = null) { try { Params ctrlParams = ParamBuilder.buildParams(ctrl, tdsContainer); string file = (string)ctrlParams.getOneValue(new string[] { "file", "filename", "path", "file_name"}); string ext = Path.GetExtension(file); if (ext == ".xls" || ext == ".xlsx" || ext == ".xlsb") { // TODO: read excel throw new Exception("Excel file is not currently supported"); } else { Tds tds = TdsUtils.readFile(name, file, ctrlParams); tdsContainer.add(tds); } return name; } catch (Exception e) { return "#error: " + e.Message; } } #endregion public object fabInfo(object ctrl = null, object flag = null) { try { Params ctrlParams = ParamBuilder.buildParams(ctrl, tdsContainer); if ( ctrlParams.hasKey("version", "ver") ) { return Assembly.GetExecutingAssembly().GetName().Version; } else if (ctrlParams.hasKey("env")) { return (env == null?"unknown": env); } else if (ctrlParams.hasKey("user")) { object[,] data = new object[2, 6]; data[0, 0] = "username"; data[1, 0] = System.Security.Principal.WindowsIdentity.GetCurrent().Name; data[0, 1] = "user"; data[1, 1] = System.Environment.UserName; data[0, 2] = "host"; data[1, 2] = System.Environment.MachineName; data[0, 3] = "timestamp"; data[1, 3] = DateTime.UtcNow.ToString("o"); data[0, 4] = "process"; data[1, 4] = System.Diagnostics.Process.GetCurrentProcess().ProcessName; data[0, 5] = "env"; data[1, 5] = (env == null ? "unknown" : env); return data; } else if (ctrlParams.hasKey("42")) { return "Answer to the Ultimate Question of Life, the Universe, and Everything"; } else if (ctrlParams.hasKey("help") || ctrlParams.hasKey("wiki")) { string wikiurl = null; if (properties.TryGetValue("wiki", out wikiurl)) { Process.Start("IExplore.exe", wikiurl); } return "DON'T PANIC"; } return "#error: Unknown command"; } catch (Exception e) { return "#error:" + e.ToString(); } } public object fabSetEnv(object ctrl = null, object flag = null) { try { Params ctrlParams = ParamBuilder.buildParams(ctrl, tdsContainer); object _url = ctrlParams.getOneValue(new string[] {"url", "serviceUrl", "serverUrl"}); object _env = ctrlParams.getOneValue(new string[] { "env" }); if (_url != null) { serviceUrl = "" + _url; return serviceUrl; } else if ( _env != null ) { if ( _env.ToString().StartsWith("http",StringComparison.CurrentCultureIgnoreCase) ) { serviceUrl = "" + _env; } else { env = _env.ToString().ToLower(); } return _env; } return "#warn: unknown key. Supported(url)"; } catch (Exception e) { return "#error:" + e.ToString(); } } [Description("fabGet")] public string fabGet(string tdsname, string funcname, object ctrl = null, object flag = null) { string url = null; try { url = getFunctionUrl(funcname); Params flagParams = ParamBuilder.buildParams(flag, tdsContainer); Params ctrlParams = ParamBuilder.buildParams(ctrl, tdsContainer); NameValueCollection values = ctrlParams.asNameValueCollection(); values.Add("_username", System.Security.Principal.WindowsIdentity.GetCurrent().Name); values.Add("_user", System.Environment.UserName); values.Add("_host", System.Environment.MachineName); values.Add("_timestamp", DateTime.UtcNow.ToString("o")); values.Add("_process", System.Diagnostics.Process.GetCurrentProcess().ProcessName ); values.Add("_url", url); values.Add("_env", (env == null ? "unknown" : env)); object[,] data = HttpUtil.httpPut(url, values, flagParams); tdsContainer.add(new InMemoryTds(tdsname, data)); return tdsname; } catch (Exception e) { return "#error: " + e.Message + ", url=" + url; } } #region Plumbing static Assembly AssemblyResolver(object source, ResolveEventArgs e) { Console.WriteLine("Resolving {0}", e.Name); // Assembly.LoadFrom(String) return Assembly.Load(e.Name); } [ComRegisterFunctionAttribute] public static void RegisterFunction(Type type) { Registry.ClassesRoot.CreateSubKey(GetSubKeyName(type, "Programmable")); RegistryKey key = Registry.ClassesRoot.OpenSubKey(GetSubKeyName(type, "InprocServer32"), true); key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll", RegistryValueKind.String); } [ComUnregisterFunctionAttribute] public static void UnregisterFunction(Type type) { Registry.ClassesRoot.DeleteSubKey(GetSubKeyName(type, "Programmable"), false); } private static string GetSubKeyName(Type type, string subKeyName) { System.Text.StringBuilder s = new System.Text.StringBuilder(); s.Append(@"CLSID\{"); s.Append(type.GUID.ToString().ToUpper()); s.Append(@"}\"); s.Append(subKeyName); return s.ToString(); } [ComVisible(false)] public override string ToString() { return base.ToString(); } [ComVisible(false)] public override bool Equals(object obj) { return base.Equals(obj); } [ComVisible(false)] public override int GetHashCode() { return base.GetHashCode(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; //IEnumerator using System.Collections.Generic; //List<T> namespace Microsoft.Test.ModuleCore { //////////////////////////////////////////////////////////////// // TestInput // //////////////////////////////////////////////////////////////// public class TestInput { //Data private static TestProps s_pproperties; private static String s_pinitstring; private static String s_pcommandline; //Constructor static public TestProps Properties { get { if (s_pproperties == null) { s_pproperties = new TestProps(new TestProperties()); //CommandLine String commandline = s_pcommandline; s_pproperties["CommandLine"] = commandline; //CommandLine Options KeywordParser.Tokens tokens = new KeywordParser.Tokens(); tokens.Equal = " "; tokens.Seperator = "/"; Dictionary<string, string> options = KeywordParser.ParseKeywords(commandline, tokens); foreach (String key in options.Keys) s_pproperties["CommandLine/" + key] = options[key]; } return s_pproperties; } set { if (value != null) { //Clear between each run s_pproperties = null; //InitString keywords String initstring = value["Alias/InitString"]; TestInput.Properties["Alias/InitString"] = initstring; Dictionary<string, string> keywords = KeywordParser.ParseKeywords(initstring); foreach (String key in keywords.Keys) TestInput.Properties["Alias/InitString/" + key] = keywords[key] as String; // Command line keywords (if any) TestProp commandLineProp = value.Get("CommandLine"); if (commandLineProp != null) { string commandLine = value["CommandLine"]; TestInput.Properties["CommandLine"] = commandLine; //CommandLine Options KeywordParser.Tokens tokens = new KeywordParser.Tokens(); tokens.Equal = " "; tokens.Seperator = "/"; Dictionary<string, string> options = KeywordParser.ParseKeywords(commandLine, tokens); foreach (String key in options.Keys) TestInput.Properties["CommandLine/" + key] = options[key]; } } } } public static bool IsTestCaseSelected(string testcasename) { bool ret = true; string testcasefilter = Properties["CommandLine/testcase"]; if (testcasefilter != null && testcasefilter != "*" && testcasefilter != testcasename) { ret = false; } return ret; } public static bool IsVariationSelected(string variationname) { bool ret = true; string variationfilter = s_pproperties["variation"]; if (variationfilter != null && variationfilter != "*" && variationfilter != variationname) { ret = false; } return ret; } static internal void Dispose() { //Reset the info. //Since this is a static class, (to make it simplier to access from anywhere in your code) //we need to reset this info everytime a test is run - so if you don't select an alias //the next time it doesn't use the previous alias setting - ie: ProviderInfo doesn't //get called when no alias is selected... s_pproperties = null; s_pinitstring = null; s_pcommandline = null; } static public string InitString { get { //Useful typed getter if (s_pinitstring == null) s_pinitstring = TestInput.Properties["Alias/InitString"]; return s_pinitstring; } } static public string CommandLine { get { //Useful typed getter if (s_pcommandline == null) s_pcommandline = TestInput.Properties["CommandLine"]; return s_pcommandline; } set { s_pcommandline = value; } } static public String Filter { get { if (TestInput.Properties != null) return TestInput.Properties["CommandLine/Filter"]; return null; } } static public String MaxPriority { get { if (TestInput.Properties != null) return TestInput.Properties["CommandLine/MaxPriority"]; return null; } } } //////////////////////////////////////////////////////////////// // TestProps // //////////////////////////////////////////////////////////////// public class TestProps : ITestProperties, IEnumerable, IEnumerator { //Data protected ITestProperties pinternal; protected int penum = -1; //Constructor public TestProps(ITestProperties properties) { pinternal = properties; } //Accessors public virtual ITestProperties Internal { get { return pinternal; } } public virtual int Count { get { if (pinternal != null) return pinternal.Count; return 0; } } public virtual TestProp this[int index] { get { ITestProperty property = pinternal.GetItem(index); if (property != null) return new TestProp(property); return null; } } public virtual String this[String name] { get { ITestProperty property = pinternal.Get(name); if (property != null) return StringEx.ToString(property.Value); return null; } set { this.Add(name).Value = value; } } public virtual TestProp Get(String name) { ITestProperty property = pinternal.Get(name); if (property != null) return new TestProp(property); return null; } public virtual TestProp Add(String name) { return new TestProp(pinternal.Add(name)); } public virtual void Remove(String name) { pinternal.Remove(name); } public virtual IEnumerator GetEnumerator() { return this; } public virtual bool MoveNext() { if (penum + 1 >= this.Count) return false; penum++; return true; } public virtual Object Current { get { return this[penum]; } } public virtual void Reset() { penum = -1; } public virtual void Clear() { if (pinternal != null) pinternal.Clear(); } ITestProperty ITestProperties.Add(String name) { return pinternal.Add(name); } ITestProperty ITestProperties.Get(String name) { return pinternal.Get(name); } ITestProperty ITestProperties.GetItem(int index) { return pinternal.GetItem(index); } } //////////////////////////////////////////////////////////////// // TestProp // //////////////////////////////////////////////////////////////// public class TestProp : ITestProperty, IEnumerable { //Data protected ITestProperty pinternal; //Constructor public TestProp(ITestProperty property) { pinternal = property; } //Accessors public virtual ITestProperty Internal { get { return pinternal; } } public virtual String Name { get { return pinternal.Name; } } public virtual String Desc { get { return pinternal.Desc; } } public virtual TestPropertyFlags Flags { get { return pinternal.Flags; } set { pinternal.Flags = value; } } public virtual Object Value { get { return pinternal.Value; } set { pinternal.set_Value(ref value); } } public virtual TestProps Children { get { return new TestProps(pinternal.Children); } } public virtual IEnumerator GetEnumerator() { return this.Children; } void ITestProperty.set_Value(ref object value) { pinternal.set_Value(ref value); } ITestProperties ITestProperty.Children { get { return pinternal.Children; } } ITestProperties ITestProperty.Metadata { get { return pinternal.Metadata; } } } //////////////////////////////////////////////////////////////// // TestProperty // //////////////////////////////////////////////////////////////// public class TestProperty : ITestProperty { //Data protected String pname = null; protected String pdesc = null; protected Object pvalue = null; protected TestPropertyFlags pflags = 0; protected TestProperties pmetadata = null; protected TestProperties pchildren = null; //Constructor public TestProperty(String name, Object value) { pname = name; pvalue = value; } //Accessors public string Name { get { return pname; } set { pname = value; } } public string Desc { get { return pdesc; } set { pdesc = value; } } public TestPropertyFlags Flags { get { return pflags; } set { pflags = value; } } public object Value { get { return pvalue; } set { pvalue = value; } } public void set_Value(ref object value) { pvalue = value; } public ITestProperties Metadata { get { return pmetadata; } } public ITestProperties Children { get { return pchildren; } } } //////////////////////////////////////////////////////////////// // TestProperties // //////////////////////////////////////////////////////////////// public class TestProperties : ITestProperties, IEnumerable { //Data protected List<TestProperty> plist = null; //Constructor public TestProperties() { plist = new List<TestProperty>(); } //Methods public virtual int Count { get { return plist.Count; } } public virtual TestProperty this[int index] { get { return plist[index]; } } public virtual Object this[String name] { get { ITestProperty property = this.Get(name); if (property != null) return property.Value; return null; } set { this.Add(name).Value = value; } } public virtual int IndexOf(string name) { int count = plist.Count; for (int i = 0; i < count; i++) { if (String.Compare(plist[i].Name, name) == 0) return i; } return -1; } public virtual IEnumerator GetEnumerator() { return plist.GetEnumerator(); } ITestProperty ITestProperties.GetItem(int index) { return this[index]; } public virtual ITestProperty Get(String name) { int index = this.IndexOf(name); if (index >= 0) return plist[index]; return null; } ITestProperty ITestProperties.Add(String name) { return (TestProperty)Add(name); } public virtual TestProperty Add(String name) { //Exists int index = this.IndexOf(name); if (index >= 0) return plist[index]; //Otherwise add TestProperty property = new TestProperty(name, null); plist.Add(property); return property; } public virtual void Remove(String name) { int index = this.IndexOf(name); if (index >= 0) plist.RemoveAt(index); } public virtual void Clear() { plist.Clear(); } } }
/* * Copyright (c) 2006-2014, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using OpenMetaverse; namespace OpenMetaverse { /// <summary> /// /// </summary> public enum FieldType { /// <summary></summary> U8, /// <summary></summary> U16, /// <summary></summary> U32, /// <summary></summary> U64, /// <summary></summary> S8, /// <summary></summary> S16, /// <summary></summary> S32, /// <summary></summary> F32, /// <summary></summary> F64, /// <summary></summary> UUID, /// <summary></summary> BOOL, /// <summary></summary> Vector3, /// <summary></summary> Vector3d, /// <summary></summary> Vector4, /// <summary></summary> Quaternion, /// <summary></summary> IPADDR, /// <summary></summary> IPPORT, /// <summary></summary> Variable, /// <summary></summary> Fixed, /// <summary></summary> Single, /// <summary></summary> Multiple } /// <summary> /// /// </summary> public class MapField : IComparable { /// <summary></summary> public int KeywordPosition; /// <summary></summary> public string Name; /// <summary></summary> public FieldType Type; /// <summary></summary> public int Count; /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(object obj) { MapField temp = (MapField)obj; if (this.KeywordPosition > temp.KeywordPosition) { return 1; } else { if(temp.KeywordPosition == this.KeywordPosition) { return 0; } else { return -1; } } } } /// <summary> /// /// </summary> public class MapBlock : IComparable { /// <summary></summary> public int KeywordPosition; /// <summary></summary> public string Name; /// <summary></summary> public int Count; /// <summary></summary> public List<MapField> Fields; /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(object obj) { MapBlock temp = (MapBlock)obj; if (this.KeywordPosition > temp.KeywordPosition) { return 1; } else { if(temp.KeywordPosition == this.KeywordPosition) { return 0; } else { return -1; } } } } /// <summary> /// /// </summary> public class MapPacket { /// <summary></summary> public ushort ID; /// <summary></summary> public string Name; /// <summary></summary> public PacketFrequency Frequency; /// <summary></summary> public bool Trusted; /// <summary></summary> public bool Encoded; /// <summary></summary> public List<MapBlock> Blocks; } /// <summary> /// /// </summary> public class ProtocolManager { /// <summary></summary> public Dictionary<FieldType, int> TypeSizes; /// <summary></summary> public Dictionary<string, int> KeywordPositions; /// <summary></summary> public MapPacket[] LowMaps; /// <summary></summary> public MapPacket[] MediumMaps; /// <summary></summary> public MapPacket[] HighMaps; private GridClient Client; /// <summary> /// /// </summary> /// <param name="mapFile"></param> /// <param name="client"></param> public ProtocolManager(string mapFile, GridClient client) { Client = client; // Initialize the map arrays LowMaps = new MapPacket[65536]; MediumMaps = new MapPacket[256]; HighMaps = new MapPacket[256]; // Build the type size hash table TypeSizes = new Dictionary<FieldType,int>(); TypeSizes.Add(FieldType.U8, 1); TypeSizes.Add(FieldType.U16, 2); TypeSizes.Add(FieldType.U32, 4); TypeSizes.Add(FieldType.U64, 8); TypeSizes.Add(FieldType.S8, 1); TypeSizes.Add(FieldType.S16, 2); TypeSizes.Add(FieldType.S32, 4); TypeSizes.Add(FieldType.F32, 4); TypeSizes.Add(FieldType.F64, 8); TypeSizes.Add(FieldType.UUID, 16); TypeSizes.Add(FieldType.BOOL, 1); TypeSizes.Add(FieldType.Vector3, 12); TypeSizes.Add(FieldType.Vector3d, 24); TypeSizes.Add(FieldType.Vector4, 16); TypeSizes.Add(FieldType.Quaternion, 16); TypeSizes.Add(FieldType.IPADDR, 4); TypeSizes.Add(FieldType.IPPORT, 2); TypeSizes.Add(FieldType.Variable, -1); TypeSizes.Add(FieldType.Fixed, -2); KeywordPositions = new Dictionary<string, int>(); LoadMapFile(mapFile); } /// <summary> /// /// </summary> /// <param name="command"></param> /// <returns></returns> public MapPacket Command(string command) { foreach (MapPacket map in HighMaps) { if (map != null) { if (command == map.Name) { return map; } } } foreach (MapPacket map in MediumMaps) { if (map != null) { if (command == map.Name) { return map; } } } foreach (MapPacket map in LowMaps) { if (map != null) { if (command == map.Name) { return map; } } } throw new Exception("Cannot find map for command \"" + command + "\""); } /// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public MapPacket Command(byte[] data) { ushort command; if (data.Length < 5) { return null; } if (data[4] == 0xFF) { if ((byte)data[5] == 0xFF) { // Low frequency command = (ushort)(data[6] * 256 + data[7]); return Command(command, PacketFrequency.Low); } else { // Medium frequency command = (ushort)data[5]; return Command(command, PacketFrequency.Medium); } } else { // High frequency command = (ushort)data[4]; return Command(command, PacketFrequency.High); } } /// <summary> /// /// </summary> /// <param name="command"></param> /// <param name="frequency"></param> /// <returns></returns> public MapPacket Command(ushort command, PacketFrequency frequency) { switch (frequency) { case PacketFrequency.High: return HighMaps[command]; case PacketFrequency.Medium: return MediumMaps[command]; case PacketFrequency.Low: return LowMaps[command]; } throw new Exception("Cannot find map for command \"" + command + "\" with frequency \"" + frequency + "\""); } /// <summary> /// /// </summary> public void PrintMap() { PrintOneMap(LowMaps, "Low "); PrintOneMap(MediumMaps, "Medium"); PrintOneMap(HighMaps, "High "); } /// <summary> /// /// </summary> /// <param name="map"></param> /// <param name="frequency"></param> private void PrintOneMap(MapPacket[] map, string frequency) { int i; for (i = 0; i < map.Length; ++i) { if (map[i] != null) { Console.WriteLine("{0} {1,5} - {2} - {3} - {4}", frequency, i, map[i].Name, map[i].Trusted ? "Trusted" : "Untrusted", map[i].Encoded ? "Unencoded" : "Zerocoded"); foreach (MapBlock block in map[i].Blocks) { if (block.Count == -1) { Console.WriteLine("\t{0,4} {1} (Variable)", block.KeywordPosition, block.Name); } else { Console.WriteLine("\t{0,4} {1} ({2})", block.KeywordPosition, block.Name, block.Count); } foreach (MapField field in block.Fields) { Console.WriteLine("\t\t{0,4} {1} ({2} / {3})", field.KeywordPosition, field.Name, field.Type, field.Count); } } } } } /// <summary> /// /// </summary> /// <param name="mapFile"></param> /// <param name="outputFile"></param> public static void DecodeMapFile(string mapFile, string outputFile) { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; try { using (BinaryReader map = new BinaryReader(new FileStream(mapFile, FileMode.Open))) { using (BinaryWriter output = new BinaryWriter(new FileStream(outputFile, FileMode.CreateNew))) { while ((nread = map.Read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.Write(buffer, 0, nread); } } } } catch (Exception e) { throw new Exception("Map file error", e); } } /// <summary> /// /// </summary> /// <param name="mapFile"></param> private void LoadMapFile(string mapFile) { ushort low = 1; ushort medium = 1; ushort high = 1; // Load the protocol map file try { using (FileStream map = new FileStream(mapFile, FileMode.Open, FileAccess.Read)) { using (StreamReader r = new StreamReader(map)) { r.BaseStream.Seek(0, SeekOrigin.Begin); string newline; string trimmedline; bool inPacket = false; bool inBlock = false; MapPacket currentPacket = null; MapBlock currentBlock = null; char[] trimArray = new char[] { ' ', '\t' }; // While not at the end of the file while (r.Peek() > -1) { #region ParseMap newline = r.ReadLine(); trimmedline = System.Text.RegularExpressions.Regex.Replace(newline, @"\s+", " "); trimmedline = trimmedline.Trim(trimArray); if (!inPacket) { // Outside of all packet blocks if (trimmedline == "{") { inPacket = true; } } else { // Inside of a packet block if (!inBlock) { // Inside a packet block, outside of the blocks if (trimmedline == "{") { inBlock = true; } else if (trimmedline == "}") { // Reached the end of the packet currentPacket.Blocks.Sort(); inPacket = false; } else { // The packet header #region ParsePacketHeader // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); if (tokens.Length > 3) { //Hash packet name to insure correct keyword ordering KeywordPosition(tokens[0]); if (tokens[1] == "Fixed") { // Remove the leading "0x" if (tokens[2].Substring(0, 2) == "0x") { tokens[2] = tokens[2].Substring(2, tokens[2].Length - 2); } uint fixedID = UInt32.Parse(tokens[2], System.Globalization.NumberStyles.HexNumber); // Truncate the id to a short fixedID ^= 0xFFFF0000; LowMaps[fixedID] = new MapPacket(); LowMaps[fixedID].ID = (ushort)fixedID; LowMaps[fixedID].Frequency = PacketFrequency.Low; LowMaps[fixedID].Name = tokens[0]; LowMaps[fixedID].Trusted = (tokens[3] == "Trusted"); LowMaps[fixedID].Encoded = (tokens[4] == "Zerocoded"); LowMaps[fixedID].Blocks = new List<MapBlock>(); currentPacket = LowMaps[fixedID]; } else if (tokens[1] == "Low") { LowMaps[low] = new MapPacket(); LowMaps[low].ID = low; LowMaps[low].Frequency = PacketFrequency.Low; LowMaps[low].Name = tokens[0]; LowMaps[low].Trusted = (tokens[2] == "Trusted"); LowMaps[low].Encoded = (tokens[3] == "Zerocoded"); LowMaps[low].Blocks = new List<MapBlock>(); currentPacket = LowMaps[low]; low++; } else if (tokens[1] == "Medium") { MediumMaps[medium] = new MapPacket(); MediumMaps[medium].ID = medium; MediumMaps[medium].Frequency = PacketFrequency.Medium; MediumMaps[medium].Name = tokens[0]; MediumMaps[medium].Trusted = (tokens[2] == "Trusted"); MediumMaps[medium].Encoded = (tokens[3] == "Zerocoded"); MediumMaps[medium].Blocks = new List<MapBlock>(); currentPacket = MediumMaps[medium]; medium++; } else if (tokens[1] == "High") { HighMaps[high] = new MapPacket(); HighMaps[high].ID = high; HighMaps[high].Frequency = PacketFrequency.High; HighMaps[high].Name = tokens[0]; HighMaps[high].Trusted = (tokens[2] == "Trusted"); HighMaps[high].Encoded = (tokens[3] == "Zerocoded"); HighMaps[high].Blocks = new List<MapBlock>(); currentPacket = HighMaps[high]; high++; } else { Logger.Log("Unknown packet frequency", Helpers.LogLevel.Error, Client); } } #endregion } } else { if (trimmedline.Length > 0 && trimmedline.Substring(0, 1) == "{") { // A field #region ParseField MapField field = new MapField(); // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); field.Name = tokens[1]; field.KeywordPosition = KeywordPosition(field.Name); field.Type = (FieldType)Enum.Parse(typeof(FieldType), tokens[2], true); if (tokens[3] != "}") { field.Count = Int32.Parse(tokens[3]); } else { field.Count = 1; } // Save this field to the current block currentBlock.Fields.Add(field); #endregion } else if (trimmedline == "}") { currentBlock.Fields.Sort(); inBlock = false; } else if (trimmedline.Length != 0 && trimmedline.Substring(0, 2) != "//") { // The block header #region ParseBlockHeader currentBlock = new MapBlock(); // Splice the string in to tokens string[] tokens = trimmedline.Split(new char[] { ' ', '\t' }); currentBlock.Name = tokens[0]; currentBlock.KeywordPosition = KeywordPosition(currentBlock.Name); currentBlock.Fields = new List<MapField>(); currentPacket.Blocks.Add(currentBlock); if (tokens[1] == "Single") { currentBlock.Count = 1; } else if (tokens[1] == "Multiple") { currentBlock.Count = Int32.Parse(tokens[2]); } else if (tokens[1] == "Variable") { currentBlock.Count = -1; } else { Logger.Log("Unknown block frequency", Helpers.LogLevel.Error, Client); } #endregion } } } #endregion } } } } catch (Exception e) { throw new Exception("Map file parsing error", e); ; } } private int KeywordPosition(string keyword) { if (KeywordPositions.ContainsKey(keyword)) { return KeywordPositions[keyword]; } int hash = 0; for (int i = 1; i < keyword.Length; i++) { hash = (hash + (int)(keyword[i])) * 2; } hash *= 2; hash &= 0x1FFF; int startHash = hash; while (KeywordPositions.ContainsValue(hash)) { hash++; hash &= 0x1FFF; if (hash == startHash) { //Give up looking, went through all values and they were all taken. throw new Exception("All hash values are taken. Failed to add keyword: " + keyword); } } KeywordPositions[keyword] = hash; return hash; } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects { public unsafe class AssetTagsManifest : SimObject { public AssetTagsManifest() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.AssetTagsManifestCreateInstance()); } public AssetTagsManifest(uint pId) : base(pId) { } public AssetTagsManifest(string pName) : base(pName) { } public AssetTagsManifest(IntPtr pObjPtr) : base(pObjPtr) { } public AssetTagsManifest(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public AssetTagsManifest(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _AssetTagsManifestCreateInstance(); private static _AssetTagsManifestCreateInstance _AssetTagsManifestCreateInstanceFunc; internal static IntPtr AssetTagsManifestCreateInstance() { if (_AssetTagsManifestCreateInstanceFunc == null) { _AssetTagsManifestCreateInstanceFunc = (_AssetTagsManifestCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestCreateInstance"), typeof(_AssetTagsManifestCreateInstance)); } return _AssetTagsManifestCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _AssetTagsManifestCreateTag(IntPtr assetTagsManifest, string tagName); private static _AssetTagsManifestCreateTag _AssetTagsManifestCreateTagFunc; internal static void AssetTagsManifestCreateTag(IntPtr assetTagsManifest, string tagName) { if (_AssetTagsManifestCreateTagFunc == null) { _AssetTagsManifestCreateTagFunc = (_AssetTagsManifestCreateTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestCreateTag"), typeof(_AssetTagsManifestCreateTag)); } _AssetTagsManifestCreateTagFunc(assetTagsManifest, tagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _AssetTagsManifestRenameTag(IntPtr assetTagsManifest, string oldTagName, string newTagName); private static _AssetTagsManifestRenameTag _AssetTagsManifestRenameTagFunc; internal static bool AssetTagsManifestRenameTag(IntPtr assetTagsManifest, string oldTagName, string newTagName) { if (_AssetTagsManifestRenameTagFunc == null) { _AssetTagsManifestRenameTagFunc = (_AssetTagsManifestRenameTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestRenameTag"), typeof(_AssetTagsManifestRenameTag)); } return _AssetTagsManifestRenameTagFunc(assetTagsManifest, oldTagName, newTagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _AssetTagsManifestDeleteTag(IntPtr assetTagsManifest, string tagName); private static _AssetTagsManifestDeleteTag _AssetTagsManifestDeleteTagFunc; internal static bool AssetTagsManifestDeleteTag(IntPtr assetTagsManifest, string tagName) { if (_AssetTagsManifestDeleteTagFunc == null) { _AssetTagsManifestDeleteTagFunc = (_AssetTagsManifestDeleteTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestDeleteTag"), typeof(_AssetTagsManifestDeleteTag)); } return _AssetTagsManifestDeleteTagFunc(assetTagsManifest, tagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _AssetTagsManifestIsTag(IntPtr assetTagsManifest, string tagName); private static _AssetTagsManifestIsTag _AssetTagsManifestIsTagFunc; internal static bool AssetTagsManifestIsTag(IntPtr assetTagsManifest, string tagName) { if (_AssetTagsManifestIsTagFunc == null) { _AssetTagsManifestIsTagFunc = (_AssetTagsManifestIsTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestIsTag"), typeof(_AssetTagsManifestIsTag)); } return _AssetTagsManifestIsTagFunc(assetTagsManifest, tagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _AssetTagsManifestGetTagCount(IntPtr assetTagsManifest); private static _AssetTagsManifestGetTagCount _AssetTagsManifestGetTagCountFunc; internal static int AssetTagsManifestGetTagCount(IntPtr assetTagsManifest) { if (_AssetTagsManifestGetTagCountFunc == null) { _AssetTagsManifestGetTagCountFunc = (_AssetTagsManifestGetTagCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestGetTagCount"), typeof(_AssetTagsManifestGetTagCount)); } return _AssetTagsManifestGetTagCountFunc(assetTagsManifest); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _AssetTagsManifestGetTag(IntPtr assetTagsManifest, int tagIndex); private static _AssetTagsManifestGetTag _AssetTagsManifestGetTagFunc; internal static IntPtr AssetTagsManifestGetTag(IntPtr assetTagsManifest, int tagIndex) { if (_AssetTagsManifestGetTagFunc == null) { _AssetTagsManifestGetTagFunc = (_AssetTagsManifestGetTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestGetTag"), typeof(_AssetTagsManifestGetTag)); } return _AssetTagsManifestGetTagFunc(assetTagsManifest, tagIndex); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _AssetTagsManifestGetAssetTagCount(IntPtr assetTagsManifest, string assetId); private static _AssetTagsManifestGetAssetTagCount _AssetTagsManifestGetAssetTagCountFunc; internal static int AssetTagsManifestGetAssetTagCount(IntPtr assetTagsManifest, string assetId) { if (_AssetTagsManifestGetAssetTagCountFunc == null) { _AssetTagsManifestGetAssetTagCountFunc = (_AssetTagsManifestGetAssetTagCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestGetAssetTagCount"), typeof(_AssetTagsManifestGetAssetTagCount)); } return _AssetTagsManifestGetAssetTagCountFunc(assetTagsManifest, assetId); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _AssetTagsManifestGetAssetTag(IntPtr assetTagsManifest, string assetId, int tagIndex); private static _AssetTagsManifestGetAssetTag _AssetTagsManifestGetAssetTagFunc; internal static IntPtr AssetTagsManifestGetAssetTag(IntPtr assetTagsManifest, string assetId, int tagIndex) { if (_AssetTagsManifestGetAssetTagFunc == null) { _AssetTagsManifestGetAssetTagFunc = (_AssetTagsManifestGetAssetTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestGetAssetTag"), typeof(_AssetTagsManifestGetAssetTag)); } return _AssetTagsManifestGetAssetTagFunc(assetTagsManifest, assetId, tagIndex); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _AssetTagsManifestTag(IntPtr assetTagsManifest, string assetId, string tagName); private static _AssetTagsManifestTag _AssetTagsManifestTagFunc; internal static bool AssetTagsManifestTag(IntPtr assetTagsManifest, string assetId, string tagName) { if (_AssetTagsManifestTagFunc == null) { _AssetTagsManifestTagFunc = (_AssetTagsManifestTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestTag"), typeof(_AssetTagsManifestTag)); } return _AssetTagsManifestTagFunc(assetTagsManifest, assetId, tagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _AssetTagsManifestUntag(IntPtr assetTagsManifest, string assetId, string tagName); private static _AssetTagsManifestUntag _AssetTagsManifestUntagFunc; internal static bool AssetTagsManifestUntag(IntPtr assetTagsManifest, string assetId, string tagName) { if (_AssetTagsManifestUntagFunc == null) { _AssetTagsManifestUntagFunc = (_AssetTagsManifestUntag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestUntag"), typeof(_AssetTagsManifestUntag)); } return _AssetTagsManifestUntagFunc(assetTagsManifest, assetId, tagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _AssetTagsManifestHasTag(IntPtr assetTagsManifest, string assetId, string tagName); private static _AssetTagsManifestHasTag _AssetTagsManifestHasTagFunc; internal static bool AssetTagsManifestHasTag(IntPtr assetTagsManifest, string assetId, string tagName) { if (_AssetTagsManifestHasTagFunc == null) { _AssetTagsManifestHasTagFunc = (_AssetTagsManifestHasTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "AssetTagsManifestHasTag"), typeof(_AssetTagsManifestHasTag)); } return _AssetTagsManifestHasTagFunc(assetTagsManifest, assetId, tagName); } } #endregion #region Properties #endregion #region Methods public void CreateTag(string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.AssetTagsManifestCreateTag(ObjectPtr->ObjPtr, tagName); } public bool RenameTag(string oldTagName, string newTagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestRenameTag(ObjectPtr->ObjPtr, oldTagName, newTagName); } public bool DeleteTag(string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestDeleteTag(ObjectPtr->ObjPtr, tagName); } public bool IsTag(string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestIsTag(ObjectPtr->ObjPtr, tagName); } public int GetTagCount() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestGetTagCount(ObjectPtr->ObjPtr); } public string GetTag(int tagIndex) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AssetTagsManifestGetTag(ObjectPtr->ObjPtr, tagIndex)); } public int GetAssetTagCount(string assetId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestGetAssetTagCount(ObjectPtr->ObjPtr, assetId); } public string GetAssetTag(string assetId, int tagIndex) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AssetTagsManifestGetAssetTag(ObjectPtr->ObjPtr, assetId, tagIndex)); } public bool Tag(string assetId, string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestTag(ObjectPtr->ObjPtr, assetId, tagName); } public bool Untag(string assetId, string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestUntag(ObjectPtr->ObjPtr, assetId, tagName); } public bool HasTag(string assetId, string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.AssetTagsManifestHasTag(ObjectPtr->ObjPtr, assetId, tagName); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Apple; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class AppleCrypto { [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeychainItemCopyKeychain( IntPtr item, out SafeKeychainHandle keychain); [DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SecKeychainCreate")] private static extern int AppleCryptoNative_SecKeychainCreateTemporary( string path, int utf8PassphraseLength, byte[] utf8Passphrase, out SafeTemporaryKeychainHandle keychain); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeychainDelete(IntPtr keychain); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeychainCopyDefault(out SafeKeychainHandle keychain); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeychainOpen( string keychainPath, out SafeKeychainHandle keychain); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SetKeychainNeverLock(SafeKeychainHandle keychain); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeychainEnumerateCerts( SafeKeychainHandle keychain, out SafeCFArrayHandle matches, out int pOSStatus); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeychainEnumerateIdentities( SafeKeychainHandle keychain, out SafeCFArrayHandle matches, out int pOSStatus); internal static SafeKeychainHandle SecKeychainItemCopyKeychain(SafeKeychainItemHandle item) { bool addedRef = false; try { item.DangerousAddRef(ref addedRef); var handle = SecKeychainItemCopyKeychain(item.DangerousGetHandle()); return handle; } finally { if (addedRef) { item.DangerousRelease(); } } } internal static SafeKeychainHandle SecKeychainItemCopyKeychain(IntPtr item) { SafeKeychainHandle keychain; int osStatus = AppleCryptoNative_SecKeychainItemCopyKeychain(item, out keychain); // A whole lot of NULL is expected from this. // Any key or cert which isn't keychain-backed, and this is the primary way we'd find that out. if (keychain.IsInvalid) { GC.SuppressFinalize(keychain); } if (osStatus == 0) { return keychain; } throw CreateExceptionForOSStatus(osStatus); } internal static SafeKeychainHandle SecKeychainCopyDefault() { SafeKeychainHandle keychain; int osStatus = AppleCryptoNative_SecKeychainCopyDefault(out keychain); if (osStatus == 0) { return keychain; } keychain.Dispose(); throw CreateExceptionForOSStatus(osStatus); } internal static SafeKeychainHandle SecKeychainOpen(string keychainPath) { SafeKeychainHandle keychain; int osStatus = AppleCryptoNative_SecKeychainOpen(keychainPath, out keychain); if (osStatus == 0) { return keychain; } keychain.Dispose(); throw CreateExceptionForOSStatus(osStatus); } internal static SafeCFArrayHandle KeychainEnumerateCerts(SafeKeychainHandle keychainHandle) { SafeCFArrayHandle matches; int osStatus; int result = AppleCryptoNative_SecKeychainEnumerateCerts(keychainHandle, out matches, out osStatus); if (result == 1) { return matches; } matches.Dispose(); if (result == 0) throw CreateExceptionForOSStatus(osStatus); Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}"); throw new CryptographicException(); } internal static SafeCFArrayHandle KeychainEnumerateIdentities(SafeKeychainHandle keychainHandle) { SafeCFArrayHandle matches; int osStatus; int result = AppleCryptoNative_SecKeychainEnumerateIdentities(keychainHandle, out matches, out osStatus); if (result == 1) { return matches; } matches.Dispose(); if (result == 0) throw CreateExceptionForOSStatus(osStatus); Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}"); throw new CryptographicException(); } internal static SafeTemporaryKeychainHandle CreateTemporaryKeychain() { string tmpKeychainPath = Path.Combine( Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".keychain"); // Use a distinct GUID so that if a keychain is abandoned it isn't recoverable. string tmpKeychainPassphrase = Guid.NewGuid().ToString("N"); byte[] utf8Passphrase = System.Text.Encoding.UTF8.GetBytes(tmpKeychainPassphrase); SafeTemporaryKeychainHandle keychain; int osStatus = AppleCryptoNative_SecKeychainCreateTemporary( tmpKeychainPath, utf8Passphrase.Length, utf8Passphrase, out keychain); SafeTemporaryKeychainHandle.TrackKeychain(keychain); if (osStatus == 0) { osStatus = AppleCryptoNative_SetKeychainNeverLock(keychain); } if (osStatus != 0) { keychain.Dispose(); throw CreateExceptionForOSStatus(osStatus); } return keychain; } internal static void SecKeychainDelete(IntPtr handle, bool throwOnError=true) { int osStatus = AppleCryptoNative_SecKeychainDelete(handle); if (throwOnError && osStatus != 0) { throw CreateExceptionForOSStatus(osStatus); } } } } namespace System.Security.Cryptography.Apple { internal class SafeKeychainItemHandle : SafeHandle { internal SafeKeychainItemHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { SafeTemporaryKeychainHandle.UntrackItem(handle); Interop.CoreFoundation.CFRelease(handle); SetHandle(IntPtr.Zero); return true; } public override bool IsInvalid => handle == IntPtr.Zero; } internal class SafeKeychainHandle : SafeHandle { internal SafeKeychainHandle() : base(IntPtr.Zero, ownsHandle: true) { } internal SafeKeychainHandle(IntPtr handle) : base(handle, ownsHandle: true) { } protected override bool ReleaseHandle() { Interop.CoreFoundation.CFRelease(handle); SetHandle(IntPtr.Zero); return true; } public override bool IsInvalid => handle == IntPtr.Zero; } internal sealed class SafeTemporaryKeychainHandle : SafeKeychainHandle { private static readonly Dictionary<IntPtr, SafeTemporaryKeychainHandle> s_lookup = new Dictionary<IntPtr, SafeTemporaryKeychainHandle>(); internal SafeTemporaryKeychainHandle() { } protected override bool ReleaseHandle() { lock (s_lookup) { s_lookup.Remove(handle); } Interop.AppleCrypto.SecKeychainDelete(handle, throwOnError: false); return base.ReleaseHandle(); } protected override void Dispose(bool disposing) { if (disposing && SafeHandleCache<SafeTemporaryKeychainHandle>.IsCachedInvalidHandle(this)) { return; } base.Dispose(disposing); } public static SafeTemporaryKeychainHandle InvalidHandle => SafeHandleCache<SafeTemporaryKeychainHandle>.GetInvalidHandle(() => new SafeTemporaryKeychainHandle()); internal static void TrackKeychain(SafeTemporaryKeychainHandle toTrack) { if (toTrack.IsInvalid) { return; } lock (s_lookup) { Debug.Assert(!s_lookup.ContainsKey(toTrack.handle)); s_lookup[toTrack.handle] = toTrack; } } internal static void TrackItem(SafeKeychainItemHandle keychainItem) { if (keychainItem.IsInvalid) return; using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem)) { if (keychain.IsInvalid) { return; } lock (s_lookup) { SafeTemporaryKeychainHandle temporaryHandle; if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle)) { bool ignored = false; temporaryHandle.DangerousAddRef(ref ignored); } } } } internal static void UntrackItem(IntPtr keychainItem) { using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem)) { if (keychain.IsInvalid) { return; } lock (s_lookup) { SafeTemporaryKeychainHandle temporaryHandle; if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle)) { temporaryHandle.DangerousRelease(); } } } } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; namespace WebsitePanel.Providers.Mail { [Serializable] public class MailDomain : ServiceProviderItem { #region Smarter Mail 5.x String Constants //Domain Features public const string SMARTERMAIL5_SHOW_DOMAIN_REPORTS = "ShowDomainReports"; public const string SMARTERMAIL5_SHOW_CALENDAR = "ShowCalendar"; public const string SMARTERMAIL5_SHOW_CONTACTS = "ShowContacts"; public const string SMARTERMAIL5_SHOW_TASKS = "ShowTasks"; public const string SMARTERMAIL5_SHOW_NOTES = "ShowNotes"; public const string SMARTERMAIL5_POP_RETRIEVAL = "ShowCalendar"; public const string SMARTERMAIL5_POP_RETREIVAL_ENABLED = "EnablePopRetreival"; public const string SMARTERMAIL5_CATCHALLS_ENABLED = "EnableCatchAlls"; //Domain Throttling public const string SMARTERMAIL5_MESSAGES_PER_HOUR = "MessagesPerHour"; public const string SMARTERMAIL5_MESSAGES_PER_HOUR_ENABLED = "MessagesPerHourEnabled"; public const string SMARTERMAIL5_BANDWIDTH_PER_HOUR = "BandwidthPerHour"; public const string SMARTERMAIL5_BANDWIDTH_PER_HOUR_ENABLED = "BandwidthPerHourEnabled"; public const string SMARTERMAIL5_BOUNCES_PER_HOUR = "BouncesReceivedPerHour"; public const string SMARTERMAIL5_BOUNCES_PER_HOUR_ENABLED = "BouncesPerHourEnabled"; //Domain Limits public const string SMARTERMAIL5_POP_RETREIVAL_ACCOUNTS = "PopRetreivalAccounts"; #endregion #region Smarter Mail 6.x String Constants //Domain Features public const string SMARTERMAIL6_IMAP_RETREIVAL_ENABLED = "EnableImapRetreival"; public const string SMARTERMAIL6_MAIL_SIGNING_ENABLED = "EnableMailSigning"; public const string SMARTERMAIL6_EMAIL_REPORTS_ENABLED = "EnableEmailReports"; public const string SMARTERMAIL6_SYNCML_ENABLED = "EnableSyncML"; #endregion //license type public const string SMARTERMAIL_LICENSE_TYPE = "LicenseType"; private string[] blackList = new string[0]; private string redirectionHosts; private bool redirectionActive; private bool enabled; private string postmasterAccount; private string catchAllAccount; private string abuseAccount; private int maxPopRetrievalAccounts; public string RedirectionHosts { get { return this.redirectionHosts; } set { this.redirectionHosts = value; } } public string[] BlackList { get { return this.blackList; } set { this.blackList = value; } } public string CatchAllAccount { get { return this.catchAllAccount; } set { this.catchAllAccount = value; } } public string AbuseAccount { get { return this.abuseAccount; } set { this.abuseAccount = value; } } public bool RedirectionActive { get { return this.redirectionActive; } set { this.redirectionActive = value; } } public bool Enabled { get { return this.enabled; } set { this.enabled = value; } } public string PostmasterAccount { get { return this.postmasterAccount; } set { this.postmasterAccount = value; } } #region SmarterMail private string primaryDomainAdminUserName; private string primaryDomainAdminPassword; private string primaryDomainAdminFirstName; private string primaryDomainAdminLastName; private string serverIP; private string path; private int imapPort = 143; private int popPort = 110; private int smtpPort = 25; private int smtpPortAlt; private int ldapPort; private int maxAliases; private int maxDomainAliases; private int maxLists; private int maxDomainSizeInMB; private int maxDomainUsers; private int maxMailboxSizeInMB; private int maxMessageSize; private int maxRecipients; private bool requireSmtpAuthentication; private string listCommandAddress = ""; private bool isGlobalAddressList; private bool sharedContacts; private bool sharedNotes; private bool sharedCalendars; private bool sharedFolders; private bool sharedTasks; private bool bypassForwardBlackList; private bool showstatsmenu; private bool showspammenu; private bool showlistmenu; private bool showdomainaliasmenu; private bool showcontentfilteringmenu; public bool ShowsStatsMenu { get { return showstatsmenu; } set { showstatsmenu = value; } } public bool ShowSpamMenu { get { return showspammenu; } set { showspammenu = value; } } public bool ShowListMenu { get { return showlistmenu; } set { showlistmenu = value; } } public bool ShowDomainAliasMenu { get { return showdomainaliasmenu; } set { showdomainaliasmenu = value; } } public bool ShowContentFilteringMenu { get { return showcontentfilteringmenu; } set { showcontentfilteringmenu = value; } } public bool BypassForwardBlackList { get { return bypassForwardBlackList; } set { bypassForwardBlackList = value; } } public bool IsGlobalAddressList { get { return isGlobalAddressList; } set { isGlobalAddressList = value; } } public bool SharedContacts { get { return sharedContacts; } set { sharedContacts = value; } } public bool SharedNotes { get { return sharedNotes; } set { sharedNotes = value; } } public bool SharedCalendars { get { return sharedCalendars; } set { sharedCalendars = value; } } public bool SharedFolders { get { return sharedFolders; } set { sharedFolders = value; } } public bool SharedTasks { get { return sharedTasks; } set { sharedTasks = value; } } public string PrimaryDomainAdminUserName { get { return primaryDomainAdminUserName; } set { primaryDomainAdminUserName = value; } } public string PrimaryDomainAdminPassword { get { return primaryDomainAdminPassword; } set { primaryDomainAdminPassword = value; } } public string PrimaryDomainAdminFirstName { get { return primaryDomainAdminFirstName; } set { primaryDomainAdminFirstName = value; } } public string PrimaryDomainAdminLastName { get { return primaryDomainAdminLastName; } set { primaryDomainAdminLastName = value; } } public string ServerIP { get { return serverIP; } set { serverIP = value; } } public string Path { get { return path; } set { path = value; } } public int SmtpPortAlt { get { return smtpPortAlt; } set { smtpPortAlt = value; } } public int LdapPort { get { return ldapPort; } set { ldapPort = value; } } public int ImapPort { get { return imapPort; } set { imapPort = value; } } public int PopPort { get { return popPort; } set { popPort = value; } } public int SmtpPort { get { return smtpPort; } set { smtpPort = value; } } public int MaxAliases { get { return maxAliases; } set { maxAliases = value; } } public int MaxDomainAliases { get { return maxDomainAliases; } set { maxDomainAliases = value; } } public int MaxLists { get { return maxLists; } set { maxLists = value; } } public int MaxDomainSizeInMB { get { return maxDomainSizeInMB; } set { maxDomainSizeInMB = value; } } public int MaxDomainUsers { get { return maxDomainUsers; } set { maxDomainUsers = value; } } public int MaxMailboxSizeInMB { get { return maxMailboxSizeInMB; } set { maxMailboxSizeInMB = value; } } public int MaxMessageSize { get { return maxMessageSize; } set { maxMessageSize = value; } } public int MaxRecipients { get { return maxRecipients; } set { maxRecipients = value; } } public int MaxPopRetrievalAccounts { get { return maxPopRetrievalAccounts; } set { maxPopRetrievalAccounts = value; } } public bool RequireSmtpAuthentication { get { return requireSmtpAuthentication; } set { requireSmtpAuthentication = value; } } public string ListCommandAddress { get { return listCommandAddress; } set { listCommandAddress = value; } } #endregion #region IceWarp public bool UseDomainDiskQuota { get; set; } public bool UseDomainLimits { get; set; } public bool UseUserLimits { get; set; } public int MegaByteSendLimit { get; set; } public int NumberSendLimit { get; set; } public int DefaultUserQuotaInMB { get; set; } public int DefaultUserMaxMessageSizeMegaByte { get; set; } public int DefaultUserMegaByteSendLimit { get; set; } public int DefaultUserNumberSendLimit { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace VotingInfo.Database.Logic.Data { [Serializable] public abstract partial class LocationLogicBase : LogicBase<LocationLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<LocationContract> Results; public LocationLogicBase() { Results = new List<LocationContract>(); } /// <summary> /// Run Location_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , string fldLocationName ) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationName", fldLocationName) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run Location_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , string fldLocationName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationName", fldLocationName) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(LocationContract row) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationName", row.LocationName) }); result = (int?)cmd.ExecuteScalar(); row.LocationId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(LocationContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Data].[Location_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationName", row.LocationName) }); result = (int?)cmd.ExecuteScalar(); row.LocationId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<LocationContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run Location_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> public virtual int Update(int fldLocationId , int fldContentInspectionId , string fldLocationName ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationName", fldLocationName) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run Location_Update. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldLocationId , int fldContentInspectionId , string fldLocationName , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Location_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationName", fldLocationName) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(LocationContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", row.LocationId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationName", row.LocationName) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(LocationContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Location_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", row.LocationId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationName", row.LocationName) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<LocationContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run Location_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldLocationId">Value for LocationId</param> public virtual int Delete(int fldLocationId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run Location_Delete. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Location_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(LocationContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", row.LocationId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(LocationContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Location_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", row.LocationId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<LocationContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldLocationId ) { bool result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run Location_Search, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <returns>A collection of LocationRow.</returns> public virtual bool Search(string fldLocationName ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationName", fldLocationName) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Location_Search, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public virtual bool Search(string fldLocationName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationName", fldLocationName) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Location_SelectAll, and return results as a list of LocationRow. /// </summary> /// <returns>A collection of LocationRow.</returns> public virtual bool SelectAll() { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Location_SelectAll, and return results as a list of LocationRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Location_List, and return results as a list. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldLocationName ) { List<ListItemContract> result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_List]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationName", fldLocationName) }); using(var r = cmd.ExecuteReader()) result = ListItemLogic.ReadAllNow(r); } }); return result; } /// <summary> /// Run Location_List, and return results as a list. /// </summary> /// <param name="fldLocationName">Value for LocationName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldLocationName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_List]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationName", fldLocationName) }); using(var r = cmd.ExecuteReader()) return ListItemLogic.ReadAllNow(r); } } /// <summary> /// Run Location_SelectBy_LocationId, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>A collection of LocationRow.</returns> public virtual bool SelectBy_LocationId(int fldLocationId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_SelectBy_LocationId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Location_SelectBy_LocationId, and return results as a list of LocationRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public virtual bool SelectBy_LocationId(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_SelectBy_LocationId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Location_SelectBy_ContentInspectionId, and return results as a list of LocationRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of LocationRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Location_SelectBy_ContentInspectionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Location_SelectBy_ContentInspectionId, and return results as a list of LocationRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of LocationRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Location_SelectBy_ContentInspectionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new LocationContract { LocationId = reader.GetInt32(0), ContentInspectionId = reader.GetInt32(1), LocationName = reader.GetString(2), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(LocationContract row) { if(row == null) return 0; if(row.LocationId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(LocationContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.LocationId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<LocationContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<LocationContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { internal static class StringUtils { public const string CarriageReturnLineFeed = "\r\n"; public const string Empty = ""; public const char CarriageReturn = '\r'; public const char LineFeed = '\n'; public const char Tab = '\t'; public static string FormatWith(this string format, IFormatProvider provider, object arg0) { return format.FormatWith(provider, new[] { arg0 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1) { return format.FormatWith(provider, new[] { arg0, arg1 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2) { return format.FormatWith(provider, new[] { arg0, arg1, arg2 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) { return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 }); } private static string FormatWith(this string format, IFormatProvider provider, params object[] args) { // leave this a private to force code to use an explicit overload // avoids stack memory being reserved for the object array ValidationUtils.ArgumentNotNull(format, nameof(format)); return string.Format(provider, format, args); } /// <summary> /// Determines whether the string is all white space. Empty string will return false. /// </summary> /// <param name="s">The string to test whether it is all white space.</param> /// <returns> /// <c>true</c> if the string is all white space; otherwise, <c>false</c>. /// </returns> public static bool IsWhiteSpace(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (s.Length == 0) { return false; } for (int i = 0; i < s.Length; i++) { if (!char.IsWhiteSpace(s[i])) { return false; } } return true; } /// <summary> /// Nulls an empty string. /// </summary> /// <param name="s">The string.</param> /// <returns>Null if the string was null, otherwise the string unchanged.</returns> public static string NullEmptyString(string s) { return (string.IsNullOrEmpty(s)) ? null : s; } public static StringWriter CreateStringWriter(int capacity) { StringBuilder sb = new StringBuilder(capacity); StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); return sw; } public static int? GetLength(string value) { if (value == null) { return null; } else { return value.Length; } } public static void ToCharAsUnicode(char c, char[] buffer) { buffer[0] = '\\'; buffer[1] = 'u'; buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f'); buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f'); buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f'); buffer[5] = MathUtils.IntToHex(c & '\x000f'); } public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (valueSelector == null) { throw new ArgumentNullException(nameof(valueSelector)); } var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) { return caseInsensitiveResults.SingleOrDefault(); } else { // multiple results returned. now filter using case sensitivity var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); return caseSensitiveResults.SingleOrDefault(); } } public static string ToCamelCase(string s) { if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0])) { return s; } char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) { if (i == 1 && !char.IsUpper(chars[i])) { break; } bool hasNext = (i + 1 < chars.Length); if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { break; } #if !(DOTNET || PORTABLE) chars[i] = char.ToLower(chars[i], CultureInfo.InvariantCulture); #else chars[i] = char.ToLowerInvariant(chars[i]); #endif } return new string(chars); } public static bool IsHighSurrogate(char c) { #if !(PORTABLE40 || PORTABLE) return char.IsHighSurrogate(c); #else return (c >= 55296 && c <= 56319); #endif } public static bool IsLowSurrogate(char c) { #if !(PORTABLE40 || PORTABLE) return char.IsLowSurrogate(c); #else return (c >= 56320 && c <= 57343); #endif } public static bool StartsWith(this string source, char value) { return (source.Length > 0 && source[0] == value); } public static bool EndsWith(this string source, char value) { return (source.Length > 0 && source[source.Length - 1] == value); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Model { using System.Collections; using NPOI.HSSF.Record; using System.Collections.Generic; /// <summary> /// List for records in Workbook /// </summary> public class WorkbookRecordList { private List<Record> records = new List<Record>(); private int protpos = 0; // holds the position of the protect record. private int bspos = 0; // holds the position of the last bound sheet. private int tabpos = 0; // holds the position of the tabid record private int fontpos = 0; // hold the position of the last font record private int xfpos = 0; // hold the position of the last extended font record private int backuppos = 0; // holds the position of the backup record. private int namepos = 0; // holds the position of last name record private int supbookpos = 0; // holds the position of sup book private int externsheetPos = 0;// holds the position of the extern sheet private int palettepos = -1; // hold the position of the palette, if applicable /// <summary> /// Gets or sets the records. /// </summary> /// <value>The records.</value> public List<Record> Records { get { return records; } set { this.records = value; } } /// <summary> /// Gets the count. /// </summary> /// <value>The count.</value> public int Count { get { return records.Count; } } /// <summary> /// Gets the <see cref="NPOI.HSSF.Record.Record"/> at the specified index. /// </summary> /// <value></value> public Record this[int index] { get { return (Record)records[index]; } } /// <summary> /// Adds the specified pos. /// </summary> /// <param name="pos">The pos.</param> /// <param name="r">The r.</param> public void Add(int pos, Record r) { records.Insert(pos, r); if (Protpos >= pos) Protpos=(protpos + 1); if (Bspos >= pos) Bspos=(bspos + 1); if (Tabpos >= pos) Tabpos=(tabpos + 1); if (Fontpos >= pos) Fontpos=(fontpos + 1); if (Xfpos >= pos) Xfpos=(xfpos + 1); if (Backuppos >= pos) Backuppos=(backuppos + 1); if (Namepos>= pos) Namepos=(namepos + 1); if (Supbookpos >= pos) Supbookpos=(supbookpos + 1); if ((Palettepos!= -1) && (Palettepos>= pos)) Palettepos=(palettepos + 1); if (ExternsheetPos >= pos) ExternsheetPos=ExternsheetPos + 1; } public IEnumerator<Record> GetEnumerator() { return records.GetEnumerator(); } /// <summary> /// Removes the specified record. /// </summary> /// <param name="record">The record.</param> public void Remove(Record record) { int i = records.IndexOf(record); this.Remove(i); } /// <summary> /// Removes the specified position. /// </summary> /// <param name="pos">The position.</param> public void Remove(int pos) { records.RemoveAt(pos); if (Protpos >= pos) Protpos=protpos - 1; if (Bspos >= pos) Bspos=bspos - 1; if (Tabpos >= pos) Tabpos=tabpos - 1; if (Fontpos >= pos) Fontpos=fontpos - 1; if (Xfpos >= pos) Xfpos=xfpos - 1; if (Backuppos >= pos) Backuppos=backuppos - 1; if (Namepos >= pos) Namepos=Namepos - 1; if (Supbookpos >= pos) Supbookpos=Supbookpos - 1; if ((Palettepos != -1) && (Palettepos >= pos)) Palettepos=palettepos - 1; if (ExternsheetPos >= pos) ExternsheetPos=ExternsheetPos- 1; } /// <summary> /// Gets or sets the protpos. /// </summary> /// <value>The protpos.</value> public int Protpos { get { return protpos; } set { this.protpos = value; } } /// <summary> /// Gets or sets the bspos. /// </summary> /// <value>The bspos.</value> public int Bspos { get{return bspos;} set { this.bspos = value; } } /// <summary> /// Gets or sets the tabpos. /// </summary> /// <value>The tabpos.</value> public int Tabpos { get { return tabpos; } set { this.tabpos =value; } } /// <summary> /// Gets or sets the fontpos. /// </summary> /// <value>The fontpos.</value> public int Fontpos { get { return fontpos; } set { this.fontpos = value; } } /// <summary> /// Gets or sets the xfpos. /// </summary> /// <value>The xfpos.</value> public int Xfpos { get { return xfpos; } set { this.xfpos = value; } } /// <summary> /// Gets or sets the backuppos. /// </summary> /// <value>The backuppos.</value> public int Backuppos { get{return backuppos;} set { this.backuppos = value; } } /// <summary> /// Gets or sets the palettepos. /// </summary> /// <value>The palettepos.</value> public int Palettepos { get{return palettepos;} set { this.palettepos = value; } } /// <summary> /// Gets or sets the namepos. /// </summary> /// <value>The namepos.</value> public int Namepos { get { return namepos; } set { this.namepos = value; } } /// <summary> /// Gets or sets the supbookpos. /// </summary> /// <value>The supbookpos.</value> public int Supbookpos { get{return supbookpos;} set { this.supbookpos = value; } } /// <summary> /// Gets or sets the externsheet pos. /// </summary> /// <value>The externsheet pos.</value> public int ExternsheetPos { get { return externsheetPos; } set { this.externsheetPos = value; } } } }
using System; using UnityEngine; using System.Collections; public class MyGUI3_1 : MonoBehaviour { public enum GuiStat { Ball, BallRotate, BallRotatex4, Bottom, Middle, MiddleWithoutRobot, Top, TopTarget } public int CurrentPrefabNomber = 0; public float UpdateInterval = 0.5F; public Light DirLight; public GameObject Target; public GameObject TopPosition; public GameObject MiddlePosition; public Vector3 defaultRobotPos; public GameObject BottomPosition; public GameObject Plane1; public GameObject Plane2; public Material[] PlaneMaterials; public GuiStat[] GuiStats; public GameObject[] Prefabs; private float oldLightIntensity; private Color oldAmbientColor; private GameObject currentGo; private bool isDay, isHomingMove, isDefaultPlaneTexture; private int current; private Animator anim; private float prefabSpeed = 4; private EffectSettings effectSettings; private bool isReadyEffect; private Quaternion defaultRobotRotation; private float accum = 0; // FPS accumulated over the interval private int frames = 0; // Frames drawn over the interval private float timeleft; // Left time for current interval private float fps; private GUIStyle guiStyleHeader = new GUIStyle(); void Start() { oldAmbientColor = RenderSettings.ambientLight; oldLightIntensity = DirLight.intensity; anim = Target.GetComponent<Animator>(); guiStyleHeader.fontSize = 14; guiStyleHeader.normal.textColor = new Color(1,1,1); var prefabSett = Prefabs[current].GetComponent<EffectSettings>(); if (prefabSett != null) prefabSpeed = prefabSett.MoveSpeed; current = CurrentPrefabNomber; InstanceCurrent(GuiStats[CurrentPrefabNomber]); } private void InstanceEffect(Vector3 pos) { currentGo = Instantiate(Prefabs[current], pos, Prefabs[current].transform.rotation) as GameObject; effectSettings = currentGo.GetComponent<EffectSettings>(); effectSettings.Target = GetTargetObject(GuiStats[current]); if (isHomingMove) effectSettings.IsHomingMove = isHomingMove; prefabSpeed = effectSettings.MoveSpeed; effectSettings.EffectDeactivated+=effectSettings_EffectDeactivated; if (GuiStats[current]==GuiStat.Middle) { currentGo.transform.parent = GetTargetObject(GuiStat.Middle).transform; currentGo.transform.position = GetInstancePosition(GuiStat.Middle); } else currentGo.transform.parent = transform; effectSettings.CollisionEnter += (n, e) => { if(e.Hit.transform!=null) Debug.Log(e.Hit.transform.name); }; } GameObject GetTargetObject(GuiStat stat) { switch (stat) { case GuiStat.Ball: { return Target; } case GuiStat.BallRotate: { return Target; } case GuiStat.Bottom: { return BottomPosition; } case GuiStat.Top: { return TopPosition; } case GuiStat.TopTarget: { return BottomPosition; } case GuiStat.Middle: { MiddlePosition.transform.localPosition = defaultRobotPos; MiddlePosition.transform.localRotation = Quaternion.Euler(0, 180, 0); return MiddlePosition; } case GuiStat.MiddleWithoutRobot: { return MiddlePosition.transform.parent.gameObject; } } return gameObject; } private void effectSettings_EffectDeactivated(object sender, EventArgs e) { if (GuiStats[current]!=GuiStat.Middle) currentGo.transform.position = GetInstancePosition(GuiStats[current]); isReadyEffect = true; } private void OnGUI() { if (GUI.Button(new Rect(10, 15, 105, 30), "Previous Effect")) { ChangeCurrent(-1); } if (GUI.Button(new Rect(130, 15, 105, 30), "Next Effect")) { ChangeCurrent(+1); } if(Prefabs[current]!=null)GUI.Label(new Rect(300, 15, 100, 20), "Prefab name is \"" + Prefabs[current].name + "\" \r\nHold any mouse button that would move the camera", guiStyleHeader); if (GUI.Button(new Rect(10, 60, 225, 30), "Day/Night")) { DirLight.intensity = !isDay ? 0.00f : oldLightIntensity; RenderSettings.ambientLight = !isDay ? new Color(0.1f, 0.1f, 0.1f) : oldAmbientColor; isDay = !isDay; } if (GUI.Button(new Rect(10, 105, 225, 30), "Change environment")) { if (isDefaultPlaneTexture) { Plane1.GetComponent<Renderer>().material = PlaneMaterials[0]; Plane2.GetComponent<Renderer>().material = PlaneMaterials[0]; } else { Plane1.GetComponent<Renderer>().material = PlaneMaterials[1]; Plane2.GetComponent<Renderer>().material = PlaneMaterials[2]; } isDefaultPlaneTexture = !isDefaultPlaneTexture; } if (current <= 40) { GUI.Label(new Rect(10, 152, 225, 30), "Ball Speed " + (int) prefabSpeed + "m", guiStyleHeader); prefabSpeed = GUI.HorizontalSlider(new Rect(115, 155, 120, 30), prefabSpeed, 1.0F, 30.0F); isHomingMove = GUI.Toggle(new Rect(10, 190, 150, 30), isHomingMove, " Is Homing Move"); effectSettings.MoveSpeed = prefabSpeed; } //GUI.Label(new Rect(1, 1, 30, 30), "" + (int)fps + " " + Screen.dpi, guiStyleHeader); } void Update() { anim.enabled = isHomingMove; //effectSettings.IsHomingMove = isHomingMove; timeleft -= Time.deltaTime; accum += Time.timeScale / Time.deltaTime; ++frames; if (timeleft <= 0.0) { fps = accum / frames; timeleft = UpdateInterval; accum = 0.0F; frames = 0; } if (isReadyEffect) { isReadyEffect = false; currentGo.SetActive(true); } if (GuiStats[current]==GuiStat.BallRotate) { currentGo.transform.localRotation = Quaternion.Euler(0, Mathf.PingPong(Time.time*5, 60)-50, 0); } if (GuiStats[current] == GuiStat.BallRotatex4) { currentGo.transform.localRotation = Quaternion.Euler(0, Mathf.PingPong(Time.time * 30, 100) - 70, 0); } } private void InstanceCurrent(GuiStat stat) { switch (stat) { case GuiStat.Ball: { MiddlePosition.SetActive(false); InstanceEffect(transform.position); break; } case GuiStat.BallRotate: { MiddlePosition.SetActive(false); InstanceEffect(transform.position); break; } case GuiStat.BallRotatex4: { MiddlePosition.SetActive(false); InstanceEffect(transform.position); break; } case GuiStat.Bottom: { MiddlePosition.SetActive(false); InstanceEffect(BottomPosition.transform.position); break; } case GuiStat.Top: { MiddlePosition.SetActive(false); InstanceEffect(TopPosition.transform.position); break; } case GuiStat.TopTarget: { MiddlePosition.SetActive(false); InstanceEffect(TopPosition.transform.position); break; } case GuiStat.Middle: { MiddlePosition.SetActive(true); InstanceEffect(MiddlePosition.transform.parent.transform.position); break; } case GuiStat.MiddleWithoutRobot: { MiddlePosition.SetActive(false); InstanceEffect(MiddlePosition.transform.position); break; } } } private Vector3 GetInstancePosition(GuiStat stat) { switch (stat) { case GuiStat.Ball: { return transform.position; } case GuiStat.BallRotate: { return transform.position; } case GuiStat.BallRotatex4: { return transform.position; } case GuiStat.Bottom: { return BottomPosition.transform.position; } case GuiStat.Top: { return TopPosition.transform.position; } case GuiStat.TopTarget: { return TopPosition.transform.position; } case GuiStat.MiddleWithoutRobot: { return MiddlePosition.transform.parent.transform.position; } case GuiStat.Middle: { return MiddlePosition.transform.parent.transform.position; } } return transform.position; } void ChangeCurrent(int delta) { Destroy(currentGo); CancelInvoke("InstanceDefaulBall"); current += delta; if (current> Prefabs.Length - 1) current = 0; else if (current < 0) current = Prefabs.Length - 1; if(effectSettings!=null) effectSettings.EffectDeactivated -= effectSettings_EffectDeactivated; MiddlePosition.SetActive(GuiStats[current]==GuiStat.Middle); //if (GuiStats[current] == GuiStat.Middle) Invoke("InstanceDefaulBall", 2); InstanceEffect(GetInstancePosition(GuiStats[current])); } }
//#define NoTagPenalty //Enables or disables tag penalties. Can give small performance boost #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif #if !UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3 #define UNITY_4 #endif using UnityEngine; using UnityEditor; using System.Collections.Generic; using Pathfinding; [CustomEditor(typeof(Seeker))] [RequireComponent(typeof(CharacterController))] [RequireComponent(typeof(Seeker))] public class SeekerEditor : Editor { public static bool modifiersOpen = false; public static bool tagPenaltiesOpen = false; List<IPathModifier> mods = null; public override void OnInspectorGUI () { DrawDefaultInspector (); Seeker script = target as Seeker; #if !UNITY_LE_4_3 Undo.RecordObject ( script, "modify settings on Seeker"); #endif EditorGUILayoutx.SetTagField (new GUIContent ("Valid Tags"),ref script.traversableTags); EditorGUI.indentLevel=0; tagPenaltiesOpen = EditorGUILayout.Foldout (tagPenaltiesOpen,new GUIContent ("Tag Penalties","Penalties for each tag")); if (tagPenaltiesOpen) { EditorGUI.indentLevel=2; string[] tagNames = AstarPath.FindTagNames (); for (int i=0;i<script.tagPenalties.Length;i++) { int tmp = EditorGUILayout.IntField ((i < tagNames.Length ? tagNames[i] : "Tag "+i),(int)script.tagPenalties[i]); if (tmp < 0) tmp = 0; script.tagPenalties[i] = tmp; } if (GUILayout.Button ("Edit Tag Names...")) { AstarPathEditor.EditTags (); } } EditorGUI.indentLevel=1; //Do some loading and checking if (!AstarPathEditor.stylesLoaded) { if (!AstarPathEditor.LoadStyles ()) { if (AstarPathEditor.upArrow == null) { AstarPathEditor.upArrow = GUI.skin.FindStyle ("Button"); AstarPathEditor.downArrow = AstarPathEditor.upArrow; } } else { AstarPathEditor.stylesLoaded = true; } } GUIStyle helpBox = GUI.skin.GetStyle ("helpBox"); if (mods == null) { mods = new List<IPathModifier>(script.GetComponents<MonoModifier>() as IPathModifier[]); } else { mods.Clear (); mods.AddRange (script.GetComponents<MonoModifier>() as IPathModifier[]); } mods.Add (script.startEndModifier as IPathModifier); bool changed = true; while (changed) { changed = false; for (int i=0;i<mods.Count-1;i++) { if (mods[i].Priority < mods[i+1].Priority) { IPathModifier tmp = mods[i+1]; mods[i+1] = mods[i]; mods[i] = tmp; changed = true; } } } for (int i=0;i<mods.Count;i++) { if (mods.Count-i != mods[i].Priority) { mods[i].Priority = mods.Count-i; GUI.changed = true; EditorUtility.SetDirty (target); } } bool modifierErrors = false; IPathModifier prevMod = mods[0]; //Loops through all modifiers and checks if there are any errors in converting output between modifiers for (int i=1;i<mods.Count;i++) { MonoModifier monoMod = mods[i] as MonoModifier; if ((prevMod as MonoModifier) != null && !(prevMod as MonoModifier).enabled) { if (monoMod == null || monoMod.enabled) prevMod = mods[i]; continue; } if ((monoMod == null || monoMod.enabled) && prevMod != mods[i] && !ModifierConverter.CanConvert (prevMod.output, mods[i].input)) { modifierErrors = true; } if (monoMod == null || monoMod.enabled) { prevMod = mods[i]; } } EditorGUI.indentLevel = 0; #if UNITY_LE_4_3 modifiersOpen = EditorGUILayout.Foldout (modifiersOpen, "Modifiers Priorities"+(modifierErrors ? " - Errors in modifiers!" : ""),EditorStyles.foldout); #else modifiersOpen = EditorGUILayout.Foldout (modifiersOpen, "Modifiers Priorities"+(modifierErrors ? " - Errors in modifiers!" : "")); #endif #if UNITY_LE_4_3 EditorGUI.indentLevel = 1; #endif if (modifiersOpen) { #if UNITY_LE_4_3 EditorGUI.indentLevel+= 2; #endif //GUILayout.BeginHorizontal (); //GUILayout.Space (28); if (GUILayout.Button ("Modifiers attached to this gameObject are listed here.\nModifiers with a higher priority (higher up in the list) will be executed first.\nClick here for more info",helpBox)) { Application.OpenURL (AstarPathEditor.GetURL ("modifiers")); } EditorGUILayout.HelpBox ("Original or All can be converted to anything\n" + "NodePath can be converted to VectorPath\n"+ "VectorPath can only be used as VectorPath\n"+ "Vector takes both VectorPath and StrictVectorPath\n"+ "Strict... can be converted to the non-strict variant", MessageType.None ); //GUILayout.EndHorizontal (); prevMod = mods[0]; for (int i=0;i<mods.Count;i++) { //EditorGUILayout.LabelField (mods[i].GetType ().ToString (),mods[i].Priority.ToString ()); MonoModifier monoMod = mods[i] as MonoModifier; Color prevCol = GUI.color; if (monoMod != null && !monoMod.enabled) { GUI.color *= new Color (1,1,1,0.5F); } GUILayout.BeginVertical (GUI.skin.box); if (i > 0) { if ((prevMod as MonoModifier) != null && !(prevMod as MonoModifier).enabled) { prevMod = mods[i]; } else { if ((monoMod == null || monoMod.enabled) && !ModifierConverter.CanConvert (prevMod.output, mods[i].input)) { //GUILayout.BeginHorizontal (); //GUILayout.Space (28); GUIUtilityx.SetColor (new Color (0.8F,0,0)); GUILayout.Label ("Cannot convert "+prevMod.GetType ().Name+"'s output to "+mods[i].GetType ().Name+"'s input\nRearranging the modifiers might help",EditorStyles.whiteMiniLabel); GUIUtilityx.ResetColor (); //GUILayout.EndHorizontal (); } if (monoMod == null || monoMod.enabled) { prevMod = mods[i]; } } } GUILayout.Label ("Input: "+mods[i].input,EditorStyles.wordWrappedMiniLabel); int newPrio = EditorGUILayoutx.UpDownArrows (new GUIContent (ObjectNames.NicifyVariableName (mods[i].GetType ().ToString ())),mods[i].Priority, EditorStyles.label, AstarPathEditor.upArrow,AstarPathEditor.downArrow); GUILayout.Label ("Output: "+mods[i].output,EditorStyles.wordWrappedMiniLabel); GUILayout.EndVertical (); int diff = newPrio - mods[i].Priority; if (i > 0 && diff > 0) { mods[i-1].Priority = mods[i].Priority; } else if (i < mods.Count-1 && diff < 0) { mods[i+1].Priority = mods[i].Priority; } mods[i].Priority = newPrio; GUI.color = prevCol; } #if UNITY_LE_4_3 EditorGUI.indentLevel-= 2; #endif } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyArray { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Array operations. /// </summary> public partial interface IArray { /// <summary> /// Get null array value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid array [1, 2, 3 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty array value [] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [true, false, false, true] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<bool?>>> GetBooleanTfftWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [true, false, false, true] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBooleanTfftWithHttpMessagesAsync(IList<bool?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [true, null, false] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<bool?>>> GetBooleanInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [true, 'boolean', false] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<bool?>>> GetBooleanInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, -1, 3, 300] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetIntegerValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [1, -1, 3, 300] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutIntegerValidWithHttpMessagesAsync(IList<int?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, null, 0] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetIntInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, 'integer', 0] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetIntInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, -1, 3, 300] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<long?>>> GetLongValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [1, -1, 3, 300] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutLongValidWithHttpMessagesAsync(IList<long?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long array value [1, null, 0] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<long?>>> GetLongInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long array value [1, 'integer', 0] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<long?>>> GetLongInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0, -0.01, 1.2e20] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetFloatValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value [0, -0.01, 1.2e20] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutFloatValidWithHttpMessagesAsync(IList<double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0.0, null, -1.2e20] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetFloatInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [1.0, 'number', 0.0] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetFloatInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0, -0.01, 1.2e20] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetDoubleValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value [0, -0.01, 1.2e20] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleValidWithHttpMessagesAsync(IList<double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0.0, null, -1.2e20] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetDoubleInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [1.0, 'number', 0.0] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetDoubleInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string array value ['foo1', 'foo2', 'foo3'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<string>>> GetStringValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['foo1', 'foo2', 'foo3'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutStringValidWithHttpMessagesAsync(IList<string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string array value ['foo', null, 'foo2'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<string>>> GetStringWithNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string array value ['foo', 123, 'foo2'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<string>>> GetStringWithInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value ['2000-12-01', '1980-01-02', '1492-10-12'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['2000-12-01', '1980-01-02', '1492-10-12'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateValidWithHttpMessagesAsync(IList<DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2012-01-01', null, '1776-07-04'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2011-03-22', 'date'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time array value ['2000-12-01t00:00:01z', /// '1980-01-02T00:11:35+01:00', '1492-10-12T10:15:01-08:00'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['2000-12-01t00:00:01z', /// '1980-01-02T00:11:35+01:00', '1492-10-12T10:15:01-08:00'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeValidWithHttpMessagesAsync(IList<DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2000-12-01t00:00:01z', null] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2000-12-01t00:00:01z', 'date-time'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, /// 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeRfc1123ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan /// 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeRfc1123ValidWithHttpMessagesAsync(IList<DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<TimeSpan?>>> GetDurationValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDurationValidWithHttpMessagesAsync(IList<TimeSpan?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte array value [hex(FF FF FF FA), hex(01 02 03), hex (25, /// 29, 43)] with each item encoded in base64 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<byte[]>>> GetByteValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, /// 43)] with each elementencoded in base 64 /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutByteValidWithHttpMessagesAsync(IList<byte[]> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte array value [hex(AB, AC, AD), null] with the first item /// base64 encoded /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<byte[]>>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty array of complex type [] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type with null item [{'integer': 1 'string': /// '2'}, null, {'integer': 5, 'string': '6'}] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type with empty item [{'integer': 1 'string': /// '2'}, {}, {'integer': 5, 'string': '6'}] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type with [{'integer': 1 'string': '2'}, /// {'integer': 3, 'string': '4'}, {'integer': 5, 'string': '6'}] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put an array of complex type with values [{'integer': 1 'string': /// '2'}, {'integer': 3, 'string': '4'}, {'integer': 5, 'string': /// '6'}] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutComplexValidWithHttpMessagesAsync(IList<Product> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a null array /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an empty array [] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [['1', '2', '3'], null, ['7', /// '8', '9']] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [['1', '2', '3'], [], ['7', '8', /// '9']] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [['1', '2', '3'], ['4', '5', /// '6'], ['7', '8', '9']] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put An array of array of strings [['1', '2', '3'], ['4', '5', /// '6'], ['7', '8', '9']] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutArrayValidWithHttpMessagesAsync(IList<IList<string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries with value null /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, null, {'7': /// 'seven', '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, {}, {'7': 'seven', /// '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, {'4': 'four', '5': /// 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, {'4': 'four', '5': /// 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryValidWithHttpMessagesAsync(IList<IDictionary<string, string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * 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.Linq; namespace Aerospike.Client { /// <summary> /// Unique record identifier. Records can be identified using a specified namespace, /// an optional set name, and a user defined key which must be unique within a set. /// Records can also be identified by namespace/digest which is the combination used /// on the server. /// </summary> public sealed class Key { /// <summary> /// Namespace. Equivalent to database name. /// </summary> public readonly string ns; /// <summary> /// Optional set name. Equivalent to database table. /// </summary> public readonly string setName; /// <summary> /// Unique server hash value generated from set name and user key. /// </summary> public readonly byte[] digest; /// <summary> /// Original user key. This key is immediately converted to a hash digest. /// This key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> public readonly Value userKey; /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, Value key) { this.ns = ns; this.setName = setName; this.userKey = key; // Some value types can't be used as keys (csblob, list, map, null). Verify key type. key.ValidateKeyType(); digest = ComputeDigest(setName, key); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, string key) { this.ns = ns; this.setName = setName; this.userKey = new Value.StringValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, byte[] key) { this.ns = ns; this.setName = setName; this.userKey = new Value.BytesValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <param name="offset">byte array segment offset</param> /// <param name="length">byte array segment length</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, byte[] key, int offset, int length) { this.ns = ns; this.setName = setName; this.userKey = new Value.ByteSegmentValue(key, offset, length); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, long key) { this.ns = ns; this.setName = setName; this.userKey = new Value.LongValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, ulong key) { this.ns = ns; this.setName = setName; this.userKey = new Value.UnsignedLongValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, int key) { this.ns = ns; this.setName = setName; this.userKey = new Value.IntegerValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, uint key) { this.ns = ns; this.setName = setName; this.userKey = new Value.UnsignedIntegerValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, short key) { this.ns = ns; this.setName = setName; this.userKey = new Value.ShortValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, ushort key) { this.ns = ns; this.setName = setName; this.userKey = new Value.UnsignedShortValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, bool key) { this.ns = ns; this.setName = setName; this.userKey = new Value.BooleanValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, byte key) { this.ns = ns; this.setName = setName; this.userKey = new Value.ByteValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, optional set name and user key. /// The set name and user defined key are converted to a digest before sending to the server. /// The user key is not used or returned by the server by default. If the user key needs /// to persist on the server, use one of the following methods: /// <list type="bullet"> /// <item>Set "WritePolicy.sendKey" to true. In this case, the key will be sent to the server for storage on writes /// and retrieved on multi-record scans and queries.</item> /// <item>Explicitly store and retrieve the key in a bin.</item> /// </list> /// </summary> /// <param name="ns">namespace</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">user defined unique identifier within set.</param> /// <exception cref="AerospikeException">if digest computation fails</exception> public Key(string ns, string setName, sbyte key) { this.ns = ns; this.setName = setName; this.userKey = new Value.SignedByteValue(key); digest = ComputeDigest(setName, this.userKey); } /// <summary> /// Initialize key from namespace, digest, optional set name and optional userKey. /// </summary> /// <param name="ns">namespace</param> /// <param name="digest">unique server hash value</param> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="userKey">optional original user key (not hash digest)</param> public Key(string ns, byte[] digest, string setName, Value userKey) { this.ns = ns; this.digest = digest; this.setName = setName; this.userKey = userKey; } /// <summary> /// Hash lookup uses namespace and digest. /// </summary> public override int GetHashCode() { int result = 1; foreach (byte element in digest) { result = 31 * result + element; } return 31 * result + ns.GetHashCode(); } /// <summary> /// Equality uses namespace and digest. /// </summary> public override bool Equals(object obj) { Key other = (Key) obj; if (digest.Length != other.digest.Length) { return false; } for (int i = 0; i < digest.Length; i++) { if (digest[i] != other.digest[i]) { return false; } } return ns.Equals(other.ns); } /// <summary> /// Return key elements in string format. /// </summary> public override string ToString() { return this.ns + ":" + this.setName + ":" + this.userKey + ":" + ByteUtil.BytesToHexString(this.digest); } /// <summary> /// Generate unique server hash value from set name, key type and user defined key. /// The hash function is RIPEMD-160 (a 160 bit hash). /// </summary> /// <param name="setName">optional set name, enter null when set does not exist</param> /// <param name="key">record identifier, unique within set</param> /// <returns>unique server hash value</returns> /// <exception cref="AerospikeException">if digest computation fails</exception> public static byte[] ComputeDigest(string setName, Value key) { byte[] buffer = ThreadLocalData.GetBuffer(); int offset = ByteUtil.StringToUtf8(setName, buffer, 0); buffer[offset++] = (byte)key.Type; offset += key.Write(buffer, offset); return Hash.Algorithm.ComputeHash(buffer, 0, offset); } } }
// 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; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; using System.Reflection; internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount { get { return System.Environment.TickCount; } } public static string GetResourceString(string key, params object[] args) { string fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = String.Empty; foreach (var arg in args) { if (sargs != String.Empty) sargs += ", "; sargs += arg.ToString(); } return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object[] args) { return GetResourceString(key, args); } private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Diagnostics.Contracts.Internal { internal class Contract { public static void Assert(bool invariant) { Assert(invariant, string.Empty); } public static void Assert(bool invariant, string message) { if (!invariant) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); throw new Exception("Assertion failed: " + message); } } public static void EndContractBlock() { } } } namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { using System.Reflection; #if (ES_BUILD_PCL || PROJECTN) [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif internal static class ReflectionExtensions { #if (!ES_BUILD_PCL && !PROJECTN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // ES_BUILD_PCL // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { return type.GetRuntimeProperties(); } public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type GetNestedType(this Type type, string nestedTypeName) { TypeInfo ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(Decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } // Defining some no-ops in PCL builds #if ES_BUILD_PCL || PROJECTN namespace System.Security { class SuppressUnmanagedCodeSecurityAttribute : Attribute { } enum SecurityAction { Demand } } namespace System.Security.Permissions { class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } } class PermissionSetAttribute : Attribute { public PermissionSetAttribute(System.Security.SecurityAction action) { } public bool Unrestricted { get; set; } } } #endif #if PROJECTN namespace System { public static class AppDomain { public static int GetCurrentThreadId() { return (int)Interop.mincore.GetCurrentThreadId(); } } } #endif
using System; using System.Data; using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Framework; using DotNetNuke.Modules.UserDefinedTable.Components; using DotNetNuke.Modules.UserDefinedTable.Controllers.Caches; using DotNetNuke.Modules.UserDefinedTable.Interfaces; using DotNetNuke.Security; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Mail; using DotNetNuke.UI.Modules; using DotNetNuke.UI.Skins.Controls; using DotNetNuke.UI.UserControls; using DotNetNuke.UI.Utilities; using Microsoft.VisualBasic; using Microsoft.VisualBasic.CompilerServices; using DataProvider = DotNetNuke.Data.DataProvider; using Globals = DotNetNuke.Common.Globals; namespace DotNetNuke.Modules.UserDefinedTable { /// ----------------------------------------------------------------------------- /// <summary> /// The ManageUserDefinedTable Class provides the UI for manageing the UserDefinedTable /// </summary> /// ----------------------------------------------------------------------------- public partial class Configuration : ModuleUserControlBase, IActionable, IPostBackEventHandler { // ReSharper disable InconsistentNaming protected LabelControl lblNormalizeFlag; protected Panel dshRendering; protected Panel dshFormsSettings; protected Panel dshChangeTracking; protected TextEditor teSubmissionSuccess; protected TextEditor teTrackingMessage; protected LabelControl lblMultipleValues; protected LabelControl lblInputSettings; protected LabelControl lblDefault; protected LabelControl lblOutputSettings; protected UrlControl XslUserDefinedUrlControl; protected UrlControl XslTracking; protected UrlControl urlOnSubmissionRedirect; protected UrlControl userDefinedHandlebarsUrlControl; // ReSharper restore InconsistentNaming ModuleController _objModules; const string StrAuto = "[AUTO]"; protected int RowCount; UserDefinedTableController _udtController; #region Private Properties public ModuleController ModulesController { get { return _objModules ?? (_objModules = new ModuleController()); } } UserDefinedTableController UdtController { get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); } } #endregion #region Private Methods void BindData() { BindSettings(); } /// ----------------------------------------------------------------------------- /// <summary> /// Gets the module settings and binds it to the web controls /// </summary> /// ----------------------------------------------------------------------------- void BindSettings() { var oldSelectedSortField = cboSortField.SelectedValue; var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId); cboSortField.DataSource = new DataView(fields, "UserDefinedFieldId<>\'-1\'", string.Empty, DataViewRowState.CurrentRows); cboSortField.DataBind(); cboSortField.Items.Insert(0, new ListItem(Localization.GetString("Not_Specified"), string.Empty)); if (cboSortField.Items.FindByValue(oldSelectedSortField) != null) { cboSortField.Items.FindByValue(oldSelectedSortField).Selected = true; } chkExcludeFromSearch.Checked = ModuleContext.Settings[SettingName.ExcludeFromSearch].AsBoolean(); cboSortField.ClearSelection(); var sortFieldSetting = ModuleContext.Settings[SettingName.SortField].AsString(); if (cboSortField.Items.FindByValue(sortFieldSetting) != null) { cboSortField.Items.FindByValue(sortFieldSetting).Selected = true; } cboSortOrder.ClearSelection(); var sortOrderSetting = ModuleContext.Settings[SettingName.SortOrder].AsString(); if (cboSortOrder.Items.FindByValue(sortOrderSetting) != null) { cboSortOrder.Items.FindByValue(sortOrderSetting).Selected = true; } txtFilter.Text = ModuleContext.Settings[SettingName.Filter].AsString(); txtTopCount.Text = ModuleContext.Settings[SettingName.TopCount].AsString(); chkShowSearchTextBox.Checked = ModuleContext.Settings[SettingName.ShowSearchTextBox].AsBoolean(); chkUseButtons.Checked = ModuleContext.Settings[SettingName.UseButtonsInForm].AsBoolean(); chkShowNoRecordsUntilSearch.Checked = ModuleContext.Settings[SettingName.ShowNoRecordsUntilSearch].AsBoolean(); chkSimpleSearch.Checked = ModuleContext.Settings[SettingName.SimpleSearch].AsBoolean(); chkURLSearch.Checked = ModuleContext.Settings[SettingName.URLSearch].AsBoolean(); cboPaging.ClearSelection(); if (ModuleContext.Settings.ContainsKey(SettingName.Paging)) { if (cboPaging.Items.FindByValue(ModuleContext.Settings[SettingName.Paging].AsString()) != null) { cboPaging.SelectedValue = ModuleContext.Settings[SettingName.Paging].AsString(); } } var strRenderMethod = ModuleContext.Settings[SettingName.RenderingMethod].AsString(); if (strRenderMethod == string.Empty) { strRenderMethod = RenderingMethod.GridRendering; } renderMethodRadioButtonList.SelectedValue = strRenderMethod; try { if (ModuleContext.Settings.ContainsKey(SettingName.XslUserDefinedStyleSheet)) { XslUserDefinedUrlControl.Url = ModuleContext.Settings[SettingName.XslUserDefinedStyleSheet].AsString(); } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { //Old StyleSheet removed } #region Handlebars Template if (ModuleContext.Settings.ContainsKey(SettingName.UserDefinedHandlebarsTemplateUrl)) { userDefinedHandlebarsUrlControl.Url = ModuleContext.Settings[SettingName.UserDefinedHandlebarsTemplateUrl].AsString(); } #endregion //Expand sections only, if not all values set to default: rblUsageListForm.SelectedValue = ModuleContext.Settings[SettingName.ListOrForm].AsString("List"); //tracking chkTrackingOnDelete.Checked = ModuleContext.Settings[SettingName.TrackingTriggerOnDelete].AsBoolean(); chkTrackingOnNew.Checked = ModuleContext.Settings[SettingName.TrackingTriggerOnNew].AsBoolean(); chkTrackingOnUpdate.Checked = ModuleContext.Settings[SettingName.TrackingTriggerOnUpdate].AsBoolean(); txtOnNew.Text = ModuleContext.Settings[SettingName.TrackingTextOnNew].AsString(); txtOnUpdate.Text = ModuleContext.Settings[SettingName.TrackingTextOnUpdate].AsString(); txtOnDelete.Text = ModuleContext.Settings[SettingName.TrackingTextOnDelete].AsString(); txtTrackingEmailAddresses.Text = ModuleContext.Settings[SettingName.TrackingEmailTo].AsString(); txtTrackingEmail_CC.Text = ModuleContext.Settings[SettingName.TrackingEmailCc].AsString(); txtTrackingEmail_BCC.Text = ModuleContext.Settings[SettingName.TrackingEmailBcc].AsString(); txtTrackingEmail_from.Text = ModuleContext.Settings[SettingName.TrackingEmailFrom].AsString(); txtTrackingEmail_replyto.Text = ModuleContext.Settings[SettingName.TrackingEmailReplyTo].AsString(); txtTrackingSubject.Text = ModuleContext.Settings[SettingName.TrackingSubject].AsString(); var strTrackingScript = ModuleContext.Settings[SettingName.TrackingScript].AsString(StrAuto); if (strTrackingScript == StrAuto) { rblBodyType.SelectedValue = "Auto"; } else { rblBodyType.SelectedValue = "XslScript"; try { XslTracking.Url = strTrackingScript; } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { //Old StyleSheet removed } } //form settings rblOnSubmission.SelectedValue = ModuleContext.Settings[SettingName.UponSubmitAction].AsString("Form"); urlOnSubmissionRedirect.Url = ModuleContext.Settings[SettingName.UponSubmitRedirect].AsString(); } bool ValidateMailTo() { var fields = FieldController.GetFieldsTable(ModuleContext.ModuleId, false); return TestForValidEmailSources(fields, txtTrackingEmailAddresses.Text) && TestForValidEmailSources(fields, txtTrackingEmail_CC.Text) && TestForValidEmailSources(fields, txtTrackingEmail_BCC.Text) && TestForValidEmailSources(fields, txtTrackingEmail_replyto.Text) && TestForValidEmailSources(fields, txtTrackingEmail_from.Text); } bool TestForValidEmailSources(DataTable fields, string emailSources) { foreach (var sx in emailSources.Split(';'.ToString(CultureInfo.InvariantCulture).ToCharArray())) { var source = sx.Trim(); if (source.Length > 0) { if (source.StartsWith("[") && source.EndsWith("]")) { var fieldtitle = source.Substring(1, source.Length - 2); var rows = fields.Select(string.Format("{0}=\'{1}\'", FieldsTableColumn.Title, fieldtitle)); if (rows.Length == 1) { var type = DataType.ByName((string) (rows[0][FieldsTableColumn.Type])); if (!(type is IEmailAdressSource)) { UI.Skins.Skin.AddModuleMessage(this, string.Format( Localization.GetString("NotEmailSource", LocalResourceFile), fieldtitle), ModuleMessage.ModuleMessageType.YellowWarning); return false; } } else if (rows.Length == 0) { UI.Skins.Skin.AddModuleMessage(this, string.Format( Localization.GetString("NotEmailSource", LocalResourceFile), fieldtitle), ModuleMessage.ModuleMessageType.YellowWarning); return false; } } else { if (! Mail.IsValidEmailAddress(source, ModuleContext.PortalId)) { UI.Skins.Skin.AddModuleMessage(this, string.Format( Localization.GetString("NotEmailAddress", LocalResourceFile), source), ModuleMessage.ModuleMessageType.YellowWarning); return false; } } } } return true; } /// ----------------------------------------------------------------------------- /// <summary> /// Set the visibility of controls according to /// </summary> /// ----------------------------------------------------------------------------- void ApplySettingsVisibility() { var isFormMode = rblUsageListForm.SelectedValue == "Form"; rememberSettings.Visible = rblUsageListForm.SelectedValue.Contains("Form"); plainFormSettingSet.Visible = isFormMode; noFormSettings.Visible = !isFormMode; rowOnSubmissionRedirect.Visible = rblOnSubmission.SelectedValue == "Redirect"; rowSubmissionText.Visible = Convert.ToBoolean(! rowOnSubmissionRedirect.Visible); rowTrackingScript.Visible = Convert.ToBoolean(rblBodyType.SelectedValue == "XslScript"); switch (renderMethodRadioButtonList.SelectedValue) { case RenderingMethod.GridRendering: rowUserDefined.Visible = false; handlebarsTemplatePanel.Visible = false; break; case RenderingMethod.UserdefinedXSL: rowUserDefined.Visible = true; handlebarsTemplatePanel.Visible = false; break; case RenderingMethod.UserDefinedHandlebarsTemplate: rowUserDefined.Visible = false; handlebarsTemplatePanel.Visible = true; break; } } int GetEditableFileId(string url) { if (LikeOperator.LikeString(url, "fileid=*", CompareMethod.Binary)) { var fileId = int.Parse(UrlUtils.GetParameterValue(url)); var f = FileManager.Instance.GetFile(fileId); if (Utilities.HasWritePermission(f.Folder, ModuleContext.PortalId)) { return fileId; } } return - 1; } void UpdateModuleSetting(string name, string value) { ModulesController.UpdateModuleSetting(ModuleContext.ModuleId, name, value); ModuleContext.Settings[name] = value; } void UpdateTabModuleSetting(string name, string value) { ModulesController.UpdateTabModuleSetting(ModuleContext.TabModuleId, name, value); ModuleContext.Settings[name] = value; } /// <summary> /// Save settings /// </summary> void SaveSettings() { try { // clear html cache new CachedHtmlContentController().DeleteCachedHtmlContentsByModuleId(ModuleContext.ModuleId); UpdateModuleSetting(SettingName.ExcludeFromSearch, chkExcludeFromSearch.Checked.ToString(CultureInfo.InvariantCulture)); if (cboSortField.SelectedItem != null) { var sortOrder = cboSortField.SelectedIndex == 0 ? string.Empty : cboSortOrder.SelectedItem.Value.AsString("ASC"); UpdateTabModuleSetting(SettingName.SortOrder, sortOrder); UpdateTabModuleSetting(SettingName.SortField, cboSortField.SelectedItem.Value); } else { UpdateTabModuleSetting(SettingName.SortOrder, string.Empty); UpdateTabModuleSetting(SettingName.SortField, string.Empty); } //save rendering and rendering specific values var strRenderingMethod = renderMethodRadioButtonList.SelectedValue; var strUserDefinedXsl = ""; if (strRenderingMethod == RenderingMethod.UserdefinedXSL && XslUserDefinedUrlControl.Url != string.Empty) { var file = FileManager.Instance.GetFile(int.Parse(XslUserDefinedUrlControl.Url.Substring(7))); if (file == null) { strRenderingMethod = RenderingMethod.GridRendering; } else { strUserDefinedXsl = file.Folder + file.FileName; } } // BEGIN: Handlebars template if (strRenderingMethod == RenderingMethod.UserDefinedHandlebarsTemplate) { var file = FileManager.Instance.GetFile(int.Parse(userDefinedHandlebarsUrlControl.Url.Substring(7))); if (file == null) { strRenderingMethod = RenderingMethod.GridRendering; } else { UpdateTabModuleSetting(SettingName.UserDefinedHandlebarsTemplateUrl, file.Folder + file.FileName); } } // END: Handlebars template UpdateTabModuleSetting(SettingName.XslUserDefinedStyleSheet, strUserDefinedXsl); UpdateTabModuleSetting(SettingName.RenderingMethod, strRenderingMethod); //Paging UpdateTabModuleSetting(SettingName.Paging, cboPaging.SelectedValue); //Filter UpdateTabModuleSetting(SettingName.Filter, txtFilter.Text); if (txtTopCount.Text == string.Empty) { UpdateModuleSetting(SettingName.TopCount, string.Empty); } else if (Information.IsNumeric(txtTopCount.Text)) { var count = int.Parse(txtTopCount.Text); if (count < 1) { count = 1; } if (count > 1000) { count = 1000; } UpdateModuleSetting(SettingName.TopCount, count.ToString(CultureInfo.InvariantCulture)); } UpdateTabModuleSetting(SettingName.TopCount, txtTopCount.Text); //Search UpdateTabModuleSetting(SettingName.ShowSearchTextBox, chkShowSearchTextBox.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.ShowNoRecordsUntilSearch, chkShowNoRecordsUntilSearch.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.SimpleSearch, chkSimpleSearch.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.UseButtonsInForm, chkUseButtons.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.URLSearch, chkURLSearch.Checked.ToString(CultureInfo.InvariantCulture)); //forms or list UpdateTabModuleSetting(SettingName.ListOrForm, rblUsageListForm.SelectedValue); //form UpdateTabModuleSetting(SettingName.SubmissionText, HttpUtility.HtmlDecode(teSubmissionSuccess.Text)); UpdateTabModuleSetting(SettingName.UponSubmitRedirect, urlOnSubmissionRedirect.Url); UpdateTabModuleSetting(SettingName.UponSubmitAction, rblOnSubmission.SelectedValue); //tracking var strTrackingEmailSkript = ""; if (rblBodyType.SelectedValue == "XslScript" && XslTracking.Url != string.Empty) { var file = FileManager.Instance.GetFile(int.Parse(XslTracking.Url.Substring(7))); if (file != null) { strTrackingEmailSkript = file.Folder + file.FileName; } } else { strTrackingEmailSkript = StrAuto; } UpdateTabModuleSetting(SettingName.TrackingScript, strTrackingEmailSkript); UpdateTabModuleSetting(SettingName.TrackingEmailTo, txtTrackingEmailAddresses.Text); UpdateTabModuleSetting(SettingName.TrackingEmailCc, txtTrackingEmail_CC.Text); UpdateTabModuleSetting(SettingName.TrackingEmailBcc, txtTrackingEmail_BCC.Text); UpdateTabModuleSetting(SettingName.TrackingEmailReplyTo, txtTrackingEmail_replyto.Text); UpdateTabModuleSetting(SettingName.TrackingEmailFrom, txtTrackingEmail_from.Text); UpdateTabModuleSetting(SettingName.TrackingSubject, txtTrackingSubject.Text); UpdateTabModuleSetting(SettingName.TrackingMessage, HttpUtility.HtmlDecode(teTrackingMessage.Text)); UpdateTabModuleSetting(SettingName.TrackingTriggerOnDelete, chkTrackingOnDelete.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.TrackingTriggerOnNew, chkTrackingOnNew.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.TrackingTriggerOnUpdate, chkTrackingOnUpdate.Checked.ToString(CultureInfo.InvariantCulture)); UpdateTabModuleSetting(SettingName.TrackingTextOnNew, txtOnNew.Text); UpdateTabModuleSetting(SettingName.TrackingTextOnUpdate, txtOnUpdate.Text); UpdateTabModuleSetting(SettingName.TrackingTextOnDelete, txtOnDelete.Text); } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } void SetHelpLinks() { var helpUrL = string.Format("javascript:OpenHelpWindow(\'{0}\')", ResolveUrl( "~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_Tokens_6")); hlpToken2.NavigateUrl = helpUrL; helpUrL = string.Format("javascript:OpenHelpWindow(\'{0}\')", ResolveUrl( "~/desktopmodules/userdefinedtable/HelpPopup.aspx?resourcekey=Help_HiddenColumns")); hlpColumns2.NavigateUrl = helpUrL; } #endregion #region Event Handlers protected override void OnInit(EventArgs e) { // Moved from BindSettings to handle issues with the RTE teSubmissionSuccess.Text = ModuleContext.Settings[SettingName.SubmissionText].AsString(Localization.GetString("SubmissionSuccess", LocalResourceFile)); teTrackingMessage.Text = ModuleContext.Settings[SettingName.TrackingMessage].AsString(); cmdCancel.Click += cmdCancel_Click; cmdEditEmail.Click += cmdEditEmail_Click; cmdEditXSL.Click += cmdEditXSL_Click; cmdGenerateEmail.Click += cmdGenerateEmail_Click; cmdGenerateXSL.Click += cmdGenerateXSL_Click; cmdUpdate.Click += cmdUpdate_Click; chkShowSearchTextBox.CheckedChanged += chkShowSearchTextBox_CheckedChanged; // BEGIN: Handlebars template cmdEditHandlebars.Click += cmdEditHandlebars_Click; cmdGenerateHandlebars.Click += cmdGenerateHandlebars_Click; // END: Handlebars template Load += Page_Load; Fields.LocalizeString = LocalizeString; Fields.LocalResourceFile = LocalResourceFile; Fields.ModuleContext = ModuleContext; jQuery.RequestDnnPluginsRegistration(); ClientAPI.RegisterClientReference(Page, ClientAPI.ClientNamespaceReferences.dnn); } void Page_Load(object sender, EventArgs e) { try { if (! Page.IsPostBack) { //Localize Grid BindData(); } SetHelpLinks(); ApplySettingsVisibility(); } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } #region Handlebars template /// <summary> /// Triggered when user clicks on Generate New button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void cmdGenerateHandlebars_Click(object sender, EventArgs e) { SaveSettings(); Response.Redirect(ModuleContext.EditUrl(ControlKeys.HandlebarsTemplatesFile), true); } /// <summary> /// Triggered when user clicks on Edit button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void cmdEditHandlebars_Click(object sender, EventArgs e) { var fileId = GetEditableFileId(userDefinedHandlebarsUrlControl.Url.ToLowerInvariant()); if (fileId > -1) { SaveSettings(); Response.Redirect(ModuleContext.EditUrl("FileID", fileId.ToString(CultureInfo.InvariantCulture), ControlKeys.HandlebarsTemplatesFile), true); } } #endregion void cmdCancel_Click(object sender, EventArgs e) { Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); } /// <summary> /// Save configuration /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void cmdUpdate_Click(object sender, EventArgs e) { if (ValidateMailTo()) { if (chkExcludeFromSearch.Checked) { DataProvider.Instance().DeleteSearchItems(ModuleContext.ModuleId); } SaveSettings(); Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); } } void cmdGenerateXSL_Click(object sender, EventArgs e) { SaveSettings(); Response.Redirect(ModuleContext.EditUrl("GenerateXsl"), true); } void cmdEditXSL_Click(object sender, EventArgs e) { var fileId = GetEditableFileId(XslUserDefinedUrlControl.Url.ToLowerInvariant()); if (fileId > - 1) { SaveSettings(); Response.Redirect(ModuleContext.EditUrl("FileID", fileId.ToString(CultureInfo.InvariantCulture), "GenerateXsl"), true); } } void chkShowSearchTextBox_CheckedChanged(object sender, EventArgs e) { var searchEnabled = chkShowSearchTextBox.Checked; chkShowNoRecordsUntilSearch.Enabled = searchEnabled; chkSimpleSearch.Enabled = searchEnabled; chkURLSearch.Enabled = searchEnabled; if (! searchEnabled) { chkShowNoRecordsUntilSearch.Checked = false; chkSimpleSearch.Checked = false; chkURLSearch.Checked = false; } } protected void cmdEditEmail_Click(object sender, EventArgs e) { var fileId = GetEditableFileId(XslTracking.Url.ToLowerInvariant()); if (fileId > - 1) { SaveSettings(); Response.Redirect(ModuleContext.EditUrl("FileID", fileId.ToString(CultureInfo.InvariantCulture), "GenerateXsl"), true); } } protected void cmdGenerateEmail_Click(object sender, EventArgs e) { SaveSettings(); Response.Redirect(ModuleContext.EditUrl("tracking", "true", "GenerateXsl"), true); } #endregion #region Optional Interfaces public ModuleActionCollection ModuleActions { get { var actions = new ModuleActionCollection(); var url = string.Format("javascript:{0}", Page.ClientScript.GetPostBackEventReference(this, "SaveSettingsAsDefault")); actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("SaveSettingsAsDefault.Action", LocalResourceFile), "", "", Utilities.IconURL("Save"), url, false, SecurityAccessLevel.Edit, true, false); url = string.Format("javascript:if (confirm(\'{0}\')) {1}", Localization.GetString("ResetModuleTabSettings.Confirm", LocalResourceFile).AsString().Replace("\'", "\\\'"), Page.ClientScript.GetPostBackEventReference(this, "ResetModuleTabSettings")); actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("ResetModuleTabSettings.Action", LocalResourceFile), "", "", Utilities.IconURL("Restore"), url, false, SecurityAccessLevel.Edit, true, false); url = string.Format("javascript:if (confirm(\'{0}\')) {1}", Localization.GetString("DeleteAll.Confirm", LocalResourceFile).AsString(). Replace("\'", "\\\'"), Page.ClientScript.GetPostBackEventReference(this, "DeleteAll")); actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("DeleteAll.Action", LocalResourceFile), "", "", Utilities.IconURL("Save"), url, false, SecurityAccessLevel.Edit, true, false); #region Export/Import Settings actions.Add(new ModuleAction(ModuleContext.GetNextActionID(), Localization.GetString("ExportModuleSettings.Action", LocalResourceFile), ModuleActionType.ExportModule, string.Empty, Utilities.IconURL("Edit"), ModuleContext.EditUrl(ControlKeys.ExportModuleSettings), string.Empty, false, SecurityAccessLevel.Edit, true, false)); actions.Add(new ModuleAction(ModuleContext.GetNextActionID(), Localization.GetString("ImportModuleSettings.Action", LocalResourceFile), ModuleActionType.ImportModule, string.Empty, Utilities.IconURL("Edit"), ModuleContext.EditUrl(ControlKeys.ImportModuleSettings), string.Empty, false, SecurityAccessLevel.Edit, true, false)); #endregion return actions; } } public void RaisePostBackEvent(string eventArgument) { switch (eventArgument) { case "ResetModuleTabSettings": ModulesController.DeleteTabModuleSettings(ModuleContext.TabModuleId); break; case "SaveSettingsAsDefault": SaveSettings(); var tabModuleSettings = ModulesController.GetTabModuleSettings(ModuleContext.TabModuleId); foreach (string key in tabModuleSettings.Keys) { ModulesController.UpdateModuleSetting(ModuleContext.ModuleId, key, tabModuleSettings[key].ToString()); } break; case "DeleteAll": UdtController.DeleteRows(); Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); break; } } #endregion } }
//--------------------------------------------------------------------------- // // File: PasswordTextPointer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: An override class representing a movable // position within a PasswordTextContainer. // //--------------------------------------------------------------------------- namespace System.Windows.Controls { using System; using System.Windows.Threading; using System.Diagnostics; using System.Windows.Documents; using MS.Internal; // TextNavigator implementation for the PasswordTextContainer. internal sealed class PasswordTextPointer : ITextPointer { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors // Creates a new PasswordTextPointer instance. internal PasswordTextPointer(PasswordTextContainer container, LogicalDirection gravity, int offset) { Debug.Assert(offset >= 0 && offset <= container.SymbolCount, "Bad PasswordTextPointer offset!"); _container = container; _gravity = gravity; _offset = offset; container.AddPosition(this); } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// <see cref="ITextPointer.SetLogicalDirection"/> /// </summary> void ITextPointer.SetLogicalDirection(LogicalDirection direction) { Debug.Assert(!_isFrozen, "Can't reposition a frozen pointer!"); if (direction != _gravity) { // We need to remove the position from the container since we're // going to change its gravity, which changes its internal sort order. this.Container.RemovePosition(this); _gravity = direction; // Now start tracking the position again, at it's new sort order. this.Container.AddPosition(this); } } /// <summary> /// Compares this TextPointer with another TextPointer. /// </summary> /// <param name="position"> /// The TextPointer to compare with. /// </param> /// <returns> /// Less than zero: this TextPointer preceeds position. /// Zero: this TextPointer is at the same location as position. /// Greater than zero: this TextPointer follows position. /// </returns> int ITextPointer.CompareTo(ITextPointer position) { int offset; int result; offset = ((PasswordTextPointer)position)._offset; if (_offset < offset) { result = -1; } else if (_offset > offset) { result = +1; } else { result = 0; } return result; } int ITextPointer.CompareTo(StaticTextPointer position) { return ((ITextPointer)this).CompareTo((ITextPointer)position.Handle0); } /// <summary> /// Returns the count of symbols between this TextPointer and another. /// </summary> /// <param name="position"> /// TextPointer to compare. /// </param> /// <returns> /// The return value will be negative if /// position preceeds this TextPointer, zero if the two TextPositions /// are equally positioned, or positive if position follows this /// TextPointer. /// </returns> int ITextPointer.GetOffsetToPosition(ITextPointer position) { return ((PasswordTextPointer)position)._offset - _offset; } /// <summary> /// Returns the TextPointerContext of a symbol bordering this TextPointer /// in a given direction. /// </summary> /// <param name="direction"> /// Direction to query. /// </param> /// <remarks> /// Returns TextPointerContext.None if the query is Backward at /// TextContainer.Start or Forward at TextContainer.End. /// </remarks> TextPointerContext ITextPointer.GetPointerContext(LogicalDirection direction) { TextPointerContext symbolType; if ((direction == LogicalDirection.Backward && _offset == 0) || (direction == LogicalDirection.Forward && _offset == _container.SymbolCount)) { symbolType = TextPointerContext.None; } else { symbolType = TextPointerContext.Text; } return symbolType; } /// <summary> /// Returns the count of characters between this TextPointer and the /// next non-Character symbol. /// </summary> /// <param name="direction"> /// Direction to query. /// </param> /// <remarks> /// If a non-Character symbol follows immediately in the specified /// direction, returns zero. /// /// TextContainer implementation does not guarantee that all neighboring /// characters are counted, but this method must return values consistent /// with GetText and TextPointerBase.Move. /// </remarks> int ITextPointer.GetTextRunLength(LogicalDirection direction) { int length; if (direction == LogicalDirection.Forward) { length = _container.SymbolCount - _offset; } else { length = _offset; } return length; } // <see cref="System.Windows.Documents.ITextPointer.GetText"/> string ITextPointer.GetTextInRun(LogicalDirection direction) { return TextPointerBase.GetTextInRun(this, direction); } int ITextPointer.GetTextInRun(LogicalDirection direction, char[] textBuffer, int startIndex, int count) { int finalCount; int i; // Truncate based on document size. if (direction == LogicalDirection.Forward) { finalCount = Math.Min(count, _container.SymbolCount - _offset); } else { finalCount = Math.Min(count, _offset); } // Substitute a placeholder char for the real password text. char passwordChar = _container.PasswordChar; for (i = 0; i < finalCount; i++) { textBuffer[startIndex + i] = passwordChar; } return finalCount; } /// <summary> /// Returns an embedded object, if any, bordering this TextPointer in the /// specified direction. /// </summary> /// <param name="direction"> /// Direction to query. /// </param> /// <returns> /// The embedded object, if any exists, otherwise null. /// </returns> object ITextPointer.GetAdjacentElement(LogicalDirection direction) { return null; } /// <summary> /// Returns the type of the text element whose edge is in a specified /// direction from position. /// </summary> /// <param name="direction"> /// Direction to query. /// </param> /// <returns> /// If the symbol in the specified direction is /// TextPointerContext.ElementStart or TextPointerContext.ElementEnd, then this /// method will return the type of element whose edge preceeds this /// TextPointer. /// /// Otherwise, the method returns null. /// </returns> Type ITextPointer.GetElementType(LogicalDirection direction) { return null; } /// <summary> /// Tests if this position has the same scoping element as /// another one. /// </summary> /// <param name="position"> /// Position to compare. /// </param> /// <returns> /// true if the scoping element for this position is the same /// instance as the one for a position passed as a parameter, /// or if the both positions have no scoping element. /// /// false otherwise. /// </returns> bool ITextPointer.HasEqualScope(ITextPointer position) { return true; } /// <summary> /// Returns the value of a DependencyProperty at the specified position. /// </summary> /// <param name="formattingProperty"> /// Property to query. /// </param> /// <returns> /// Returns the value of the specified property at position. /// If the position has no scoping text element, and the TextContainer /// has a null Parent property, returns DependencyProperty.UnsetValue. /// </returns> /// <remarks> /// This method considers inherited values from the containing control. /// This method will return property values even from positions with /// no scoping element (when GetElement returns null). /// </remarks> object ITextPointer.GetValue(DependencyProperty formattingProperty) { return _container.PasswordBox.GetValue(formattingProperty); } /// <summary> /// Returns the local value of a DependencyProperty at the specified position. /// </summary> /// <param name="formattingProperty"> /// Property to query. /// </param> object ITextPointer.ReadLocalValue(DependencyProperty formattingProperty) { // This method should never be called because we never have a scoping element. Debug.Assert(false); return DependencyProperty.UnsetValue; } /// <summary> /// Returns an enumerator for property values declared locally on this /// TextPointer's scoping element. If there is no scoping element, /// returns an empty enumerator. /// </summary> LocalValueEnumerator ITextPointer.GetLocalValueEnumerator() { return (new DependencyObject()).GetLocalValueEnumerator(); } ITextPointer ITextPointer.CreatePointer() { return new PasswordTextPointer(_container, _gravity, _offset); } // Unoptimized CreateStaticPointer implementation. // Creates a simple wrapper for an ITextPointer instance. StaticTextPointer ITextPointer.CreateStaticPointer() { return new StaticTextPointer(((ITextPointer)this).TextContainer, ((ITextPointer)this).CreatePointer()); } ITextPointer ITextPointer.CreatePointer(int distance) { return new PasswordTextPointer(_container, _gravity, _offset + distance); } ITextPointer ITextPointer.CreatePointer(LogicalDirection gravity) { return new PasswordTextPointer(_container, gravity, _offset); } /// <summary> /// Returns an immutable TextPointer located at some distance /// relative to this TextPointer. /// </summary> /// <param name="distance"> /// Distance, in symbols, of the new TextPointer relative to this one. /// distance may be negative, placing the new TextPositon behind this /// one. /// </param> /// <param name="gravity"> /// Gravity of the new TextPointer. /// </param> /// <remarks> /// The returned position may be the same instance as the calling /// position if distance is zero and this TextPointer is immutable with /// equal gravity. /// </remarks> ITextPointer ITextPointer.CreatePointer(int distance, LogicalDirection gravity) { return new PasswordTextPointer(_container, gravity, _offset + distance); } // <see cref="ITextPointer.Freeze"/> void ITextPointer.Freeze() { _isFrozen = true; } /// <summary> /// <see cref="ITextPointer.GetFrozenPointer"/> /// </summary> ITextPointer ITextPointer.GetFrozenPointer(LogicalDirection logicalDirection) { return TextPointerBase.GetFrozenPointer(this, logicalDirection); } /// <summary> /// Inserts text at a specified position. /// </summary> /// <param name="textData"> /// Text to insert. /// </param> void ITextPointer.InsertTextInRun(string textData) { _container.InsertText(this, textData); } /// <summary> /// Removes content covered by a pair of positions. /// </summary> /// <param name="limit"> /// Position following the last symbol to delete. endPosition must be /// scoped by the same text element as startPosition. /// </param> void ITextPointer.DeleteContentToPosition(ITextPointer limit) { _container.DeleteContent(this, limit); } /// <summary> /// Advances this TextNavigator over one or more symbols -- a single /// ElementStart/End or Object symbol, or a group of neighboring /// Character symbols. /// </summary> /// <param name="direction"> /// Direction to move. /// </param> /// <returns> /// true if the navigator is repositioned, false if the navigator /// borders the start or end of the TextContainer. /// </returns> /// <remarks> /// If the following symbol is of type EmbeddedObject, ElementBegin, /// or ElementEnd, this TextNavigator is advanced by exactly one symbol. /// /// If the following symbol is of type Character, this TextNavigator is /// advanced by some number of Character symbols. The exact value can /// determined in advance by calling TextPointer.GetTextLength at the /// current position. The movement distance is not guaranteed to /// include all neighboring characters, but it must be consistent with /// TextPointer.GetTextLength and TextContainer.GetText. /// /// If there is no following symbol in the indicated direction, this /// TextNavigator is not repositioned and the method returns /// TextPointerContext.None. /// </remarks> bool ITextPointer.MoveToNextContextPosition(LogicalDirection direction) { int offset; Debug.Assert(!_isFrozen, "Can't reposition a frozen pointer!"); if (direction == LogicalDirection.Backward) { if (this.Offset == 0) { return false; } offset = 0; } else { if (this.Offset == this.Container.SymbolCount) { return false; } offset = this.Container.SymbolCount; } this.Container.RemovePosition(this); this.Offset = offset; this.Container.AddPosition(this); return true; } /// <summary> /// Repositions this TextNavigator at a symbol offset relative to /// its current position. /// </summary> /// <param name="distance"> /// The offset count, in symbols. This value may be /// negative, positioning this TextNavigator behind its current /// position. /// </param> int ITextPointer.MoveByOffset(int distance) { int offset; Debug.Assert(!_isFrozen, "Can't reposition a frozen pointer!"); offset = this.Offset + distance; if (offset < 0 || offset > this.Container.SymbolCount) { Debug.Assert(false, "Bad distance!"); } this.Container.RemovePosition(this); this.Offset = offset; this.Container.AddPosition(this); return distance; } /// <summary> /// Repositions this TextNavigator at the location of a TextPointer. /// </summary> /// <param name="position"> /// TextPointer to move to. /// </param> void ITextPointer.MoveToPosition(ITextPointer position) { Debug.Assert(!_isFrozen, "Can't reposition a frozen pointer!"); this.Container.RemovePosition(this); this.Offset = ((PasswordTextPointer)position).Offset; this.Container.AddPosition(this); } /// <summary> /// Repositions this TextNavigator at an element edge of its scoping /// text element. /// </summary> /// <param name="edge"> /// The specific edge to move to. /// </param> void ITextPointer.MoveToElementEdge(ElementEdge edge) { Debug.Assert(!_isFrozen, "Can't reposition a frozen pointer!"); Debug.Assert(false, "No scoping element!"); } // <see cref="TextPointer.MoveToLineBoundary"/> int ITextPointer.MoveToLineBoundary(int count) { return TextPointerBase.MoveToLineBoundary(this, _container.TextView, count); } // <see cref="TextPointer.GetCharacterRect"/> Rect ITextPointer.GetCharacterRect(LogicalDirection direction) { return TextPointerBase.GetCharacterRect(this, direction); } bool ITextPointer.MoveToInsertionPosition(LogicalDirection direction) { return TextPointerBase.MoveToInsertionPosition(this, direction); } bool ITextPointer.MoveToNextInsertionPosition(LogicalDirection direction) { return TextPointerBase.MoveToNextInsertionPosition(this, direction); } // Candidate for replacing MoveToNextContextPosition for immutable TextPointer model ITextPointer ITextPointer.GetNextContextPosition(LogicalDirection direction) { ITextPointer pointer = ((ITextPointer)this).CreatePointer(); if (pointer.MoveToNextContextPosition(direction)) { pointer.Freeze(); } else { pointer = null; } return pointer; } // Candidate for replacing MoveToInsertionPosition for immutable TextPointer model ITextPointer ITextPointer.GetInsertionPosition(LogicalDirection direction) { ITextPointer pointer = ((ITextPointer)this).CreatePointer(); pointer.MoveToInsertionPosition(direction); pointer.Freeze(); return pointer; } // Candidate for replacing MoveToNextInsertionPosition for immutable TextPointer model ITextPointer ITextPointer.GetNextInsertionPosition(LogicalDirection direction) { ITextPointer pointer = ((ITextPointer)this).CreatePointer(); if (pointer.MoveToNextInsertionPosition(direction)) { pointer.Freeze(); } else { pointer = null; } return pointer; } // Returns the closest insertion position, treating all unicode code points // as valid insertion positions. A useful performance win over // GetNextInsertionPosition when only formatting scopes are important. ITextPointer ITextPointer.GetFormatNormalizedPosition(LogicalDirection direction) { ITextPointer pointer = ((ITextPointer)this).CreatePointer(); TextPointerBase.MoveToFormatNormalizedPosition(pointer, direction); pointer.Freeze(); return pointer; } /// <see cref="ITextPointer.ValidateLayout"/> bool ITextPointer.ValidateLayout() { return TextPointerBase.ValidateLayout(this, _container.TextView); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // <see cref="System.Windows.Documents.ITextPointer.ParentType"/> Type ITextPointer.ParentType { get { return null; } } // The PasswordTextContainer associated with this PasswordTextPointer. ITextContainer ITextPointer.TextContainer { get { return _container; } } // <see cref="TextPointer.HasValidLayout"/> bool ITextPointer.HasValidLayout { get { return (_container.TextView != null && _container.TextView.IsValid && _container.TextView.Contains(this)); } } // <see cref="ITextPointer.IsAtCaretUnitBoundary"/> bool ITextPointer.IsAtCaretUnitBoundary { get { // Because the PasswordTextContainer only ever contains PasswordChars // (as far as the renderer is concerned) all positions are caret // unit boundaries. return true; } } /// <summary> /// Returns the gravity of this TextPointer. /// </summary> /// <remarks> /// Gravity determines where a TextPointer moves after an insertion of /// content at its location. Backward gravity implies the TextPointer /// sticks with its preceding symbol; forward gravity implies the TextPointer /// sticks with its following symbol. /// </remarks> LogicalDirection ITextPointer.LogicalDirection { get { return _gravity; } } bool ITextPointer.IsAtInsertionPosition { get { return TextPointerBase.IsAtInsertionPosition(this); } } // <see cref="TextPointer.IsFrozen"/> bool ITextPointer.IsFrozen { get { return _isFrozen; } } // <see cref="ITextPointer.Offset"/> int ITextPointer.Offset { get { return TextPointerBase.GetOffset(this); } } // Offset in unicode chars within the document. int ITextPointer.CharOffset { get { return this.Offset; } } // The PasswordTextContainer associated with this PasswordTextPointer. internal PasswordTextContainer Container { get { return _container; } // setter removed (unused internal API). If needed, recall from history. } // This PasswordTextPointer's gravity. internal LogicalDirection LogicalDirection { get { return _gravity; } // setter removed (unused internal API). If needed, recall from history. } // The offset, in symbols, of this PasswordTextPointer. // NB: do not modify this value directly unless you have first removed // the positoin from PasswordTextContainer's _positionList with // PasswordTextContainter.RemovePosition! Failure to do so will break // the list's sort order. internal int Offset { get { return _offset; } set { _offset = value; } } #if DEBUG // Unique debug-only identifier for this instance. internal int DebugId { get { return _debugId; } } #endif // DEBUG #endregion Internal Properties //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // The PasswordTextContainer associated with this PasswordTextPointer. private PasswordTextContainer _container; // This position's gravity. private LogicalDirection _gravity; // The offset, in symbols, of this PasswordTextPointer. // NB: do not modify this value directly unless you have first removed // the positoin from PasswordTextContainer's _positionList with // PasswordTextContainter.RemovePosition! Failure to do so will break // the list's sort order. private int _offset; // True if Freeze has been called, in which case // this TextPointer is immutable and may not be repositioned. private bool _isFrozen; #if DEBUG private static int _debugIdCounter; // Unique debug-only identifier for this instance. private int _debugId = _debugIdCounter++; #endif #endregion Private Fields } }
//------------------------------------------------------------------------------ // <copyright file="WriteFileContext.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Configuration.Internal { using System.Configuration; using System.IO; using System.Security.Permissions; using System.Reflection; using System.Threading; using System.Security; using System.CodeDom.Compiler; using Microsoft.Win32; #if !FEATURE_PAL using System.Security.AccessControl; #endif internal class WriteFileContext { private const int SAVING_TIMEOUT = 10000; // 10 seconds private const int SAVING_RETRY_INTERVAL = 100; // 100 milliseconds private static volatile bool _osPlatformDetermined; private static volatile PlatformID _osPlatform; private TempFileCollection _tempFiles; private string _tempNewFilename; private string _templateFilename; internal WriteFileContext(string filename, string templateFilename) { string directoryname = UrlPath.GetDirectoryOrRootName(filename); _templateFilename = templateFilename; _tempFiles = new TempFileCollection(directoryname); try { _tempNewFilename = _tempFiles.AddExtension("newcfg"); } catch { ((IDisposable)_tempFiles).Dispose(); _tempFiles = null; throw; } } static WriteFileContext() { _osPlatformDetermined = false; } internal string TempNewFilename { get {return _tempNewFilename;} } // Complete // // Cleanup the WriteFileContext object based on either success // or failure // // Note: The current algorithm guarantess // 1) The file we are saving to will always be present // on the file system (ie. there will be no window // during saving in which there won't be a file there) // 2) It will always be available for reading from a // client and it will be complete and accurate. // // ... This means that writing is a bit more complicated, and may // have to be retried (because of reading lock), but I don't see // anyway to get around this given 1 and 2. // internal void Complete(string filename, bool success) { try { if (success) { if ( File.Exists( filename ) ) { // Test that we can write to the file ValidateWriteAccess( filename ); // Copy Attributes from original DuplicateFileAttributes( filename, _tempNewFilename ); } else { if ( _templateFilename != null ) { // Copy Acl from template file DuplicateTemplateAttributes( _templateFilename, _tempNewFilename ); } } ReplaceFile(_tempNewFilename, filename); // Don't delete, since we just moved it. _tempFiles.KeepFiles = true; } } finally { ((IDisposable)_tempFiles).Dispose(); _tempFiles = null; } } // DuplicateFileAttributes // // Copy all the files attributes that we care about from the source // file to the destination file // private void DuplicateFileAttributes( string source, string destination ) { #if !FEATURE_PAL FileAttributes attributes; DateTime creationTime; // Copy File Attributes, ie. Hidden, Readonly, etc. attributes = File.GetAttributes( source ); File.SetAttributes( destination, attributes ); // Copy Creation Time creationTime = File.GetCreationTimeUtc( source ); File.SetCreationTimeUtc( destination, creationTime ); // Copy ACL's DuplicateTemplateAttributes( source, destination ); #endif // FEATURE_PAL } // DuplicateTemplateAttributes // // Copy over all the attributes you would want copied from a template file. // As of right now this is just acl's // private void DuplicateTemplateAttributes( string source, string destination ) { #if !FEATURE_PAL if (IsWinNT) { FileSecurity fileSecurity; // Copy Security information fileSecurity = File.GetAccessControl( source, AccessControlSections.Access ); // Mark dirty, so effective for write fileSecurity.SetAccessRuleProtection( fileSecurity.AreAccessRulesProtected, true ); File.SetAccessControl( destination, fileSecurity ); } else { FileAttributes fileAttributes; fileAttributes = File.GetAttributes( source ); File.SetAttributes( destination, fileAttributes ); } #endif // FEATURE_PAL } // ValidateWriteAccess // // Validate that we can write to the file. This will enforce the ACL's // on the file. Since we do our moving of files to replace, this is // nice to ensure we are not by-passing some security permission // that someone set (although that could bypass this via move themselves) // // Note: 1) This is really just a nice to have, since with directory permissions // they could do the same thing we are doing // // 2) We are depending on the current behavior that if the file is locked // and we can not open it, that we will get an UnauthorizedAccessException // and not the IOException. // private void ValidateWriteAccess( string filename ) { FileStream fs = null; try { // Try to open file for write access fs = new FileStream( filename, FileMode.Open, FileAccess.Write, FileShare.ReadWrite ); } catch ( UnauthorizedAccessException ) { // Access was denied, make sure we throw this throw; } catch ( IOException ) { // Someone else was using the file. Since we did not get // the unauthorizedAccessException we have access to the file } catch ( Exception ) { // Unexpected, so just throw for safety sake throw; } finally { if ( fs != null ) { fs.Close(); } } } // ReplaceFile // // Replace one file with another using MoveFileEx. This will // retry the operation if the file is locked because someone // is reading it // private void ReplaceFile( string Source, string Target ) { bool WriteSucceeded = false; int Duration = 0; WriteSucceeded = AttemptMove( Source, Target ); // The file may be open for read, if it is then // lets try again because maybe they will finish // soon, and we will be able to replace while ( !WriteSucceeded && ( Duration < SAVING_TIMEOUT ) && File.Exists( Target ) && !FileIsWriteLocked( Target ) ) { Thread.Sleep( SAVING_RETRY_INTERVAL ); Duration += SAVING_RETRY_INTERVAL; WriteSucceeded = AttemptMove( Source, Target ); } if ( !WriteSucceeded ) { throw new ConfigurationErrorsException( SR.GetString(SR.Config_write_failed, Target) ); } } // AttemptMove // // Attempt to move a file from one location to another // // Return Values: // TRUE - Move Successful // FALSE - Move Failed private bool AttemptMove( string Source, string Target ) { bool MoveSuccessful = false; if ( IsWinNT ) { // We can only call this when we have kernel32.dll MoveSuccessful = UnsafeNativeMethods.MoveFileEx( Source, Target, UnsafeNativeMethods.MOVEFILE_REPLACE_EXISTING ); } else { try { // VSWhidbey 548017: // File.Move isn't supported on Win9x. We'll use File.Copy // instead. Please note that Source is a temporary file which // will be deleted when _tempFiles is disposed. File.Copy(Source, Target, true); MoveSuccessful = true; } catch { MoveSuccessful = false; } } return MoveSuccessful; } // FileIsWriteLocked // // Is the file write locked or not? // private bool FileIsWriteLocked( string FileName ) { Stream FileStream = null; bool WriteLocked = true; if (!FileUtil.FileExists(FileName, true)) { // It can't be locked if it doesn't exist return false; } try { FileShare fileShare = FileShare.Read; if (IsWinNT) { fileShare |= FileShare.Delete; } // Try to open for shared reading FileStream = new FileStream( FileName, FileMode.Open, FileAccess.Read, fileShare); // If we can open it for shared reading, it is not // write locked WriteLocked = false; } finally { if ( FileStream != null ) { FileStream.Close(); FileStream = null; } } return WriteLocked; } // IsWinNT // // Are we running in WinNT or not? // private bool IsWinNT { get { if ( !_osPlatformDetermined ) { _osPlatform = Environment.OSVersion.Platform; _osPlatformDetermined = true; } return ( _osPlatform == System.PlatformID.Win32NT ); } } } }
// // CTLine.cs: Implements the managed CTLine // // Authors: Mono Team // // Copyright 2010 Novell, Inc // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; namespace MonoMac.CoreText { [Since (3,2)] public enum CTLineTruncation { Start = 0, End = 1, Middle = 2 } public enum CTLineBoundsOptions { ExcludeTypographicLeading = 1 << 0, ExcludeTypographicShifts = 1 << 1, UseHangingPunctuation = 1 << 2, UseGlyphPathBounds = 1 << 3, UseOpticalBounds = 1 << 4 } [Since (3,2)] public class CTLine : INativeObject, IDisposable { internal IntPtr handle; internal CTLine (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw ConstructorError.ArgumentNull (this, "handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } public IntPtr Handle { get { return handle; } } ~CTLine () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region Line Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTLineCreateWithAttributedString (IntPtr @string); public CTLine (NSAttributedString value) { if (value == null) throw ConstructorError.ArgumentNull (this, "value"); handle = CTLineCreateWithAttributedString (value.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTLineCreateTruncatedLine (IntPtr line, double width, CTLineTruncation truncationType, IntPtr truncationToken); public CTLine GetTruncatedLine (double width, CTLineTruncation truncationType, CTLine truncationToken) { var h = CTLineCreateTruncatedLine (handle, width, truncationType, truncationToken == null ? IntPtr.Zero : truncationToken.Handle); if (h == IntPtr.Zero) return null; return new CTLine (h, true); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTLineCreateJustifiedLine (IntPtr line, float justificationFactor, double justificationWidth); public CTLine GetJustifiedLine (float justificationFactor, double justificationWidth) { var h = CTLineCreateJustifiedLine (handle, justificationFactor, justificationWidth); if (h == IntPtr.Zero) return null; return new CTLine (h, true); } #endregion #region Line Access [DllImport (Constants.CoreTextLibrary)] static extern int CTLineGetGlyphCount (IntPtr line); public int GlyphCount { get {return CTLineGetGlyphCount (handle);} } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTLineGetGlyphRuns (IntPtr line); public CTRun[] GetGlyphRuns () { var cfArrayRef = CTLineGetGlyphRuns (handle); if (cfArrayRef == IntPtr.Zero) return new CTRun [0]; return NSArray.ArrayFromHandle (cfArrayRef, v => new CTRun (v, false)); } [DllImport (Constants.CoreTextLibrary)] static extern NSRange CTLineGetStringRange (IntPtr line); public NSRange StringRange { get {return CTLineGetStringRange (handle);} } [DllImport (Constants.CoreTextLibrary)] static extern double CTLineGetPenOffsetForFlush (IntPtr line, float flushFactor, double flushWidth); public double GetPenOffsetForFlush (float flushFactor, double flushWidth) { return CTLineGetPenOffsetForFlush (handle, flushFactor, flushWidth); } [DllImport (Constants.CoreTextLibrary)] static extern void CTLineDraw (IntPtr line, IntPtr context); public void Draw (CGContext context) { if (context == null) throw new ArgumentNullException ("context"); CTLineDraw (handle, context.Handle); } #endregion #region Line Measurement [DllImport (Constants.CoreTextLibrary)] static extern RectangleF CTLineGetImageBounds (IntPtr line, IntPtr context); public RectangleF GetImageBounds (CGContext context) { if (context == null) throw new ArgumentNullException ("context"); return CTLineGetImageBounds (handle, context.Handle); } [DllImport (Constants.CoreTextLibrary)] static extern RectangleF CTLineGetBoundsWithOptions (IntPtr line, CTLineBoundsOptions options); [Since (6,0)] public RectangleF GetBounds (CTLineBoundsOptions options) { return CTLineGetBoundsWithOptions (handle, options); } [DllImport (Constants.CoreTextLibrary)] static extern double CTLineGetTypographicBounds (IntPtr line, out float ascent, out float descent, out float leading); public double GetTypographicBounds (out float ascent, out float descent, out float leading) { return CTLineGetTypographicBounds (handle, out ascent, out descent, out leading); } [DllImport (Constants.CoreTextLibrary)] static extern double CTLineGetTypographicBounds (IntPtr line, IntPtr ascent, IntPtr descent, IntPtr leading); public double GetTypographicBounds () { return CTLineGetTypographicBounds (handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } [DllImport (Constants.CoreTextLibrary)] static extern double CTLineGetTrailingWhitespaceWidth (IntPtr line); public double TrailingWhitespaceWidth { get {return CTLineGetTrailingWhitespaceWidth (handle);} } #endregion #region Line Caret Positioning and Highlighting [DllImport (Constants.CoreTextLibrary)] static extern int CTLineGetStringIndexForPosition (IntPtr line, PointF position); public int GetStringIndexForPosition (PointF position) { return CTLineGetStringIndexForPosition (handle, position); } [DllImport (Constants.CoreTextLibrary)] static extern float CTLineGetOffsetForStringIndex (IntPtr line, int charIndex, out float secondaryOffset); public float GetOffsetForStringIndex (int charIndex, out float secondaryOffset) { return CTLineGetOffsetForStringIndex (handle, charIndex, out secondaryOffset); } [DllImport (Constants.CoreTextLibrary)] static extern float CTLineGetOffsetForStringIndex (IntPtr line, int charIndex, IntPtr secondaryOffset); public float GetOffsetForStringIndex (int charIndex) { return CTLineGetOffsetForStringIndex (handle, charIndex, IntPtr.Zero); } #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.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace System { // Provides Windows-based support for System.Console. internal static class ConsolePal { private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers private static IntPtr InvalidHandleValue => new IntPtr(-1); private static bool IsWindows7() { // Version lies for all apps from the OS kick in starting with Windows 8 (6.2). They can // also be added via appcompat (by the OS or the users) so this can only be used as a hint. Version version = Environment.OSVersion.Version; return version.Major == 6 && version.Minor == 1; } public static Stream OpenStandardInput() { return GetStandardFile(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE, FileAccess.Read); } public static Stream OpenStandardOutput() { return GetStandardFile(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE, FileAccess.Write); } public static Stream OpenStandardError() { return GetStandardFile(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE, FileAccess.Write); } private static IntPtr InputHandle { get { return Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE); } } private static IntPtr OutputHandle { get { return Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE); } } private static IntPtr ErrorHandle { get { return Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE); } } private static Stream GetStandardFile(int handleType, FileAccess access) { IntPtr handle = Interop.Kernel32.GetStdHandle(handleType); // If someone launches a managed process via CreateProcess, stdout, // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE. // Additionally they might use 0 as an invalid handle. We also need to // ensure that if the handle is meant to be writable it actually is. if (handle == IntPtr.Zero || handle == InvalidHandleValue || (access != FileAccess.Read && !ConsoleHandleIsWritable(handle))) { return Stream.Null; } return new WindowsConsoleStream(handle, access, GetUseFileAPIs(handleType)); } // Checks whether stdout or stderr are writable. Do NOT pass // stdin here! The console handles are set to values like 3, 7, // and 11 OR if you've been created via CreateProcess, possibly -1 // or 0. -1 is definitely invalid, while 0 is probably invalid. // Also note each handle can independently be invalid or good. // For Windows apps, the console handles are set to values like 3, 7, // and 11 but are invalid handles - you may not write to them. However, // you can still spawn a Windows app via CreateProcess and read stdout // and stderr. So, we always need to check each handle independently for validity // by trying to write or read to it, unless it is -1. private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle) { // Windows apps may have non-null valid looking handle values for // stdin, stdout and stderr, but they may not be readable or // writable. Verify this by calling WriteFile in the // appropriate modes. This must handle console-less Windows apps. int bytesWritten; byte junkByte = 0x41; int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero); return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure. } public static Encoding InputEncoding { get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleCP()); } } public static void SetConsoleInputEncoding(Encoding enc) { if (enc.CodePage != Encoding.Unicode.CodePage) { if (!Interop.Kernel32.SetConsoleCP(enc.CodePage)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static Encoding OutputEncoding { get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); } } public static void SetConsoleOutputEncoding(Encoding enc) { if (enc.CodePage != Encoding.Unicode.CodePage) { if (!Interop.Kernel32.SetConsoleOutputCP(enc.CodePage)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } private static bool GetUseFileAPIs(int handleType) { switch (handleType) { case Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE: return Console.InputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsInputRedirected; case Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE: return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsOutputRedirected; case Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE: return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsErrorRedirected; default: // This can never happen. Debug.Fail("Unexpected handleType value (" + handleType + ")"); return true; } } /// <summary>Gets whether Console.In is targeting a terminal display.</summary> public static bool IsInputRedirectedCore() { return IsHandleRedirected(InputHandle); } /// <summary>Gets whether Console.Out is targeting a terminal display.</summary> public static bool IsOutputRedirectedCore() { return IsHandleRedirected(OutputHandle); } /// <summary>Gets whether Console.In is targeting a terminal display.</summary> public static bool IsErrorRedirectedCore() { return IsHandleRedirected(ErrorHandle); } private static bool IsHandleRedirected(IntPtr handle) { // If handle is not to a character device, we must be redirected: uint fileType = Interop.Kernel32.GetFileType(handle); if ((fileType & Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) != Interop.Kernel32.FileTypes.FILE_TYPE_CHAR) return true; // We are on a char device if GetConsoleMode succeeds and so we are not redirected. return (!Interop.Kernel32.IsGetConsoleModeCallSuccessful(handle)); } internal static TextReader GetOrCreateReader() { Stream inputStream = OpenStandardInput(); return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ? StreamReader.Null : new StreamReader( stream: inputStream, encoding: new ConsoleEncoding(Console.InputEncoding), detectEncodingFromByteOrderMarks: false, bufferSize: DefaultConsoleBufferSize, leaveOpen: true)); } // Use this for blocking in Console.ReadKey, which needs to protect itself in case multiple threads call it simultaneously. // Use a ReadKey-specific lock though, to allow other fields to be initialized on this type. private static readonly object s_readKeySyncObject = new object(); // ReadLine & Read can't use this because they need to use ReadFile // to be able to handle redirected input. We have to accept that // we will lose repeated keystrokes when someone switches from // calling ReadKey to calling Read or ReadLine. Those methods should // ideally flush this cache as well. private static Interop.InputRecord _cachedInputRecord; // Skip non key events. Generally we want to surface only KeyDown event // and suppress KeyUp event from the same Key press but there are cases // where the assumption of KeyDown-KeyUp pairing for a given key press // is invalid. For example in IME Unicode keyboard input, we often see // only KeyUp until the key is released. private static bool IsKeyDownEvent(Interop.InputRecord ir) { return (ir.eventType == Interop.KEY_EVENT && ir.keyEvent.keyDown != Interop.BOOL.FALSE); } private static bool IsModKey(Interop.InputRecord ir) { // We should also skip over Shift, Control, and Alt, as well as caps lock. // Apparently we don't need to check for 0xA0 through 0xA5, which are keys like // Left Control & Right Control. See the ConsoleKey enum for these values. short keyCode = ir.keyEvent.virtualKeyCode; return ((keyCode >= 0x10 && keyCode <= 0x12) || keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91); } [Flags] internal enum ControlKeyState { RightAltPressed = 0x0001, LeftAltPressed = 0x0002, RightCtrlPressed = 0x0004, LeftCtrlPressed = 0x0008, ShiftPressed = 0x0010, NumLockOn = 0x0020, ScrollLockOn = 0x0040, CapsLockOn = 0x0080, EnhancedKey = 0x0100 } // For tracking Alt+NumPad unicode key sequence. When you press Alt key down // and press a numpad unicode decimal sequence and then release Alt key, the // desired effect is to translate the sequence into one Unicode KeyPress. // We need to keep track of the Alt+NumPad sequence and surface the final // unicode char alone when the Alt key is released. private static bool IsAltKeyDown(Interop.InputRecord ir) { return (((ControlKeyState)ir.keyEvent.controlKeyState) & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; } private const int NumberLockVKCode = 0x90; private const int CapsLockVKCode = 0x14; public static bool NumberLock { get { try { short s = Interop.User32.GetKeyState(NumberLockVKCode); return (s & 1) == 1; } catch (Exception) { // Since we depend on an extension api-set here // it is not guaranteed to work across the board. // In case of exception we simply throw PNSE throw new PlatformNotSupportedException(); } } } public static bool CapsLock { get { try { short s = Interop.User32.GetKeyState(CapsLockVKCode); return (s & 1) == 1; } catch (Exception) { // Since we depend on an extension api-set here // it is not guaranteed to work across the board. // In case of exception we simply throw PNSE throw new PlatformNotSupportedException(); } } } public static bool KeyAvailable { get { if (_cachedInputRecord.eventType == Interop.KEY_EVENT) return true; Interop.InputRecord ir = new Interop.InputRecord(); int numEventsRead = 0; while (true) { bool r = Interop.Kernel32.PeekConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile); throw Win32Marshal.GetExceptionForWin32Error(errorCode, "stdin"); } if (numEventsRead == 0) return false; // Skip non key-down && mod key events. if (!IsKeyDownEvent(ir) || IsModKey(ir)) { r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } else { return true; } } } // get } private const short AltVKCode = 0x12; public static ConsoleKeyInfo ReadKey(bool intercept) { Interop.InputRecord ir; int numEventsRead = -1; bool r; lock (s_readKeySyncObject) { if (_cachedInputRecord.eventType == Interop.KEY_EVENT) { // We had a previous keystroke with repeated characters. ir = _cachedInputRecord; if (_cachedInputRecord.keyEvent.repeatCount == 0) _cachedInputRecord.eventType = -1; else { _cachedInputRecord.keyEvent.repeatCount--; } // We will return one key from this method, so we decrement the // repeatCount here, leaving the cachedInputRecord in the "queue". } else { // We did NOT have a previous keystroke with repeated characters: while (true) { r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); if (!r || numEventsRead == 0) { // This will fail when stdin is redirected from a file or pipe. // We could theoretically call Console.Read here, but I // think we might do some things incorrectly then. throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile); } short keyCode = ir.keyEvent.virtualKeyCode; // First check for non-keyboard events & discard them. Generally we tap into only KeyDown events and ignore the KeyUp events // but it is possible that we are dealing with a Alt+NumPad unicode key sequence, the final unicode char is revealed only when // the Alt key is released (i.e when the sequence is complete). To avoid noise, when the Alt key is down, we should eat up // any intermediate key strokes (from NumPad) that collectively forms the Unicode character. if (!IsKeyDownEvent(ir)) { // REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown. if (keyCode != AltVKCode) continue; } char ch = (char)ir.keyEvent.uChar; // In a Alt+NumPad unicode sequence, when the alt key is released uChar will represent the final unicode character, we need to // surface this. VirtualKeyCode for this event will be Alt from the Alt-Up key event. This is probably not the right code, // especially when we don't expose ConsoleKey.Alt, so this will end up being the hex value (0x12). VK_PACKET comes very // close to being useful and something that we could look into using for this purpose... if (ch == 0) { // Skip mod keys. if (IsModKey(ir)) continue; } // When Alt is down, it is possible that we are in the middle of a Alt+NumPad unicode sequence. // Escape any intermediate NumPad keys whether NumLock is on or not (notepad behavior) ConsoleKey key = (ConsoleKey)keyCode; if (IsAltKeyDown(ir) && ((key >= ConsoleKey.NumPad0 && key <= ConsoleKey.NumPad9) || (key == ConsoleKey.Clear) || (key == ConsoleKey.Insert) || (key >= ConsoleKey.PageUp && key <= ConsoleKey.DownArrow))) { continue; } if (ir.keyEvent.repeatCount > 1) { ir.keyEvent.repeatCount--; _cachedInputRecord = ir; } break; } } // we did NOT have a previous keystroke with repeated characters. } ControlKeyState state = (ControlKeyState)ir.keyEvent.controlKeyState; bool shift = (state & ControlKeyState.ShiftPressed) != 0; bool alt = (state & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0; bool control = (state & (ControlKeyState.LeftCtrlPressed | ControlKeyState.RightCtrlPressed)) != 0; ConsoleKeyInfo info = new ConsoleKeyInfo((char)ir.keyEvent.uChar, (ConsoleKey)ir.keyEvent.virtualKeyCode, shift, alt, control); if (!intercept) Console.Write(ir.keyEvent.uChar); return info; } public static bool TreatControlCAsInput { get { IntPtr handle = InputHandle; if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); int mode = 0; if (!Interop.Kernel32.GetConsoleMode(handle, out mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return (mode & Interop.Kernel32.ENABLE_PROCESSED_INPUT) == 0; } set { IntPtr handle = InputHandle; if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); int mode = 0; Interop.Kernel32.GetConsoleMode(handle, out mode); // failure ignored in full framework if (value) { mode &= ~Interop.Kernel32.ENABLE_PROCESSED_INPUT; } else { mode |= Interop.Kernel32.ENABLE_PROCESSED_INPUT; } if (!Interop.Kernel32.SetConsoleMode(handle, mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } // For ResetColor private static volatile bool _haveReadDefaultColors; private static volatile byte _defaultColors; public static ConsoleColor BackgroundColor { get { bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); return succeeded ? ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.BackgroundMask) : ConsoleColor.Black; // for code that may be used from Windows app w/ no console } set { Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, true); bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console if (!succeeded) return; Debug.Assert(_haveReadDefaultColors, "Setting the background color before we've read the default foreground color!"); short attrs = csbi.wAttributes; attrs &= ~((short)Interop.Kernel32.Color.BackgroundMask); // C#'s bitwise-or sign-extends to 32 bits. attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c)); // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs); } } public static ConsoleColor ForegroundColor { get { bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console return succeeded ? ColorAttributeToConsoleColor((Interop.Kernel32.Color)csbi.wAttributes & Interop.Kernel32.Color.ForegroundMask) : ConsoleColor.Gray; } set { Interop.Kernel32.Color c = ConsoleColorToColorAttribute(value, false); bool succeeded; Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded); // For code that may be used from Windows app w/ no console if (!succeeded) return; Debug.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!"); short attrs = csbi.wAttributes; attrs &= ~((short)Interop.Kernel32.Color.ForegroundMask); // C#'s bitwise-or sign-extends to 32 bits. attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c)); // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, attrs); } } public static void ResetColor() { if (!_haveReadDefaultColors) // avoid the costs of GetBufferInfo if we already know we checked it { bool succeeded; GetBufferInfo(false, out succeeded); if (!succeeded) return; // For code that may be used from Windows app w/ no console Debug.Assert(_haveReadDefaultColors, "Resetting color before we've read the default foreground color!"); } // Ignore errors here - there are some scenarios for running code that wants // to print in colors to the console in a Windows application. Interop.Kernel32.SetConsoleTextAttribute(OutputHandle, (short)(ushort)_defaultColors); } public static int CursorSize { get { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return cci.dwSize; } set { // Value should be a percentage from [1, 100]. if (value < 1 || value > 100) throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_CursorSize); Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); cci.dwSize = value; if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static bool CursorVisible { get { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); return cci.bVisible; } set { Interop.Kernel32.CONSOLE_CURSOR_INFO cci; if (!Interop.Kernel32.GetConsoleCursorInfo(OutputHandle, out cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); cci.bVisible = value; if (!Interop.Kernel32.SetConsoleCursorInfo(OutputHandle, ref cci)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static int CursorLeft { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwCursorPosition.X; } } public static int CursorTop { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwCursorPosition.Y; } } public unsafe static string Title { get { Span<char> initialBuffer = stackalloc char[256]; ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); while (true) { uint result = Interop.Errors.ERROR_SUCCESS; fixed (char* c = &builder.GetPinnableReference()) { result = Interop.Kernel32.GetConsoleTitleW(c, (uint)builder.Capacity); } // The documentation asserts that the console's title is stored in a shared 64KB buffer. // The magic number that used to exist here (24500) is likely related to that. // A full UNICODE_STRING is 32K chars... Debug.Assert(result <= short.MaxValue, "shouldn't be possible to grow beyond UNICODE_STRING size"); if (result == 0) { int error = Marshal.GetLastWin32Error(); switch (error) { case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // Typically this API truncates but there was a bug in RS2 so we'll make an attempt to handle builder.EnsureCapacity(builder.Capacity * 2); continue; case Interop.Errors.ERROR_SUCCESS: // The title is empty. break; default: throw Win32Marshal.GetExceptionForWin32Error(error, string.Empty); } } else if (result >= builder.Capacity - 1 || (IsWindows7() && result >= builder.Capacity / sizeof(char) - 1)) { // Our buffer was full. As this API truncates we need to increase our size and reattempt. // Note that Windows 7 copies count of bytes into the output buffer but returns count of chars // and as such our buffer is only "half" its actual size. // // (If we're Windows 10 with a version lie to 7 this will be inefficient so we'll want to remove // this workaround when we no longer support Windows 7) builder.EnsureCapacity(builder.Capacity * 2); continue; } builder.Length = (int)result; break; } return builder.ToString(); } set { if (!Interop.Kernel32.SetConsoleTitle(value)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static void Beep() { const int BeepFrequencyInHz = 800; const int BeepDurationInMs = 200; Interop.Kernel32.Beep(BeepFrequencyInHz, BeepDurationInMs); } public static void Beep(int frequency, int duration) { const int MinBeepFrequency = 37; const int MaxBeepFrequency = 32767; if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency) throw new ArgumentOutOfRangeException(nameof(frequency), frequency, SR.Format(SR.ArgumentOutOfRange_BeepFrequency, MinBeepFrequency, MaxBeepFrequency)); if (duration <= 0) throw new ArgumentOutOfRangeException(nameof(duration), duration, SR.ArgumentOutOfRange_NeedPosNum); Interop.Kernel32.Beep(frequency, duration); } public static unsafe void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { if (sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White) throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceForeColor)); if (sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White) throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceBackColor)); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.COORD bufferSize = csbi.dwSize; if (sourceLeft < 0 || sourceLeft > bufferSize.X) throw new ArgumentOutOfRangeException(nameof(sourceLeft), sourceLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceTop < 0 || sourceTop > bufferSize.Y) throw new ArgumentOutOfRangeException(nameof(sourceTop), sourceTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft) throw new ArgumentOutOfRangeException(nameof(sourceWidth), sourceWidth, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight) throw new ArgumentOutOfRangeException(nameof(sourceHeight), sourceHeight, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); // Note: if the target range is partially in and partially out // of the buffer, then we let the OS clip it for us. if (targetLeft < 0 || targetLeft > bufferSize.X) throw new ArgumentOutOfRangeException(nameof(targetLeft), targetLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (targetTop < 0 || targetTop > bufferSize.Y) throw new ArgumentOutOfRangeException(nameof(targetTop), targetTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); // If we're not doing any work, bail out now (Windows will return // an error otherwise) if (sourceWidth == 0 || sourceHeight == 0) return; // Read data from the original location, blank it out, then write // it to the new location. This will handle overlapping source and // destination regions correctly. // Read the old data Interop.Kernel32.CHAR_INFO[] data = new Interop.Kernel32.CHAR_INFO[sourceWidth * sourceHeight]; bufferSize.X = (short)sourceWidth; bufferSize.Y = (short)sourceHeight; Interop.Kernel32.COORD bufferCoord = new Interop.Kernel32.COORD(); Interop.Kernel32.SMALL_RECT readRegion = new Interop.Kernel32.SMALL_RECT(); readRegion.Left = (short)sourceLeft; readRegion.Right = (short)(sourceLeft + sourceWidth - 1); readRegion.Top = (short)sourceTop; readRegion.Bottom = (short)(sourceTop + sourceHeight - 1); bool r; fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data) r = Interop.Kernel32.ReadConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // Overwrite old section Interop.Kernel32.COORD writeCoord = new Interop.Kernel32.COORD(); writeCoord.X = (short)sourceLeft; Interop.Kernel32.Color c = ConsoleColorToColorAttribute(sourceBackColor, true); c |= ConsoleColorToColorAttribute(sourceForeColor, false); short attr = (short)c; int numWritten; for (int i = sourceTop; i < sourceTop + sourceHeight; i++) { writeCoord.Y = (short)i; r = Interop.Kernel32.FillConsoleOutputCharacter(OutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten); Debug.Assert(numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!"); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); r = Interop.Kernel32.FillConsoleOutputAttribute(OutputHandle, attr, sourceWidth, writeCoord, out numWritten); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } // Write text to new location Interop.Kernel32.SMALL_RECT writeRegion = new Interop.Kernel32.SMALL_RECT(); writeRegion.Left = (short)targetLeft; writeRegion.Right = (short)(targetLeft + sourceWidth); writeRegion.Top = (short)targetTop; writeRegion.Bottom = (short)(targetTop + sourceHeight); fixed (Interop.Kernel32.CHAR_INFO* pCharInfo = data) Interop.Kernel32.WriteConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion); } public static void Clear() { Interop.Kernel32.COORD coordScreen = new Interop.Kernel32.COORD(); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi; bool success; int conSize; IntPtr hConsole = OutputHandle; if (hConsole == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); // get the number of character cells in the current buffer // Go through my helper method for fetching a screen buffer info // to correctly handle default console colors. csbi = GetBufferInfo(); conSize = csbi.dwSize.X * csbi.dwSize.Y; // fill the entire screen with blanks int numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputCharacter(hConsole, ' ', conSize, coordScreen, out numCellsWritten); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // now set the buffer's attributes accordingly numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputAttribute(hConsole, csbi.wAttributes, conSize, coordScreen, out numCellsWritten); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); // put the cursor at (0, 0) success = Interop.Kernel32.SetConsoleCursorPosition(hConsole, coordScreen); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } public static void SetCursorPosition(int left, int top) { IntPtr hConsole = OutputHandle; Interop.Kernel32.COORD coords = new Interop.Kernel32.COORD(); coords.X = (short)left; coords.Y = (short)top; if (!Interop.Kernel32.SetConsoleCursorPosition(hConsole, coords)) { // Give a nice error message for out of range sizes int errorCode = Marshal.GetLastWin32Error(); Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); if (left >= csbi.dwSize.X) throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); if (top >= csbi.dwSize.Y) throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public static int BufferWidth { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwSize.X; } set { SetBufferSize(value, BufferHeight); } } public static int BufferHeight { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.dwSize.Y; } set { SetBufferSize(BufferWidth, value); } } public static void SetBufferSize(int width, int height) { // Ensure the new size is not smaller than the console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; if (width < srWindow.Right + 1 || width >= short.MaxValue) throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize); if (height < srWindow.Bottom + 1 || height >= short.MaxValue) throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize); Interop.Kernel32.COORD size = new Interop.Kernel32.COORD(); size.X = (short)width; size.Y = (short)height; if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } public static int LargestWindowWidth { get { // Note this varies based on current screen resolution and // current console font. Do not cache this value. Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); return bounds.X; } } public static int LargestWindowHeight { get { // Note this varies based on current screen resolution and // current console font. Do not cache this value. Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); return bounds.Y; } } public static int WindowLeft { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Left; } set { SetWindowPosition(value, WindowTop); } } public static int WindowTop { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Top; } set { SetWindowPosition(WindowLeft, value); } } public static int WindowWidth { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Right - csbi.srWindow.Left + 1; } set { SetWindowSize(value, WindowHeight); } } public static int WindowHeight { get { Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } set { SetWindowSize(WindowWidth, value); } } public static unsafe void SetWindowPosition(int left, int top) { // Get the size of the current console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; // Check for arithmetic underflows & overflows. int newRight = left + srWindow.Right - srWindow.Left + 1; if (left < 0 || newRight > csbi.dwSize.X || newRight < 0) throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleWindowPos); int newBottom = top + srWindow.Bottom - srWindow.Top + 1; if (top < 0 || newBottom > csbi.dwSize.Y || newBottom < 0) throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleWindowPos); // Preserve the size, but move the position. srWindow.Bottom -= (short)(srWindow.Top - top); srWindow.Right -= (short)(srWindow.Left - left); srWindow.Left = (short)left; srWindow.Top = (short)top; bool r = Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } public static unsafe void SetWindowSize(int width, int height) { if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_NeedPosNum); if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_NeedPosNum); // Get the position of the current console window Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(); // If the buffer is smaller than this new window size, resize the // buffer to be large enough. Include window position. bool resizeBuffer = false; Interop.Kernel32.COORD size = new Interop.Kernel32.COORD(); size.X = csbi.dwSize.X; size.Y = csbi.dwSize.Y; if (csbi.dwSize.X < csbi.srWindow.Left + width) { if (csbi.srWindow.Left >= short.MaxValue - width) throw new ArgumentOutOfRangeException(nameof(width), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - width)); size.X = (short)(csbi.srWindow.Left + width); resizeBuffer = true; } if (csbi.dwSize.Y < csbi.srWindow.Top + height) { if (csbi.srWindow.Top >= short.MaxValue - height) throw new ArgumentOutOfRangeException(nameof(height), SR.Format(SR.ArgumentOutOfRange_ConsoleWindowBufferSize, short.MaxValue - height)); size.Y = (short)(csbi.srWindow.Top + height); resizeBuffer = true; } if (resizeBuffer) { if (!Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, size)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } Interop.Kernel32.SMALL_RECT srWindow = csbi.srWindow; // Preserve the position, but change the size. srWindow.Bottom = (short)(srWindow.Top + height - 1); srWindow.Right = (short)(srWindow.Left + width - 1); if (!Interop.Kernel32.SetConsoleWindowInfo(OutputHandle, true, &srWindow)) { int errorCode = Marshal.GetLastWin32Error(); // If we resized the buffer, un-resize it. if (resizeBuffer) { Interop.Kernel32.SetConsoleScreenBufferSize(OutputHandle, csbi.dwSize); } // Try to give a better error message here Interop.Kernel32.COORD bounds = Interop.Kernel32.GetLargestConsoleWindowSize(OutputHandle); if (width > bounds.X) throw new ArgumentOutOfRangeException(nameof(width), width, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.X)); if (height > bounds.Y) throw new ArgumentOutOfRangeException(nameof(height), height, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.Y)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } private static Interop.Kernel32.Color ConsoleColorToColorAttribute(ConsoleColor color, bool isBackground) { if ((((int)color) & ~0xf) != 0) throw new ArgumentException(SR.Arg_InvalidConsoleColor); Interop.Kernel32.Color c = (Interop.Kernel32.Color)color; // Make these background colors instead of foreground if (isBackground) c = (Interop.Kernel32.Color)((int)c << 4); return c; } private static ConsoleColor ColorAttributeToConsoleColor(Interop.Kernel32.Color c) { // Turn background colors into foreground colors. if ((c & Interop.Kernel32.Color.BackgroundMask) != 0) { c = (Interop.Kernel32.Color)(((int)c) >> 4); } return (ConsoleColor)c; } private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo() { bool unused; return GetBufferInfo(true, out unused); } // For apps that don't have a console (like Windows apps), they might // run other code that includes color console output. Allow a mechanism // where that code won't throw an exception for simple errors. private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded) { succeeded = false; IntPtr outputHandle = OutputHandle; if (outputHandle == InvalidHandleValue) { if (throwOnNoConsole) { throw new IOException(SR.IO_NoConsole); } return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO(); } // Note that if stdout is redirected to a file, the console handle may be a file. // First try stdout; if this fails, try stderr and then stdin. Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO csbi; if (!Interop.Kernel32.GetConsoleScreenBufferInfo(outputHandle, out csbi) && !Interop.Kernel32.GetConsoleScreenBufferInfo(ErrorHandle, out csbi) && !Interop.Kernel32.GetConsoleScreenBufferInfo(InputHandle, out csbi)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE && !throwOnNoConsole) return new Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } if (!_haveReadDefaultColors) { // Fetch the default foreground and background color for the ResetColor method. Debug.Assert((int)Interop.Kernel32.Color.ColorMask == 0xff, "Make sure one byte is large enough to store a Console color value!"); _defaultColors = (byte)(csbi.wAttributes & (short)Interop.Kernel32.Color.ColorMask); _haveReadDefaultColors = true; // also used by ResetColor to know when GetBufferInfo has been called successfully } succeeded = true; return csbi; } private sealed class WindowsConsoleStream : ConsoleStream { // We know that if we are using console APIs rather than file APIs, then the encoding // is Encoding.Unicode implying 2 bytes per character: const int BytesPerWChar = 2; private readonly bool _isPipe; // When reading from pipes, we need to properly handle EOF cases. private IntPtr _handle; private readonly bool _useFileAPIs; internal WindowsConsoleStream(IntPtr handle, FileAccess access, bool useFileAPIs) : base(access) { Debug.Assert(handle != IntPtr.Zero && handle != InvalidHandleValue, "ConsoleStream expects a valid handle!"); _handle = handle; _isPipe = Interop.Kernel32.GetFileType(handle) == Interop.Kernel32.FileTypes.FILE_TYPE_PIPE; _useFileAPIs = useFileAPIs; } protected override void Dispose(bool disposing) { // We're probably better off not closing the OS handle here. First, // we allow a program to get multiple instances of ConsoleStreams // around the same OS handle, so closing one handle would invalidate // them all. Additionally, we want a second AppDomain to be able to // write to stdout if a second AppDomain quits. _handle = IntPtr.Zero; base.Dispose(disposing); } public override int Read(byte[] buffer, int offset, int count) { ValidateRead(buffer, offset, count); int bytesRead; int errCode = ReadFileNative(_handle, buffer, offset, count, _isPipe, out bytesRead, _useFileAPIs); if (Interop.Errors.ERROR_SUCCESS != errCode) throw Win32Marshal.GetExceptionForWin32Error(errCode); return bytesRead; } public override void Write(byte[] buffer, int offset, int count) { ValidateWrite(buffer, offset, count); int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs); if (Interop.Errors.ERROR_SUCCESS != errCode) throw Win32Marshal.GetExceptionForWin32Error(errCode); } public override void Flush() { if (_handle == IntPtr.Zero) throw Error.GetFileNotOpen(); base.Flush(); } // P/Invoke wrappers for writing to and from a file, nearly identical // to the ones on FileStream. These are duplicated to save startup/hello // world working set and to avoid requiring a reference to the // System.IO.FileSystem contract. private static unsafe int ReadFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool isPipe, out int bytesRead, bool useFileAPIs) { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); Debug.Assert(bytes != null, "bytes != null"); // Don't corrupt memory when multiple threads are erroneously writing // to this stream simultaneously. if (bytes.Length - offset < count) throw new IndexOutOfRangeException(SR.IndexOutOfRange_IORaceCondition); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) { bytesRead = 0; return Interop.Errors.ERROR_SUCCESS; } bool readSuccess; fixed (byte* p = &bytes[0]) { if (useFileAPIs) { readSuccess = (0 != Interop.Kernel32.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero)); } else { // If the code page could be Unicode, we should use ReadConsole instead, e.g. int charsRead; readSuccess = Interop.Kernel32.ReadConsole(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero); bytesRead = charsRead * BytesPerWChar; } } if (readSuccess) return Interop.Errors.ERROR_SUCCESS; // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.) int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE) return Interop.Errors.ERROR_SUCCESS; return errorCode; } private static unsafe int WriteFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool useFileAPIs) { Debug.Assert(offset >= 0, "offset >= 0"); Debug.Assert(count >= 0, "count >= 0"); Debug.Assert(bytes != null, "bytes != null"); Debug.Assert(bytes.Length >= offset + count, "bytes.Length >= offset + count"); // You can't use the fixed statement on an array of length 0. if (bytes.Length == 0) return Interop.Errors.ERROR_SUCCESS; bool writeSuccess; fixed (byte* p = &bytes[0]) { if (useFileAPIs) { int numBytesWritten; writeSuccess = (0 != Interop.Kernel32.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero)); // In some cases we have seen numBytesWritten returned that is twice count; // so we aren't asserting the value of it. See corefx #24508 } else { // If the code page could be Unicode, we should use ReadConsole instead, e.g. // Note that WriteConsoleW has a max limit on num of chars to write (64K) // [https://docs.microsoft.com/en-us/windows/console/writeconsole] // However, we do not need to worry about that because the StreamWriter in Console has // a much shorter buffer size anyway. int charsWritten; writeSuccess = Interop.Kernel32.WriteConsole(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero); Debug.Assert(!writeSuccess || count / BytesPerWChar == charsWritten); } } if (writeSuccess) return Interop.Errors.ERROR_SUCCESS; // For pipes that are closing or broken, just stop. // (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing; // ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is not an error, but EOF.) int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE) return Interop.Errors.ERROR_SUCCESS; return errorCode; } } internal sealed class ControlCHandlerRegistrar { private bool _handlerRegistered; private Interop.Kernel32.ConsoleCtrlHandlerRoutine _handler; internal ControlCHandlerRegistrar() { _handler = new Interop.Kernel32.ConsoleCtrlHandlerRoutine(BreakEvent); } internal void Register() { Debug.Assert(!_handlerRegistered); bool r = Interop.Kernel32.SetConsoleCtrlHandler(_handler, true); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } _handlerRegistered = true; } internal void Unregister() { Debug.Assert(_handlerRegistered); bool r = Interop.Kernel32.SetConsoleCtrlHandler(_handler, false); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } _handlerRegistered = false; } private static bool BreakEvent(int controlType) { if (controlType != Interop.Kernel32.CTRL_C_EVENT && controlType != Interop.Kernel32.CTRL_BREAK_EVENT) { return false; } return Console.HandleBreakEvent(controlType == Interop.Kernel32.CTRL_C_EVENT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak); } } } }
using Facebook; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public sealed class FB : ScriptableObject { public static InitDelegate OnInitComplete; public static HideUnityDelegate OnHideUnity; private static IFacebook facebook; private static string authResponse; private static bool isInitCalled = false; private static string appId; private static bool cookie; private static bool logging; private static bool status; private static bool xfbml; private static bool frictionlessRequests; static IFacebook FacebookImpl { get { if (facebook == null) { throw new NullReferenceException("Facebook object is not yet loaded. Did you call FB.Init()?"); } return facebook; } } public static string AppId { get { // appId might be different from FBSettings.AppId // if using the programmatic version of FB.Init() return appId; } } public static string UserId { get { return (facebook != null) ? facebook.UserId : ""; } } public static string AccessToken { get { return (facebook != null) ? facebook.AccessToken : ""; } } public static DateTime AccessTokenExpiresAt { get { return (facebook != null) ? facebook.AccessTokenExpiresAt : DateTime.MinValue; } } public static bool IsLoggedIn { get { return (facebook != null) && facebook.IsLoggedIn; } } #region Init /** * This is the preferred way to call FB.Init(). It will take the facebook app id specified in your * "Facebook" => "Edit Settings" menu when it is called. * * onInitComplete - Delegate is called when FB.Init() finished initializing everything. * By passing in a delegate you can find out when you can safely call the other methods. */ public static void Init(InitDelegate onInitComplete, HideUnityDelegate onHideUnity = null, string authResponse = null) { Init( onInitComplete, FBSettings.AppId, FBSettings.Cookie, FBSettings.Logging, FBSettings.Status, FBSettings.Xfbml, FBSettings.FrictionlessRequests, onHideUnity, authResponse); } /** * If you need a more programmatic way to set the facebook app id and other setting call this function. * Useful for a build pipeline that requires no human input. */ public static void Init( InitDelegate onInitComplete, string appId, bool cookie = true, bool logging = true, bool status = true, bool xfbml = false, bool frictionlessRequests = true, HideUnityDelegate onHideUnity = null, string authResponse = null) { FB.appId = appId; FB.cookie = cookie; FB.logging = logging; FB.status = status; FB.xfbml = xfbml; FB.frictionlessRequests = frictionlessRequests; FB.authResponse = authResponse; FB.OnInitComplete = onInitComplete; FB.OnHideUnity = onHideUnity; if (!isInitCalled) { var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(typeof (IFacebook)); if (versionInfo == null) { FbDebug.Warn("Cannot find Facebook SDK Version"); } else { FbDebug.Info(String.Format("Using SDK {0}, Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion)); } #if UNITY_EDITOR FBComponentFactory.GetComponent<EditorFacebookLoader>(); #elif UNITY_WEBPLAYER FBComponentFactory.GetComponent<CanvasFacebookLoader>(); #elif UNITY_IOS FBComponentFactory.GetComponent<IOSFacebookLoader>(); #elif UNITY_ANDROID FBComponentFactory.GetComponent<AndroidFacebookLoader>(); #else throw new NotImplementedException("Facebook API does not yet support this platform"); #endif isInitCalled = true; return; } FbDebug.Warn("FB.Init() has already been called. You only need to call this once and only once."); // Init again if possible just in case something bad actually happened. if (FacebookImpl != null) { OnDllLoaded(); } } private static void OnDllLoaded() { var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(FacebookImpl.GetType()); if (versionInfo != null) { FbDebug.Log(string.Format("Finished loading Facebook dll. Version {0} Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion)); } FacebookImpl.Init( OnInitComplete, appId, cookie, logging, status, xfbml, FBSettings.ChannelUrl, authResponse, frictionlessRequests, OnHideUnity ); } #endregion public static void Login(string scope = "", FacebookDelegate callback = null) { FacebookImpl.Login(scope, callback); } public static void Logout() { FacebookImpl.Logout(); } public static void AppRequest( string message, OGActionType actionType, string objectId, string[] to, string data = "", string title = "", FacebookDelegate callback = null) { FacebookImpl.AppRequest(message, actionType, objectId, to, null, null, null, data, title, callback); } public static void AppRequest( string message, OGActionType actionType, string objectId, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null) { FacebookImpl.AppRequest(message, actionType, objectId, null, filters, excludeIds, maxRecipients, data, title, callback); } public static void AppRequest( string message, string[] to = null, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null) { FacebookImpl.AppRequest(message, null, null, to, filters, excludeIds, maxRecipients, data, title, callback); } public static void Feed( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { FacebookImpl.FeedRequest(toId, link, linkName, linkCaption, linkDescription, picture, mediaSource, actionName, actionLink, reference, properties, callback); } public static void API(string query, HttpMethod method, FacebookDelegate callback = null, Dictionary<string, string> formData = null) { FacebookImpl.API(query, method, formData, callback); } public static void API(string query, HttpMethod method, FacebookDelegate callback, WWWForm formData) { FacebookImpl.API(query, method, formData, callback); } public static void PublishInstall(FacebookDelegate callback = null) { FacebookImpl.PublishInstall(AppId, callback); } public static void GetDeepLink(FacebookDelegate callback) { FacebookImpl.GetDeepLink(callback); } #region App Events public sealed class AppEvents { // If the player has set the limitEventUsage flag to YES, your app will continue // to send this data to Facebook, but Facebook will not use the data to serve // targeted ads. Facebook may continue to use the information for other purposes, // including frequency capping, conversion events, estimating the number of unique // users, security and fraud detection, and debugging. public static bool LimitEventUsage { get { return (facebook != null) && facebook.LimitEventUsage; } set { facebook.LimitEventUsage = value; } } public static void LogEvent( string logEvent, float? valueToSum = null, Dictionary<string, object> parameters = null) { FacebookImpl.AppEventsLogEvent(logEvent, valueToSum, parameters); } public static void LogPurchase( float logPurchase, string currency = "USD", Dictionary<string, object> parameters = null) { FacebookImpl.AppEventsLogPurchase(logPurchase, currency, parameters); } } #endregion #region Canvas-Only Implemented Methods public sealed class Canvas { public static void Pay( string product, string action = "purchaseitem", int quantity = 1, int? quantityMin = null, int? quantityMax = null, string requestId = null, string pricepointId = null, string testCurrency = null, FacebookDelegate callback = null) { FacebookImpl.Pay(product, action, quantity, quantityMin, quantityMax, requestId, pricepointId, testCurrency, callback); } public static void SetResolution(int width, int height, bool fullscreen, int preferredRefreshRate = 0, params FBScreen.Layout[] layoutParams) { FBScreen.SetResolution(width, height, fullscreen, preferredRefreshRate, layoutParams); } public static void SetAspectRatio(int width, int height, params FBScreen.Layout[] layoutParams) { FBScreen.SetAspectRatio(width, height, layoutParams); } } #endregion #region Android-Only Implemented Methods public sealed class Android { public static string KeyHash { get { var androidFacebook = facebook as AndroidFacebook; return (androidFacebook != null) ? androidFacebook.KeyHash : ""; } } } #endregion #region Facebook Loader Class public abstract class RemoteFacebookLoader : MonoBehaviour { public delegate void LoadedDllCallback(IFacebook fb); private const string facebookNamespace = "Facebook."; private const int maxRetryLoadCount = 3; private static int retryLoadCount = 0; public static IEnumerator LoadFacebookClass(string className, LoadedDllCallback callback) { var url = string.Format(IntegratedPluginCanvasLocation.DllUrl, className); var www = new WWW(url); FbDebug.Log("loading dll: " + url); yield return www; if (www.error != null) { FbDebug.Error(www.error); if (retryLoadCount < maxRetryLoadCount) { ++retryLoadCount; #if UNITY_WEBPLAYER FBComponentFactory.AddComponent<CanvasFacebookLoader>(); #endif } www.Dispose(); yield break; } #if !UNITY_WINRT #if UNITY_4_5 var authTokenWww = new WWW(IntegratedPluginCanvasLocation.KeyUrl); yield return authTokenWww; if (authTokenWww.error != null) { FbDebug.Error("Cannot load from " + IntegratedPluginCanvasLocation.KeyUrl + ": " + authTokenWww.error); authTokenWww.Dispose(); yield break; } var assembly = Security.LoadAndVerifyAssembly(www.bytes, authTokenWww.text); #else var assembly = Security.LoadAndVerifyAssembly(www.bytes); #endif if (assembly == null) { FbDebug.Error("Could not securely load assembly from " + url); www.Dispose(); yield break; } var facebookClass = assembly.GetType(facebookNamespace + className); if (facebookClass == null) { FbDebug.Error(className + " not found in assembly!"); www.Dispose(); yield break; } // load the Facebook component into the gameobject // using the "as" cast so it'll null if it fails to cast, instead of exception var fb = typeof(FBComponentFactory) .GetMethod("GetComponent") .MakeGenericMethod(facebookClass) .Invoke(null, new object[] { IfNotExist.AddNew }) as IFacebook; if (fb == null) { FbDebug.Error(className + " couldn't be created."); www.Dispose(); yield break; } callback(fb); #endif www.Dispose(); } protected abstract string className { get; } IEnumerator Start() { var loader = LoadFacebookClass(className, OnDllLoaded); while (loader.MoveNext()) { yield return loader.Current; } Destroy(this); } private void OnDllLoaded(IFacebook fb) { FB.facebook = fb; FB.OnDllLoaded(); } } public abstract class CompiledFacebookLoader : MonoBehaviour { protected abstract IFacebook fb { get; } void Start() { FB.facebook = fb; FB.OnDllLoaded(); Destroy(this); } } #endregion }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Input.StateChanges; using osu.Framework.Logging; using osu.Framework.Testing; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Graphics.Sprites; using osu.Game.Online.API; using osu.Game.Online.Spectator; using osu.Game.Replays; using osu.Game.Replays.Legacy; using osu.Game.Rulesets; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Replays.Types; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osu.Game.Screens.Play; using osu.Game.Tests.Visual.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSpectatorPlayback : OsuManualInputManagerTestScene { protected override bool UseOnlineAPI => true; private TestRulesetInputManager playbackManager; private TestRulesetInputManager recordingManager; private Replay replay; private readonly IBindableList<int> users = new BindableList<int>(); private TestReplayRecorder recorder; private readonly ManualClock manualClock = new ManualClock(); private OsuSpriteText latencyDisplay; private TestFramedReplayInputHandler replayHandler; [Resolved] private IAPIProvider api { get; set; } [Resolved] private SpectatorClient spectatorClient { get; set; } [Cached] private GameplayBeatmap gameplayBeatmap = new GameplayBeatmap(new Beatmap()); [SetUp] public void SetUp() => Schedule(() => { replay = new Replay(); users.BindTo(spectatorClient.PlayingUsers); users.BindCollectionChanged((obj, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Add: Debug.Assert(args.NewItems != null); foreach (int user in args.NewItems) { if (user == api.LocalUser.Value.Id) spectatorClient.WatchUser(user); } break; case NotifyCollectionChangedAction.Remove: Debug.Assert(args.OldItems != null); foreach (int user in args.OldItems) { if (user == api.LocalUser.Value.Id) spectatorClient.StopWatchingUser(user); } break; } }, true); spectatorClient.OnNewFrames += onNewFrames; Add(new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { recordingManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique) { Recorder = recorder = new TestReplayRecorder { ScreenSpaceToGamefield = pos => recordingManager.ToLocalSpace(pos), }, Child = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.Brown, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Text = "Sending", Scale = new Vector2(3), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new TestInputConsumer() } }, } }, new Drawable[] { playbackManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique) { Clock = new FramedClock(manualClock), ReplayInputHandler = replayHandler = new TestFramedReplayInputHandler(replay) { GamefieldToScreenSpace = pos => playbackManager.ToScreenSpace(pos), }, Child = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.DarkBlue, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Text = "Receiving", Scale = new Vector2(3), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new TestInputConsumer() } }, } } } }); Add(latencyDisplay = new OsuSpriteText()); }); private void onNewFrames(int userId, FrameDataBundle frames) { Logger.Log($"Received {frames.Frames.Count()} new frames ({string.Join(',', frames.Frames.Select(f => ((int)f.Time).ToString()))})"); foreach (var legacyFrame in frames.Frames) { var frame = new TestReplayFrame(); frame.FromLegacy(legacyFrame, null, null); replay.Frames.Add(frame); } } [Test] public void TestBasic() { } private double latency = SpectatorClient.TIME_BETWEEN_SENDS; protected override void Update() { base.Update(); if (latencyDisplay == null) return; // propagate initial time value if (manualClock.CurrentTime == 0) { manualClock.CurrentTime = Time.Current; return; } if (!replayHandler.HasFrames) return; var lastFrame = replay.Frames.LastOrDefault(); // this isn't perfect as we basically can't be aware of the rate-of-send here (the streamer is not sending data when not being moved). // in gameplay playback, the case where NextFrame is null would pause gameplay and handle this correctly; it's strictly a test limitation / best effort implementation. if (lastFrame != null) latency = Math.Max(latency, Time.Current - lastFrame.Time); latencyDisplay.Text = $"latency: {latency:N1}"; double proposedTime = Time.Current - latency + Time.Elapsed; // this will either advance by one or zero frames. double? time = replayHandler.SetFrameFromTime(proposedTime); if (time == null) return; manualClock.CurrentTime = time.Value; } [TearDownSteps] public void TearDown() { AddStep("stop recorder", () => { recorder.Expire(); spectatorClient.OnNewFrames -= onNewFrames; }); } public class TestFramedReplayInputHandler : FramedReplayInputHandler<TestReplayFrame> { public TestFramedReplayInputHandler(Replay replay) : base(replay) { } public override void CollectPendingInputs(List<IInput> inputs) { inputs.Add(new MousePositionAbsoluteInput { Position = GamefieldToScreenSpace(CurrentFrame?.Position ?? Vector2.Zero) }); inputs.Add(new ReplayState<TestAction> { PressedActions = CurrentFrame?.Actions ?? new List<TestAction>() }); } } public class TestInputConsumer : CompositeDrawable, IKeyBindingHandler<TestAction> { public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parent.ReceivePositionalInputAt(screenSpacePos); private readonly Box box; public TestInputConsumer() { Size = new Vector2(30); Origin = Anchor.Centre; InternalChildren = new Drawable[] { box = new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, }; } protected override bool OnMouseMove(MouseMoveEvent e) { Position = e.MousePosition; return base.OnMouseMove(e); } public bool OnPressed(TestAction action) { box.Colour = Color4.White; return true; } public void OnReleased(TestAction action) { box.Colour = Color4.Black; } } public class TestRulesetInputManager : RulesetInputManager<TestAction> { public TestRulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) : base(ruleset, variant, unique) { } protected override KeyBindingContainer<TestAction> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) => new TestKeyBindingContainer(); internal class TestKeyBindingContainer : KeyBindingContainer<TestAction> { public override IEnumerable<IKeyBinding> DefaultKeyBindings => new[] { new KeyBinding(InputKey.MouseLeft, TestAction.Down), }; } } public class TestReplayFrame : ReplayFrame, IConvertibleReplayFrame { public Vector2 Position; public List<TestAction> Actions = new List<TestAction>(); public TestReplayFrame(double time, Vector2 position, params TestAction[] actions) : base(time) { Position = position; Actions.AddRange(actions); } public TestReplayFrame() { } public void FromLegacy(LegacyReplayFrame currentFrame, IBeatmap beatmap, ReplayFrame lastFrame = null) { Position = currentFrame.Position; Time = currentFrame.Time; if (currentFrame.MouseLeft) Actions.Add(TestAction.Down); } public LegacyReplayFrame ToLegacy(IBeatmap beatmap) { ReplayButtonState state = ReplayButtonState.None; if (Actions.Contains(TestAction.Down)) state |= ReplayButtonState.Left1; return new LegacyReplayFrame(Time, Position.X, Position.Y, state); } } public enum TestAction { Down, } internal class TestReplayRecorder : ReplayRecorder<TestAction> { public TestReplayRecorder() : base(new Score()) { } protected override ReplayFrame HandleFrame(Vector2 mousePosition, List<TestAction> actions, ReplayFrame previousFrame) { return new TestReplayFrame(Time.Current, mousePosition, actions.ToArray()); } } } }
// 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. /*============================================================================= ** ** Class: Stack ** ** Purpose: Represents a simple last-in-first-out (LIFO) ** non-generic collection of objects. ** ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))] [DebuggerDisplay("Count = {Count}")] public class Stack : ICollection { private Object[] _array; // Storage for stack elements [ContractPublicPropertyName("Count")] private int _size; // Number of items in the stack. private int _version; // Used to keep enumerator in sync w/ collection. private Object _syncRoot; private const int _defaultCapacity = 10; public Stack() { _array = new Object[_defaultCapacity]; _size = 0; _version = 0; } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. _array = new Object[initialCapacity]; _size = 0; _version = 0; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // public Stack(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException(nameof(col)); Contract.EndContractBlock(); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Push(en.Current); } public virtual int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the Stack. public virtual void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } public virtual Object Clone() { Contract.Ensures(Contract.Result<Object>() != null); Stack s = new Stack(_size); s._size = _size; Array.Copy(_array, 0, s._array, 0, _size); s._version = _version; return s; } public virtual bool Contains(Object obj) { int count = _size; while (count-- > 0) { if (obj == null) { if (_array[count] == null) return true; } else if (_array[count] != null && _array[count].Equals(obj)) { return true; } } return false; } // Copies the stack into an array. public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); int i = 0; object[] objArray = array as object[]; if (objArray != null) { while (i < _size) { objArray[i + index] = _array[_size - i - 1]; i++; } } else { while (i < _size) { array.SetValue(_array[_size - i - 1], i + index); i++; } } } // Returns an IEnumerator for this Stack. public virtual IEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator>() != null); return new StackEnumerator(this); } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public virtual Object Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); Contract.EndContractBlock(); return _array[_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public virtual Object Pop() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); //Contract.Ensures(Count == Contract.OldValue(Count) - 1); Contract.EndContractBlock(); _version++; Object obj = _array[--_size]; _array[_size] = null; // Free memory quicker. return obj; } // Pushes an item to the top of the stack. // public virtual void Push(Object obj) { //Contract.Ensures(Count == Contract.OldValue(Count) + 1); if (_size == _array.Length) { Object[] newArray = new Object[2 * _array.Length]; Array.Copy(_array, 0, newArray, 0, _size); _array = newArray; } _array[_size++] = obj; _version++; } // Returns a synchronized Stack. // public static Stack Synchronized(Stack stack) { if (stack == null) throw new ArgumentNullException(nameof(stack)); Contract.Ensures(Contract.Result<Stack>() != null); Contract.EndContractBlock(); return new SyncStack(stack); } // Copies the Stack to an array, in the same order Pop would return the items. public virtual Object[] ToArray() { Contract.Ensures(Contract.Result<Object[]>() != null); if (_size == 0) return Array.Empty<Object>(); Object[] objArray = new Object[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } private class SyncStack : Stack { private Stack _s; private Object _root; internal SyncStack(Stack stack) { _s = stack; _root = stack.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _s.Count; } } } public override bool Contains(Object obj) { lock (_root) { return _s.Contains(obj); } } public override Object Clone() { lock (_root) { return new SyncStack((Stack)_s.Clone()); } } public override void Clear() { lock (_root) { _s.Clear(); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _s.CopyTo(array, arrayIndex); } } public override void Push(Object value) { lock (_root) { _s.Push(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Pop() { lock (_root) { return _s.Pop(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _s.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition public override Object Peek() { lock (_root) { return _s.Peek(); } } public override Object[] ToArray() { lock (_root) { return _s.ToArray(); } } } private class StackEnumerator : IEnumerator { private Stack _stack; private int _index; private int _version; private Object _currentElement; internal StackEnumerator(Stack stack) { _stack = stack; _version = _stack._version; _index = -2; _currentElement = null; } public virtual bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = null; return retval; } public virtual Object Current { get { if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _currentElement; } } public virtual void Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = null; } } internal class StackDebugView { private Stack _stack; public StackDebugView(Stack stack) { if (stack == null) throw new ArgumentNullException(nameof(stack)); Contract.EndContractBlock(); _stack = stack; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Object[] Items { get { return _stack.ToArray(); } } } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Concurrency; namespace Orleans.Streams { [Serializable] [Immutable] internal class StreamImpl<T> : IStreamIdentity, IAsyncStream<T>, IStreamControl, ISerializable { private readonly StreamId streamId; private readonly bool isRewindable; [NonSerialized] private IInternalStreamProvider provider; [NonSerialized] private volatile IAsyncBatchObserver<T> producerInterface; [NonSerialized] private IInternalAsyncObservable<T> consumerInterface; [NonSerialized] private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo. internal StreamId StreamId { get { return streamId; } } public bool IsRewindable { get { return isRewindable; } } public Guid Guid { get { return streamId.Guid; } } public string Namespace { get { return streamId.Namespace; } } public string ProviderName { get { return streamId.ProviderName; } } // IMPORTANT: This constructor needs to be public for Json deserialization to work. public StreamImpl() { initLock = new object(); } internal StreamImpl(StreamId streamId, IInternalStreamProvider provider, bool isRewindable) { if (null == streamId) throw new ArgumentNullException("streamId"); if (null == provider) throw new ArgumentNullException("provider"); this.streamId = streamId; this.provider = provider; producerInterface = null; consumerInterface = null; initLock = new object(); this.isRewindable = isRewindable; } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer) { return GetConsumerInterface().SubscribeAsync(observer, null); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { return GetConsumerInterface().SubscribeAsync(observer, token, filterFunc, filterData); } public async Task Cleanup() { // Cleanup producers if (producerInterface != null) { var producer = producerInterface as IStreamControl; if (producer != null) await producer.Cleanup(); producerInterface = null; } } public Task OnNextAsync(T item, StreamSequenceToken token = null) { return GetProducerInterface().OnNextAsync(item, token); } public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token = null) { return GetProducerInterface().OnNextBatchAsync(batch, token); } public Task OnCompletedAsync() { return GetProducerInterface().OnCompletedAsync(); } public Task OnErrorAsync(Exception ex) { return GetProducerInterface().OnErrorAsync(ex); } internal Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, StreamSequenceToken token) { return GetConsumerInterface().ResumeAsync(handle, observer, token); } public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles() { return GetConsumerInterface().GetAllSubscriptions(); } internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle) { return GetConsumerInterface().UnsubscribeAsync(handle); } internal IAsyncBatchObserver<T> GetProducerInterface() { if (producerInterface != null) return producerInterface; lock (initLock) { if (producerInterface != null) return producerInterface; if (provider == null) provider = GetStreamProvider(); producerInterface = provider.GetProducerInterface<T>(this); } return producerInterface; } internal IInternalAsyncObservable<T> GetConsumerInterface() { if (consumerInterface == null) { lock (initLock) { if (consumerInterface == null) { if (provider == null) provider = GetStreamProvider(); consumerInterface = provider.GetConsumerInterface<T>(this); } } } return consumerInterface; } private IInternalStreamProvider GetStreamProvider() { return RuntimeClient.Current.CurrentStreamProviderManager.GetProvider(streamId.ProviderName) as IInternalStreamProvider; } #region IComparable<IAsyncStream<T>> Members public int CompareTo(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o == null ? 1 : streamId.CompareTo(o.streamId); } #endregion #region IEquatable<IAsyncStream<T>> Members public virtual bool Equals(IAsyncStream<T> other) { var o = other as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } #endregion public override bool Equals(object obj) { var o = obj as StreamImpl<T>; return o != null && streamId.Equals(o.streamId); } public override int GetHashCode() { return streamId.GetHashCode(); } public override string ToString() { return streamId.ToString(); } #region ISerializable Members public void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("StreamId", streamId, typeof(StreamId)); info.AddValue("IsRewindable", isRewindable, typeof(bool)); } // The special constructor is used to deserialize values. protected StreamImpl(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. streamId = (StreamId)info.GetValue("StreamId", typeof(StreamId)); isRewindable = info.GetBoolean("IsRewindable"); initLock = new object(); } #endregion } }