context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualNetworkPeeringsOperations operations. /// </summary> public partial interface IVirtualNetworkPeeringsOperations { /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified virtual network peering. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network peering. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the virtual network peering. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a peering in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='virtualNetworkPeeringName'> /// The name of the peering. /// </param> /// <param name='virtualNetworkPeeringParameters'> /// Parameters supplied to the create or update virtual network peering /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string virtualNetworkPeeringName, VirtualNetworkPeering virtualNetworkPeeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all virtual network peerings in a virtual network. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetworkPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// namespace CallButler.Manager.Controls { partial class GreetingControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { this.StopSounds(); components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GreetingControl)); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.wzdGreeting = new global::Controls.Wizard.Wizard(); this.wizardPage1 = new global::Controls.Wizard.WizardPage(); this.smoothLabel2 = new global::Controls.SmoothLabel(); this.txtCallTo = new System.Windows.Forms.TextBox(); this.smoothLabel1 = new global::Controls.SmoothLabel(); this.pgTextGreeting = new global::Controls.Wizard.WizardPage(); this.speechControl = new WOSI.Utilities.Sound.SpeechControl(); this.panel1 = new System.Windows.Forms.Panel(); this.btnVoices = new global::Controls.LinkButton(); this.label2 = new System.Windows.Forms.Label(); this.pgRecordedGreeting = new global::Controls.Wizard.WizardPage(); this.recordingControl = new WOSI.Utilities.Sound.RecordingControl(); this.gradientPanel1 = new global::Controls.GradientPanel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.mnuGreetingType = new System.Windows.Forms.ToolStripDropDownButton(); this.mnuRecord = new System.Windows.Forms.ToolStripMenuItem(); this.mnuCall = new System.Windows.Forms.ToolStripMenuItem(); this.mnuSpeak = new System.Windows.Forms.ToolStripMenuItem(); this.gradientPanel2 = new global::Controls.GradientPanel(); this.btnPlaceCall = new System.Windows.Forms.Button(); this.wzdGreeting.SuspendLayout(); this.wizardPage1.SuspendLayout(); this.pgTextGreeting.SuspendLayout(); this.panel1.SuspendLayout(); this.pgRecordedGreeting.SuspendLayout(); this.gradientPanel1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.gradientPanel2.SuspendLayout(); this.SuspendLayout(); // // openFileDialog // resources.ApplyResources(this.openFileDialog, "openFileDialog"); // // wzdGreeting // this.wzdGreeting.AlwaysShowFinishButton = false; this.wzdGreeting.BackColor = System.Drawing.Color.Transparent; this.wzdGreeting.CloseOnCancel = false; this.wzdGreeting.CloseOnFinish = false; this.wzdGreeting.Controls.Add(this.wizardPage1); this.wzdGreeting.Controls.Add(this.pgTextGreeting); this.wzdGreeting.Controls.Add(this.pgRecordedGreeting); this.wzdGreeting.DisplayButtons = false; resources.ApplyResources(this.wzdGreeting, "wzdGreeting"); this.wzdGreeting.Name = "wzdGreeting"; this.wzdGreeting.PageIndex = 2; this.wzdGreeting.Pages.AddRange(new global::Controls.Wizard.WizardPage[] { this.pgRecordedGreeting, this.pgTextGreeting, this.wizardPage1}); this.wzdGreeting.ShowTabs = false; this.wzdGreeting.TabBackColor = System.Drawing.Color.WhiteSmoke; this.wzdGreeting.TabBackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile; this.wzdGreeting.TabDividerLineType = global::Controls.Wizard.WizardTabDividerLineType.SingleLine; // // wizardPage1 // this.wizardPage1.Controls.Add(this.btnPlaceCall); this.wizardPage1.Controls.Add(this.smoothLabel2); this.wizardPage1.Controls.Add(this.txtCallTo); this.wizardPage1.Controls.Add(this.smoothLabel1); resources.ApplyResources(this.wizardPage1, "wizardPage1"); this.wizardPage1.IsFinishPage = false; this.wizardPage1.Name = "wizardPage1"; this.wizardPage1.TabLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); // // smoothLabel2 // this.smoothLabel2.AntiAliasText = false; resources.ApplyResources(this.smoothLabel2, "smoothLabel2"); this.smoothLabel2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.smoothLabel2.Name = "smoothLabel2"; // // txtCallTo // resources.ApplyResources(this.txtCallTo, "txtCallTo"); this.txtCallTo.Name = "txtCallTo"; // // smoothLabel1 // this.smoothLabel1.AntiAliasText = false; resources.ApplyResources(this.smoothLabel1, "smoothLabel1"); this.smoothLabel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.smoothLabel1.Name = "smoothLabel1"; // // pgTextGreeting // this.pgTextGreeting.Controls.Add(this.speechControl); this.pgTextGreeting.Controls.Add(this.panel1); resources.ApplyResources(this.pgTextGreeting, "pgTextGreeting"); this.pgTextGreeting.IsFinishPage = false; this.pgTextGreeting.Name = "pgTextGreeting"; this.pgTextGreeting.TabLinkColor = System.Drawing.SystemColors.ControlText; // // speechControl // resources.ApplyResources(this.speechControl, "speechControl"); this.speechControl.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.speechControl.Name = "speechControl"; this.speechControl.ShowSuggestTextButton = false; this.speechControl.ShowVoiceSelection = false; this.speechControl.SpeechText = ""; this.speechControl.SuggestedText = ""; this.speechControl.Voice = ""; // // panel1 // this.panel1.Controls.Add(this.btnVoices); this.panel1.Controls.Add(this.label2); resources.ApplyResources(this.panel1, "panel1"); this.panel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.panel1.Name = "panel1"; // // btnVoices // this.btnVoices.AntiAliasText = false; this.btnVoices.Cursor = System.Windows.Forms.Cursors.Hand; this.btnVoices.ForeColor = System.Drawing.Color.RoyalBlue; this.btnVoices.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnVoices.LinkImage = global::CallButler.Manager.Controls.Properties.Resources.text_loudspeaker_16; resources.ApplyResources(this.btnVoices, "btnVoices"); this.btnVoices.Name = "btnVoices"; this.btnVoices.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnVoices.UnderlineOnHover = true; this.btnVoices.Click += new System.EventHandler(this.btnVoices_Click); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // pgRecordedGreeting // this.pgRecordedGreeting.Controls.Add(this.recordingControl); resources.ApplyResources(this.pgRecordedGreeting, "pgRecordedGreeting"); this.pgRecordedGreeting.IsFinishPage = false; this.pgRecordedGreeting.Name = "pgRecordedGreeting"; this.pgRecordedGreeting.TabLinkColor = System.Drawing.SystemColors.ControlText; // // recordingControl // resources.ApplyResources(this.recordingControl, "recordingControl"); this.recordingControl.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.recordingControl.Name = "recordingControl"; // // gradientPanel1 // this.gradientPanel1.BackColor = System.Drawing.Color.WhiteSmoke; this.gradientPanel1.BorderColor = System.Drawing.Color.DarkGray; this.gradientPanel1.BorderWidth = 1F; this.gradientPanel1.Controls.Add(this.toolStrip1); resources.ApplyResources(this.gradientPanel1, "gradientPanel1"); this.gradientPanel1.DrawBorder = true; this.gradientPanel1.ForeColor = System.Drawing.Color.LightGray; this.gradientPanel1.GradientAngle = 90F; this.gradientPanel1.Name = "gradientPanel1"; // // toolStrip1 // this.toolStrip1.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.toolStrip1, "toolStrip1"); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.mnuGreetingType}); this.toolStrip1.Name = "toolStrip1"; // // toolStripLabel1 // resources.ApplyResources(this.toolStripLabel1, "toolStripLabel1"); this.toolStripLabel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.toolStripLabel1.Name = "toolStripLabel1"; // // mnuGreetingType // this.mnuGreetingType.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuRecord, this.mnuCall, this.mnuSpeak}); this.mnuGreetingType.ForeColor = System.Drawing.Color.Black; resources.ApplyResources(this.mnuGreetingType, "mnuGreetingType"); this.mnuGreetingType.Name = "mnuGreetingType"; // // mnuRecord // this.mnuRecord.CheckOnClick = true; this.mnuRecord.Image = global::CallButler.Manager.Controls.Properties.Resources.loudspeaker_16; this.mnuRecord.Name = "mnuRecord"; resources.ApplyResources(this.mnuRecord, "mnuRecord"); this.mnuRecord.CheckedChanged += new System.EventHandler(this.mnuRecord_CheckedChanged); // // mnuCall // this.mnuCall.CheckOnClick = true; this.mnuCall.Image = global::CallButler.Manager.Controls.Properties.Resources.telephone_16; this.mnuCall.Name = "mnuCall"; resources.ApplyResources(this.mnuCall, "mnuCall"); this.mnuCall.CheckedChanged += new System.EventHandler(this.mnuCall_CheckedChanged); // // mnuSpeak // this.mnuSpeak.CheckOnClick = true; this.mnuSpeak.Image = global::CallButler.Manager.Controls.Properties.Resources.text_loudspeaker_16; this.mnuSpeak.Name = "mnuSpeak"; resources.ApplyResources(this.mnuSpeak, "mnuSpeak"); this.mnuSpeak.CheckedChanged += new System.EventHandler(this.mnuSpeak_CheckedChanged); // // gradientPanel2 // this.gradientPanel2.BackColor = System.Drawing.Color.WhiteSmoke; this.gradientPanel2.BorderColor = System.Drawing.Color.DarkGray; this.gradientPanel2.BorderWidth = 1F; this.gradientPanel2.Controls.Add(this.wzdGreeting); this.gradientPanel2.Controls.Add(this.gradientPanel1); resources.ApplyResources(this.gradientPanel2, "gradientPanel2"); this.gradientPanel2.DrawBorder = true; this.gradientPanel2.ForeColor = System.Drawing.Color.LightGray; this.gradientPanel2.GradientAngle = 90F; this.gradientPanel2.Name = "gradientPanel2"; // // btnPlaceCall // this.btnPlaceCall.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); resources.ApplyResources(this.btnPlaceCall, "btnPlaceCall"); this.btnPlaceCall.Name = "btnPlaceCall"; this.btnPlaceCall.UseVisualStyleBackColor = true; this.btnPlaceCall.Click += new System.EventHandler(this.btnPlaceCall_Click); // // GreetingControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.gradientPanel2); this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.Name = "GreetingControl"; this.wzdGreeting.ResumeLayout(false); this.wizardPage1.ResumeLayout(false); this.wizardPage1.PerformLayout(); this.pgTextGreeting.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.pgRecordedGreeting.ResumeLayout(false); this.gradientPanel1.ResumeLayout(false); this.gradientPanel1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.gradientPanel2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.ToolTip toolTip; private global::Controls.Wizard.Wizard wzdGreeting; private global::Controls.Wizard.WizardPage pgTextGreeting; private WOSI.Utilities.Sound.SpeechControl speechControl; private global::Controls.Wizard.WizardPage pgRecordedGreeting; private WOSI.Utilities.Sound.RecordingControl recordingControl; private global::Controls.GradientPanel gradientPanel1; private global::Controls.GradientPanel gradientPanel2; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label2; private global::Controls.LinkButton btnVoices; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripDropDownButton mnuGreetingType; private System.Windows.Forms.ToolStripMenuItem mnuRecord; private System.Windows.Forms.ToolStripMenuItem mnuCall; private System.Windows.Forms.ToolStripMenuItem mnuSpeak; private global::Controls.Wizard.WizardPage wizardPage1; private global::Controls.SmoothLabel smoothLabel2; private System.Windows.Forms.TextBox txtCallTo; private global::Controls.SmoothLabel smoothLabel1; private System.Windows.Forms.Button btnPlaceCall; } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Drawing; using System.Linq; using System.Text; using Glass.Mapper.Sc.Configuration; using Sitecore.Common; using Sitecore.Configuration; using Sitecore.Collections; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Globalization; using Sitecore.Links; using Sitecore.Xml.Xsl; namespace Glass.Mapper.Sc { /// <summary> /// Class Utilities /// </summary> public class Utilities : Mapper.Utilities { /// <summary> /// Converts a NameValueCollection into HTML attributes /// </summary> /// <param name="attributes">A list of attributes to convert</param> /// <returns>System.String.</returns> public static string ConvertAttributes(NameValueCollection attributes) { if (attributes == null || attributes.Count == 0) return ""; StringBuilder sb = new StringBuilder(); foreach (var key in attributes.AllKeys) { sb.AppendFormat("{0}='{1}' ".Formatted(key, attributes[key] ?? "")); } return sb.ToString(); } /// <summary> /// Converts a SafeDictionary into HTML attributes /// </summary> /// <param name="attributes">A list of attributes to convert</param> /// <returns>System.String.</returns> public static string ConvertAttributes(SafeDictionary<string> attributes, string quotationMark) { if (attributes == null || attributes.Count == 0) return ""; StringBuilder sb = new StringBuilder(); foreach (var pair in attributes) { sb.AppendFormat("{0}={2}{1}{2} ".Formatted(pair.Key, pair.Value ??"", quotationMark)); } return sb.ToString(); } public static Item CreateFakeItem(Dictionary<Guid, string> fields, string name = "itemName") { return CreateFakeItem(fields, new ID(Guid.NewGuid()), Factory.GetDatabase("master"), name); } public static Item CreateFakeItem(Dictionary<Guid, string> fields, ID templateId, Database database, string name = "ItemName") { var id = new ID(Guid.NewGuid()); var language = Language.Current; var version = Sitecore.Data.Version.Latest; var itemDefinition = new ItemDefinition(id, name, templateId, ID.Null); var fieldList = new FieldList(); if (fields != null) { foreach (var fieldId in fields.Keys) { fieldList.Add(new ID(fieldId), fields[fieldId]); } } var itemData = new ItemData(itemDefinition, language, version, fieldList); var item = new Item(id, itemData, database); return item; } public static Size ResizeImage(int imageW, int imageH, float imageScale, int w, int h, int maxW, int maxH) { Size size = new Size(w, h); Size imageSize = new Size(imageW, imageH); Size maxSize = new Size(maxW, maxH); if (imageW == 0 || imageH == 0) return size; return new GlassImageRender().GetFinalImageSize(imageSize, imageScale, size, maxSize); } /// <summary> /// Creates the URL options. /// </summary> /// <param name="urlOptions">The URL options.</param> /// <returns>UrlOptions.</returns> public static UrlOptions CreateUrlOptions(SitecoreInfoUrlOptions urlOptions) { UrlOptions defaultUrl = UrlOptions.DefaultOptions; return CreateUrlOptions(urlOptions, defaultUrl); } public static UrlOptions CreateUrlOptions(SitecoreInfoUrlOptions urlOptions, UrlOptions defaultOptions) { if (urlOptions == 0) return defaultOptions; Func<SitecoreInfoUrlOptions, bool> flagCheck = option => (urlOptions & option) == option; //check for any default overrides defaultOptions.AddAspxExtension = flagCheck(SitecoreInfoUrlOptions.AddAspxExtension) ? true : defaultOptions.AddAspxExtension; defaultOptions.AlwaysIncludeServerUrl = flagCheck(SitecoreInfoUrlOptions.AlwaysIncludeServerUrl) ? true : defaultOptions.AlwaysIncludeServerUrl; defaultOptions.EncodeNames = flagCheck(SitecoreInfoUrlOptions.EncodeNames) ? true : defaultOptions.EncodeNames; defaultOptions.ShortenUrls = flagCheck(SitecoreInfoUrlOptions.ShortenUrls) ? true : defaultOptions.ShortenUrls; defaultOptions.SiteResolving = flagCheck(SitecoreInfoUrlOptions.SiteResolving) ? true : defaultOptions.SiteResolving; defaultOptions.UseDisplayName =flagCheck(SitecoreInfoUrlOptions.UseUseDisplayName) ? true : defaultOptions.UseDisplayName; if (flagCheck(SitecoreInfoUrlOptions.LanguageEmbeddingAlways)) defaultOptions.LanguageEmbedding = LanguageEmbedding.Always; else if (flagCheck(SitecoreInfoUrlOptions.LanguageEmbeddingAsNeeded)) defaultOptions.LanguageEmbedding = LanguageEmbedding.AsNeeded; else if (flagCheck(SitecoreInfoUrlOptions.LanguageEmbeddingNever)) defaultOptions.LanguageEmbedding = LanguageEmbedding.Never; if (flagCheck(SitecoreInfoUrlOptions.LanguageLocationFilePath)) defaultOptions.LanguageLocation = LanguageLocation.FilePath; else if (flagCheck(SitecoreInfoUrlOptions.LanguageLocationQueryString)) defaultOptions.LanguageLocation = LanguageLocation.QueryString; return defaultOptions; } /// <summary> /// Gets the field. /// </summary> /// <param name="item">The item.</param> /// <param name="fieldId">The field id.</param> /// <param name="fieldName">Name of the field.</param> /// <returns>Field.</returns> public static Field GetField(Item item, ID fieldId, string fieldName = "") { if(item == null) throw new NullReferenceException("Item is null"); Field field; if (ID.IsNullOrEmpty(fieldId)) { field = item.Fields[fieldName]; } else// if (item.Fields.Contains(fieldId) || item.Template.GetField(fieldId) != null) { field = item.Fields[fieldId]; } return field; } /// <summary> /// Constructs the query string. /// </summary> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public static string ConstructQueryString(NameValueCollection parameters) { var sb = new StringBuilder(); foreach (String name in parameters) sb.Append(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name]), "&")); if (sb.Length > 0) return sb.ToString(0, sb.Length - 1); return String.Empty; } /// <summary> /// Gets the generic outer. /// </summary> /// <param name="type">The type.</param> /// <returns>Type.</returns> public static Type GetGenericOuter(Type type) { return type.GetGenericTypeDefinition(); } /// <summary> /// Gets the language item. /// </summary> /// <param name="foundItem">The found item.</param> /// <param name="language">The language.</param> /// <returns>Item.</returns> public static Item GetLanguageItem(Item foundItem, Language language, Config config) { if (foundItem == null) return null; var item = foundItem.Database.GetItem(foundItem.ID, language); if (item == null || (item.Versions.Count == 0 && Utilities.DoVersionCheck(config))) { return null; } return item; } public static bool DoVersionCheck(Config config) { if (config != null && config.ForceItemInPageEditor && GlassHtml.IsInEditingMode) return false; return Switcher<VersionCountState>.CurrentValue != VersionCountState.Disabled; } /// <summary> /// Gets the language items. /// </summary> /// <param name="foundItems">The found items.</param> /// <param name="language">The language.</param> /// <param name="config"></param> /// <returns>IEnumerable{Item}.</returns> public static IEnumerable<Item> GetLanguageItems(IEnumerable<Item> foundItems, Language language, Config config) { if (foundItems == null) return Enumerable.Empty<Item>(); return foundItems.Select(x => GetLanguageItem(x, language, config)).Where(x => x != null); } public class GlassImageRender : ImageRenderer { public Size GetFinalImageSize(Size imageSize, float imageScale, Size size, Size maxSize ) { return base.GetFinalImageSize(base.GetInitialImageSize(imageSize, imageScale, size), size, maxSize); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { [Flags] internal enum DeclarationInfo : byte { /// <summary> /// A declaration with this name has not been encountered. /// </summary> None = 0, /// <summary> /// This member is defined on the declared type or one of its base classes. /// </summary> FromDeclaredTypeOrBase = 0, /// <summary> /// This member is defined on a type that inherits from the declared type (is more derived). /// </summary> FromSubTypeOfDeclaredType = 1, /// <summary> /// This member should be hidden (under "Non-Public members" node), because Just My Code is on and /// no symbols have been loaded for the declaring type's module. /// </summary> HideNonPublic = 1 << 2, /// <summary> /// More than one non-virtual member with this name exists in the type hierarchy. /// The ResultProvider should include the declaring type of this member in the member name to disambiguate. /// </summary> IncludeTypeInMemberName = 1 << 3, /// <summary> /// The full name for this member access expression will require a cast to the declaring type. /// </summary> RequiresExplicitCast = 1 << 4, } internal static class DeclarationInfoExtensions { internal static bool IsSet(this DeclarationInfo info, DeclarationInfo value) { return (info & value) == value; } } internal struct MemberAndDeclarationInfo { public static readonly IComparer<MemberAndDeclarationInfo> Comparer = new MemberNameComparer(); private readonly MemberInfo _member; public readonly DkmClrDebuggerBrowsableAttributeState? BrowsableState; public readonly bool HideNonPublic; public readonly bool IncludeTypeInMemberName; public readonly bool RequiresExplicitCast; /// <summary> /// Exists to correctly order fields with the same name from different types in the inheritance hierarchy. /// </summary> private readonly int _inheritanceLevel; public MemberAndDeclarationInfo(MemberInfo member, DkmClrDebuggerBrowsableAttributeState? browsableState, DeclarationInfo info, int inheritanceLevel) { Debug.Assert(member != null); _member = member; this.BrowsableState = browsableState; this.HideNonPublic = info.IsSet(DeclarationInfo.HideNonPublic); this.IncludeTypeInMemberName = info.IsSet(DeclarationInfo.IncludeTypeInMemberName); this.RequiresExplicitCast = info.IsSet(DeclarationInfo.RequiresExplicitCast); _inheritanceLevel = inheritanceLevel; } public Type DeclaringType { get { return _member.DeclaringType; } } public bool IsPublic { get { return _member.IsPublic(); } } public bool IsStatic { get { switch (_member.MemberType) { case MemberTypes.Field: return ((FieldInfo)_member).IsStatic; case MemberTypes.Property: return ((PropertyInfo)_member).GetGetMethod(nonPublic: true).IsStatic; default: throw ExceptionUtilities.UnexpectedValue(_member.MemberType); } } } public MemberTypes MemberType { get { return _member.MemberType; } } public string Name { get { return _member.Name; } } public Type Type { get { return GetMemberType(_member); } } public Type OriginalDefinitionType { get { return GetMemberType(_member.GetOriginalDefinition()); } } private static Type GetMemberType(MemberInfo member) { switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; default: throw ExceptionUtilities.UnexpectedValue(member.MemberType); } } public DkmClrCustomTypeInfo TypeInfo { get { switch (_member.MemberType) { case MemberTypes.Field: case MemberTypes.Property: return _member.GetCustomAttributesData().GetDynamicFlags().GetCustomTypeInfo(); default: // If we ever see a method, we'll have to use ReturnTypeCustomAttributes. throw ExceptionUtilities.UnexpectedValue(_member.MemberType); } } } public Type GetExplicitlyImplementedInterface(out string memberName) { memberName = _member.Name; // We only display fields and properties and fields never implement interface members. if (_member.MemberType == MemberTypes.Property) { // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. var dotPos = memberName.LastIndexOf('.'); if (dotPos >= 0) { var property = (PropertyInfo)_member; var accessors = property.GetAccessors(nonPublic: true); Debug.Assert(accessors.Length > 0); // We'll just pick the first interface we find since we don't have a good way // to display more than one. foreach (var accessor in accessors) { foreach (var interfaceAccessor in accessor.GetExplicitInterfacesImplemented()) { memberName = memberName.Substring(dotPos + 1); return interfaceAccessor.DeclaringType; } } } } return null; } private sealed class MemberNameComparer : IComparer<MemberAndDeclarationInfo> { public int Compare(MemberAndDeclarationInfo x, MemberAndDeclarationInfo y) { var comp = string.Compare(x.Name, y.Name, StringComparison.Ordinal); return comp != 0 ? comp : (y._inheritanceLevel - x._inheritanceLevel); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataFactory.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataFactory; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Copy activity. /// </summary> [Newtonsoft.Json.JsonObject("Copy")] [Rest.Serialization.JsonTransformation] public partial class CopyActivity : ExecutionActivity { /// <summary> /// Initializes a new instance of the CopyActivity class. /// </summary> public CopyActivity() { CustomInit(); } /// <summary> /// Initializes a new instance of the CopyActivity class. /// </summary> /// <param name="name">Activity name.</param> /// <param name="source">Copy activity source.</param> /// <param name="sink">Copy activity sink.</param> /// <param name="description">Activity description.</param> /// <param name="dependsOn">Activity depends on condition.</param> /// <param name="linkedServiceName">Linked service reference.</param> /// <param name="policy">Activity policy.</param> /// <param name="translator">Copy activity translator. If not /// specificed, tabular translator is used.</param> /// <param name="enableStaging">Specifies whether to copy data via an /// interim staging. Default value is false. Type: boolean (or /// Expression with resultType boolean).</param> /// <param name="stagingSettings">Specifies interim staging settings /// when EnableStaging is true.</param> /// <param name="parallelCopies">Maximum number of concurrent sessions /// opened on the source or sink to avoid overloading the data store. /// Type: integer (or Expression with resultType integer), minimum: /// 0.</param> /// <param name="cloudDataMovementUnits">Maximum number of cloud data /// movement units that can be used to perform this data movement. /// Type: integer (or Expression with resultType integer), minimum: /// 0.</param> /// <param name="enableSkipIncompatibleRow">Whether to skip /// incompatible row. Default value is false. Type: boolean (or /// Expression with resultType boolean).</param> /// <param name="redirectIncompatibleRowSettings">Redirect incompatible /// row settings when EnableSkipIncompatibleRow is true.</param> /// <param name="inputs">List of inputs for the activity.</param> /// <param name="outputs">List of outputs for the activity.</param> public CopyActivity(string name, CopySource source, CopySink sink, string description = default(string), IList<ActivityDependency> dependsOn = default(IList<ActivityDependency>), LinkedServiceReference linkedServiceName = default(LinkedServiceReference), ActivityPolicy policy = default(ActivityPolicy), CopyTranslator translator = default(CopyTranslator), object enableStaging = default(object), StagingSettings stagingSettings = default(StagingSettings), object parallelCopies = default(object), object cloudDataMovementUnits = default(object), object enableSkipIncompatibleRow = default(object), RedirectIncompatibleRowSettings redirectIncompatibleRowSettings = default(RedirectIncompatibleRowSettings), IList<DatasetReference> inputs = default(IList<DatasetReference>), IList<DatasetReference> outputs = default(IList<DatasetReference>)) : base(name, description, dependsOn, linkedServiceName, policy) { Source = source; Sink = sink; Translator = translator; EnableStaging = enableStaging; StagingSettings = stagingSettings; ParallelCopies = parallelCopies; CloudDataMovementUnits = cloudDataMovementUnits; EnableSkipIncompatibleRow = enableSkipIncompatibleRow; RedirectIncompatibleRowSettings = redirectIncompatibleRowSettings; Inputs = inputs; Outputs = outputs; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets copy activity source. /// </summary> [JsonProperty(PropertyName = "typeProperties.source")] public CopySource Source { get; set; } /// <summary> /// Gets or sets copy activity sink. /// </summary> [JsonProperty(PropertyName = "typeProperties.sink")] public CopySink Sink { get; set; } /// <summary> /// Gets or sets copy activity translator. If not specificed, tabular /// translator is used. /// </summary> [JsonProperty(PropertyName = "typeProperties.translator")] public CopyTranslator Translator { get; set; } /// <summary> /// Gets or sets specifies whether to copy data via an interim staging. /// Default value is false. Type: boolean (or Expression with /// resultType boolean). /// </summary> [JsonProperty(PropertyName = "typeProperties.enableStaging")] public object EnableStaging { get; set; } /// <summary> /// Gets or sets specifies interim staging settings when EnableStaging /// is true. /// </summary> [JsonProperty(PropertyName = "typeProperties.stagingSettings")] public StagingSettings StagingSettings { get; set; } /// <summary> /// Gets or sets maximum number of concurrent sessions opened on the /// source or sink to avoid overloading the data store. Type: integer /// (or Expression with resultType integer), minimum: 0. /// </summary> [JsonProperty(PropertyName = "typeProperties.parallelCopies")] public object ParallelCopies { get; set; } /// <summary> /// Gets or sets maximum number of cloud data movement units that can /// be used to perform this data movement. Type: integer (or Expression /// with resultType integer), minimum: 0. /// </summary> [JsonProperty(PropertyName = "typeProperties.cloudDataMovementUnits")] public object CloudDataMovementUnits { get; set; } /// <summary> /// Gets or sets whether to skip incompatible row. Default value is /// false. Type: boolean (or Expression with resultType boolean). /// </summary> [JsonProperty(PropertyName = "typeProperties.enableSkipIncompatibleRow")] public object EnableSkipIncompatibleRow { get; set; } /// <summary> /// Gets or sets redirect incompatible row settings when /// EnableSkipIncompatibleRow is true. /// </summary> [JsonProperty(PropertyName = "typeProperties.redirectIncompatibleRowSettings")] public RedirectIncompatibleRowSettings RedirectIncompatibleRowSettings { get; set; } /// <summary> /// Gets or sets list of inputs for the activity. /// </summary> [JsonProperty(PropertyName = "inputs")] public IList<DatasetReference> Inputs { get; set; } /// <summary> /// Gets or sets list of outputs for the activity. /// </summary> [JsonProperty(PropertyName = "outputs")] public IList<DatasetReference> Outputs { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (Source == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Source"); } if (Sink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Sink"); } if (StagingSettings != null) { StagingSettings.Validate(); } if (RedirectIncompatibleRowSettings != null) { RedirectIncompatibleRowSettings.Validate(); } if (Inputs != null) { foreach (var element in Inputs) { if (element != null) { element.Validate(); } } } if (Outputs != null) { foreach (var element1 in Outputs) { if (element1 != null) { element1.Validate(); } } } } } }
using System; using System.Threading; using System.Transactions; using log4net; using Rhino.ServiceBus.FileMessaging; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Transport; using Rhino.ServiceBus.Util; using MessageType = Rhino.ServiceBus.Transport.MessageType; using System.Diagnostics; namespace Rhino.ServiceBus.File { public abstract class AbstractFileListener : IStartable { private readonly IQueueStrategy queueStrategy; private readonly Uri endpoint; private readonly Thread[] threads; private bool haveStarted; private volatile bool shouldStop; private readonly IMessageSerializer messageSerializer; private readonly ILog logger = LogManager.GetLogger(typeof(AbstractFileListener)); private readonly int threadCount; public event Action MessageMoved; public event Action TransportMessageArrived; protected AbstractFileListener( IQueueStrategy queueStrategy, Uri endpoint, int threadCount, IMessageSerializer messageSerializer, IEndpointRouter endpointRouter, TransactionalOptions transactional, IMessageBuilder<Message> messageBuilder) { this.queueStrategy = queueStrategy; this.messageSerializer = messageSerializer; this.endpointRouter = endpointRouter; this.endpoint = endpoint; this.threadCount = threadCount; threads = new Thread[threadCount]; switch (transactional) { case TransactionalOptions.Transactional: this.transactional = true; break; case TransactionalOptions.NonTransactional: this.transactional = false; break; case TransactionalOptions.FigureItOut: this.transactional = null; break; default: throw new ArgumentOutOfRangeException("transactional"); } this.messageBuilder = messageBuilder; this.messageBuilder.Initialize(Endpoint); } public event Action Started; public bool HaveStarted { get { return haveStarted; } } public int ThreadCount { get { return threadCount; } } public Endpoint Endpoint { get { var routedEndpoint = endpointRouter.GetRoutedEndpoint(endpoint); routedEndpoint.Transactional = transactional; return routedEndpoint; } } protected static TimeSpan TimeOutForPeek { get { return TimeSpan.FromHours(1); } } public void Start() { if (haveStarted) return; logger.DebugFormat("Starting eml transport on: {0}", Endpoint); using (var queue = Endpoint.InitalizeQueue()) { BeforeStart(queue); // shouldStop = false; TransportState = TransportState.Started; for (var t = 0; t < ThreadCount; t++) { var thread = new Thread(PeekMessageOnBackgroundThread) { Name = "Rhino Service Bus Worker Thread #" + t, IsBackground = true }; threads[t] = thread; thread.Start(); } haveStarted = true; // var copy = Started; if (copy != null) copy(); // AfterStart(queue); } } protected virtual void AfterStart(OpenedQueue queue) { } protected virtual void BeforeStart(OpenedQueue queue) { } public void Dispose() { shouldStop = true; OnStop(); using (var queue = Endpoint.InitalizeQueue()) queue.SendInSingleTransaction(new Message { Label = "Shutdown bus", Extension = Guid.NewGuid().ToByteArray(), AppSpecific = (int)MessageType.ShutDownMessageMarker }); WaitForProcessingToEnd(); // haveStarted = false; TransportState = TransportState.Stopped; } protected virtual void OnStop() { } private void WaitForProcessingToEnd() { if (!haveStarted) return; foreach (var thread in threads) thread.Join(); } protected void PeekMessageOnBackgroundThread(object state) { using (var queue = Endpoint.InitalizeQueue()) while (!shouldStop) try { Message message; var peek = TryPeek(queue, out message); // if (peek == false || shouldStop) // error reading from queue { TransportState = TransportState.FailedToReadFromQueue; return; // return from method, we have failed } if (peek == null) // nothing was found continue; // if ((MessageType)((message.AppSpecific & 0xFFFF0000) >> 16) == MessageType.MoveMessageMarker) { var subQueue = (SubQueue)(0x0000FFFF & message.AppSpecific); using (var tx = new TransactionScope()) { string msgId; queueStrategy.TryMoveMessage(queue, message, subQueue, out msgId); tx.Complete(); } Raise(MessageMoved); continue; } var responseQueue = "null://middle/of/nowhere?turn=left"; if (message.ResponseQueue != null) responseQueue = message.ResponseQueue.Path; logger.DebugFormat("Got message {0} on {1} from {2}", message.Label, queue.RootUri, responseQueue); // Raise(TransportMessageArrived); HandlePeekedMessage(queue, message); } catch (ThreadAbortException) { } // nothing much to do here, process is being killed or someone is trying to do something rude to us catch (Exception e) { #if DEBUG Debugger.Break(); Debug.Fail("should not happen", e.ToString()); #endif logger.Fatal("BUG_IN_THE_BUS: An error occured during message dispatch by the bus itself. Please notify the developers", e); } } protected static void Raise(Action action) { var copy = action; if (copy != null) copy(); } protected IEndpointRouter endpointRouter; private readonly bool? transactional; private readonly IMessageBuilder<Message> messageBuilder; public TransportState TransportState { get; set; } protected abstract void HandlePeekedMessage(OpenedQueue queue, Message message); private bool? TryPeek(OpenedQueue queue, out Message message) { try { message = queue.Peek(TimeOutForPeek); } catch (MessageQueueException e) { message = null; if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout) { logger.Error("Could not peek message from queue", e); return false; } return null; // nothing found } catch (Exception e) { message = null; logger.Error("Could not peek message from queue", e); return false; } return true; } protected Message GenerateMsmqMessageFromMessageBatch(params object[] msgs) { return messageBuilder.BuildFromMessageBatch(msgs); } protected object[] DeserializeMessages(OpenedQueue messageQueue, Message transportMessage, Action<CurrentMessageInformation, Exception> messageSerializationException) { try { return messageSerializer.Deserialize(transportMessage.BodyStream); } catch (Exception e) { try { logger.Error("Error when serializing message", e); if (messageSerializationException != null) { var information = new FileCurrentMessageInformation { FileMessage = transportMessage, Queue = messageQueue, Message = transportMessage, Source = messageQueue.RootUri, MessageId = transportMessage.GetMessageId(), Headers = transportMessage.Extension.DeserializeHeaders(), }; messageSerializationException(information, e); } } catch (Exception moduleEx) { logger.Error("Error when notifying about serialization exception", moduleEx); } throw; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // // <OWNER>[....]</OWNER> // // ==--== /*============================================================================= ** ** Class: Exception ** ** ** Purpose: The base class for all exceptional conditions. ** ** =============================================================================*/ namespace System { using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics; using System.Security.Permissions; using System.Security; using System.IO; using System.Text; using System.Reflection; using System.Collections; using System.Globalization; using System.Diagnostics.Contracts; [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Exception))] [Serializable] [ComVisible(true)] #if MONO [StructLayout (LayoutKind.Sequential)] #endif public class Exception : ISerializable #if !(MONO && MOBILE) , _Exception #endif { private void Init() { _message = null; _stackTrace = null; _dynamicMethods = null; HResult = __HResults.COR_E_EXCEPTION; #if !MONO _xcode = _COMPlusExceptionCode; _xptrs = (IntPtr) 0; // Initialize the WatsonBuckets to be null _watsonBuckets = null; // Initialize the watson bucketing IP _ipForWatsonBuckets = UIntPtr.Zero; #endif #if FEATURE_SERIALIZATION _safeSerializationManager = new SafeSerializationManager(); #endif // FEATURE_SERIALIZATION } public Exception() { Init(); } public Exception(String message) { Init(); _message = message; } // Creates a new Exception. All derived classes should // provide this constructor. // Note: the stack trace is not started until the exception // is thrown // public Exception (String message, Exception innerException) { Init(); _message = message; _innerException = innerException; } [System.Security.SecuritySafeCritical] // auto-generated protected Exception(SerializationInfo info, StreamingContext context) { if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); _className = info.GetString("ClassName"); _message = info.GetString("Message"); _data = (IDictionary)(info.GetValueNoThrow("Data",typeof(IDictionary))); _innerException = (Exception)(info.GetValue("InnerException",typeof(Exception))); _helpURL = info.GetString("HelpURL"); _stackTraceString = info.GetString("StackTraceString"); _remoteStackTraceString = info.GetString("RemoteStackTraceString"); _remoteStackIndex = info.GetInt32("RemoteStackIndex"); #if !MONO _exceptionMethodString = (String)(info.GetValue("ExceptionMethod",typeof(String))); #endif HResult = info.GetInt32("HResult"); _source = info.GetString("Source"); #if !MONO // Get the WatsonBuckets that were serialized - this is particularly // done to support exceptions going across AD transitions. // // We use the no throw version since we could be deserializing a pre-V4 // exception object that may not have this entry. In such a case, we would // get null. _watsonBuckets = (Object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[])); #endif #if FEATURE_SERIALIZATION _safeSerializationManager = info.GetValueNoThrow("SafeSerializationManager", typeof(SafeSerializationManager)) as SafeSerializationManager; #endif // FEATURE_SERIALIZATION if (_className == null || HResult==0) throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); // If we are constructing a new exception after a cross-appdomain call... if (context.State == StreamingContextStates.CrossAppDomain) { // ...this new exception may get thrown. It is logically a re-throw, but // physically a brand-new exception. Since the stack trace is cleared // on a new exception, the "_remoteStackTraceString" is provided to // effectively import a stack trace from a "remote" exception. So, // move the _stackTraceString into the _remoteStackTraceString. Note // that if there is an existing _remoteStackTraceString, it will be // preserved at the head of the new string, so everything works as // expected. // Even if this exception is NOT thrown, things will still work as expected // because the StackTrace property returns the concatenation of the // _remoteStackTraceString and the _stackTraceString. _remoteStackTraceString = _remoteStackTraceString + _stackTraceString; _stackTraceString = null; } } public virtual String Message { get { if (_message == null) { if (_className==null) { _className = GetClassName(); } return Environment.GetResourceString("Exception_WasThrown", _className); } else { return _message; } } } public virtual IDictionary Data { [System.Security.SecuritySafeCritical] // auto-generated get { if (_data == null) if (IsImmutableAgileException(this)) _data = new EmptyReadOnlyDictionaryInternal(); else _data = new ListDictionaryInternal(); return _data; } } #if MONO private static bool IsImmutableAgileException(Exception e) { return false; } #else [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsImmutableAgileException(Exception e); #endif #if FEATURE_COMINTEROP // // Exception requires anything to be added into Data dictionary is serializable // This wrapper is made serializable to satisfy this requirement but does NOT serialize // the object and simply ignores it during serialization, because we only need // the exception instance in the app to hold the error object alive. // Once the exception is serialized to debugger, debugger only needs the error reference string // [Serializable] internal class __RestrictedErrorObject { // Hold the error object instance but don't serialize/deserialize it [NonSerialized] private object _realErrorObject; internal __RestrictedErrorObject(object errorObject) { _realErrorObject = errorObject; } public object RealErrorObject { get { return _realErrorObject; } } } [FriendAccessAllowed] internal void AddExceptionDataForRestrictedErrorInfo( string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject, bool hasrestrictedLanguageErrorObject = false) { IDictionary dict = Data; if (dict != null) { dict.Add("RestrictedDescription", restrictedError); dict.Add("RestrictedErrorReference", restrictedErrorReference); dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid); // Keep the error object alive so that user could retrieve error information // using Data["RestrictedErrorReference"] dict.Add("__RestrictedErrorObject", (restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject))); dict.Add("__HasRestrictedLanguageErrorObject", hasrestrictedLanguageErrorObject); } } internal bool TryGetRestrictedLanguageErrorObject(out object restrictedErrorObject) { restrictedErrorObject = null; if (Data != null && Data.Contains("__HasRestrictedLanguageErrorObject")) { if (Data.Contains("__RestrictedErrorObject")) { __RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject; if (restrictedObject != null) restrictedErrorObject = restrictedObject.RealErrorObject; } return (bool)Data["__HasRestrictedLanguageErrorObject"]; } return false; } #endif // FEATURE_COMINTEROP private string GetClassName() { // Will include namespace but not full instantiation and assembly name. if (_className == null) _className = GetType().ToString(); return _className; } // Retrieves the lowest exception (inner most) for the given Exception. // This will traverse exceptions using the innerException property. // public virtual Exception GetBaseException() { Exception inner = InnerException; Exception back = this; while (inner != null) { back = inner; inner = inner.InnerException; } return back; } // Returns the inner exception contained in this exception // public Exception InnerException { get { return _innerException; } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace); #if !MONO [System.Security.SecuritySafeCritical] // auto-generated private MethodBase GetExceptionMethodFromStackTrace() { IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace); // Under certain race conditions when exceptions are re-used, this can be null if (method == null) return null; return RuntimeType.GetMethodBase(method); } #endif public MethodBase TargetSite { [System.Security.SecuritySafeCritical] // auto-generated get { #if MONO StackTrace st = new StackTrace (this, true); if (st.FrameCount > 0) return st.GetFrame (0).GetMethod (); return null; #else return GetTargetSiteInternal(); #endif } } #if !MONO // This, as well as the entire "exception method" mechanism, appear to be linked to security features which Mono does not support. // this function is provided as a private helper to avoid the security demand [System.Security.SecurityCritical] // auto-generated private MethodBase GetTargetSiteInternal() { if (_exceptionMethod!=null) { return _exceptionMethod; } if (_stackTrace==null) { return null; } if (_exceptionMethodString!=null) { _exceptionMethod = GetExceptionMethodFromString(); } else { _exceptionMethod = GetExceptionMethodFromStackTrace(); } return _exceptionMethod; } #endif // Returns the stack trace as a string. If no stack trace is // available, null is returned. public virtual String StackTrace { #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif get { // By default attempt to include file and line number info return GetStackTrace(true); } } // Computes and returns the stack trace as a string // Attempts to get source file and line number information if needFileInfo // is true. Note that this requires FileIOPermission(PathDiscovery), and so // will usually fail in CoreCLR. To avoid the demand and resulting // SecurityException we can explicitly not even try to get fileinfo. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif private string GetStackTrace(bool needFileInfo) { string stackTraceString = _stackTraceString; string remoteStackTraceString = _remoteStackTraceString; #if !FEATURE_CORECLR if (!needFileInfo) { // Filter out file names/paths and line numbers from _stackTraceString and _remoteStackTraceString. // This is used only when generating stack trace for Watson where the strings must be PII-free. stackTraceString = StripFileInfo(stackTraceString, false); remoteStackTraceString = StripFileInfo(remoteStackTraceString, true); } #endif // !FEATURE_CORECLR // if no stack trace, try to get one if (stackTraceString != null) { return remoteStackTraceString + stackTraceString; } if (_stackTrace == null) { return remoteStackTraceString; } // Obtain the stack trace string. Note that since Environment.GetStackTrace // will add the path to the source file if the PDB is present and a demand // for FileIOPermission(PathDiscovery) succeeds, we need to make sure we // don't store the stack trace string in the _stackTraceString member variable. String tempStackTraceString = Environment.GetStackTrace(this, needFileInfo); return remoteStackTraceString + tempStackTraceString; } [FriendAccessAllowed] internal void SetErrorCode(int hr) { HResult = hr; } // Sets the help link for this exception. // This should be in a URL/URN form, such as: // "file:///C:/Applications/Bazzal/help.html#ErrorNum42" // Changed to be a read-write String and not return an exception public virtual String HelpLink { get { return _helpURL; } set { _helpURL = value; } } public virtual String Source { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif get { if (_source == null) { StackTrace st = new StackTrace(this,true); if (st.FrameCount>0) { StackFrame sf = st.GetFrame(0); MethodBase method = sf.GetMethod(); #if MONO if (method != null) { // source can be null _source = method.DeclaringType.Assembly.UnprotectedGetName ().Name; } #else Module module = method.Module; RuntimeModule rtModule = module as RuntimeModule; if (rtModule == null) { System.Reflection.Emit.ModuleBuilder moduleBuilder = module as System.Reflection.Emit.ModuleBuilder; if (moduleBuilder != null) rtModule = moduleBuilder.InternalModule; else throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeReflectionObject")); } _source = rtModule.GetRuntimeAssembly().GetSimpleName(); #endif } } return _source; } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif set { _source = value; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public override String ToString() { return ToString(true, true); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif private String ToString(bool needFileLineInfo, bool needMessage) { String message = (needMessage ? Message : null); String s; if (message == null || message.Length <= 0) { s = GetClassName(); } else { s = GetClassName() + ": " + message; } if (_innerException!=null) { s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine + " " + Environment.GetResourceString("Exception_EndOfInnerExceptionStack"); } string stackTrace = GetStackTrace(needFileLineInfo); if (stackTrace != null) { s += Environment.NewLine + stackTrace; } return s; } #if !MONO [System.Security.SecurityCritical] // auto-generated private String GetExceptionMethodString() { MethodBase methBase = GetTargetSiteInternal(); if (methBase==null) { return null; } if (methBase is System.Reflection.Emit.DynamicMethod.RTDynamicMethod) { // DynamicMethods cannot be serialized return null; } // Note that the newline separator is only a separator, chosen such that // it won't (generally) occur in a method name. This string is used // only for serialization of the Exception Method. char separator = '\n'; StringBuilder result = new StringBuilder(); if (methBase is ConstructorInfo) { RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase; Type t = rci.ReflectedType; result.Append((int)MemberTypes.Constructor); result.Append(separator); result.Append(rci.Name); if (t!=null) { result.Append(separator); result.Append(t.Assembly.FullName); result.Append(separator); result.Append(t.FullName); } result.Append(separator); result.Append(rci.ToString()); } else { Contract.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo"); RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase; Type t = rmi.DeclaringType; result.Append((int)MemberTypes.Method); result.Append(separator); result.Append(rmi.Name); result.Append(separator); result.Append(rmi.Module.Assembly.FullName); result.Append(separator); if (t != null) { result.Append(t.FullName); result.Append(separator); } result.Append(rmi.ToString()); } return result.ToString(); } [System.Security.SecurityCritical] // auto-generated private MethodBase GetExceptionMethodFromString() { Contract.Assert(_exceptionMethodString != null, "Method string cannot be NULL!"); String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'}); if (args.Length!=5) { throw new SerializationException(); } SerializationInfo si = new SerializationInfo(typeof(MemberInfoSerializationHolder), new FormatterConverter()); si.AddValue("MemberType", (int)Int32.Parse(args[0], CultureInfo.InvariantCulture), typeof(Int32)); si.AddValue("Name", args[1], typeof(String)); si.AddValue("AssemblyName", args[2], typeof(String)); si.AddValue("ClassName", args[3]); si.AddValue("Signature", args[4]); MethodBase result; StreamingContext sc = new StreamingContext(StreamingContextStates.All); try { result = (MethodBase)new MemberInfoSerializationHolder(si, sc).GetRealObject(sc); } catch (SerializationException) { result = null; } return result; } #endif #if FEATURE_SERIALIZATION protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState { add { _safeSerializationManager.SerializeObjectState += value; } remove { _safeSerializationManager.SerializeObjectState -= value; } } #endif // FEATURE_SERIALIZATION [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); String tempStackTraceString = _stackTraceString; if (_stackTrace!=null) { if (tempStackTraceString==null) { tempStackTraceString = Environment.GetStackTrace(this, true); } #if !MONO if (_exceptionMethod==null) { _exceptionMethod = GetExceptionMethodFromStackTrace(); } #endif } if (_source == null) { _source = Source; // Set the Source information correctly before serialization } info.AddValue("ClassName", GetClassName(), typeof(String)); info.AddValue("Message", _message, typeof(String)); info.AddValue("Data", _data, typeof(IDictionary)); info.AddValue("InnerException", _innerException, typeof(Exception)); info.AddValue("HelpURL", _helpURL, typeof(String)); info.AddValue("StackTraceString", tempStackTraceString, typeof(String)); info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(String)); info.AddValue("RemoteStackIndex", _remoteStackIndex, typeof(Int32)); #if MONO info.AddValue("ExceptionMethod", null); #else info.AddValue("ExceptionMethod", GetExceptionMethodString(), typeof(String)); #endif info.AddValue("HResult", HResult); info.AddValue("Source", _source, typeof(String)); #if !MONO // Serialize the Watson bucket details as well info.AddValue("WatsonBuckets", _watsonBuckets, typeof(byte[])); #endif #if FEATURE_SERIALIZATION if (_safeSerializationManager != null && _safeSerializationManager.IsActive) { info.AddValue("SafeSerializationManager", _safeSerializationManager, typeof(SafeSerializationManager)); // User classes derived from Exception must have a valid _safeSerializationManager. // Exceptions defined in mscorlib don't use this field might not have it initalized (since they are // often created in the VM with AllocateObject instead if the managed construtor) // If you are adding code to use a SafeSerializationManager from an mscorlib exception, update // this assert to ensure that it fails when that exception's _safeSerializationManager is NULL Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)), "User defined exceptions must have a valid _safeSerializationManager"); // Handle serializing any transparent or partial trust subclass data _safeSerializationManager.CompleteSerialization(this, info, context); } #endif // FEATURE_SERIALIZATION } // This is used by remoting to preserve the server side stack trace // by appending it to the message ... before the exception is rethrown // at the client call site. internal Exception PrepForRemoting() { String tmp = null; if (_remoteStackIndex == 0) { tmp = Environment.NewLine+ "Server stack trace: " + Environment.NewLine + StackTrace + Environment.NewLine + Environment.NewLine + "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine; } else { tmp = StackTrace + Environment.NewLine + Environment.NewLine + "Exception rethrown at ["+_remoteStackIndex+"]: " + Environment.NewLine; } _remoteStackTraceString = tmp; _remoteStackIndex++; return this; } // This method will clear the _stackTrace of the exception object upon deserialization // to ensure that references from another AD/Process dont get accidently used. [OnDeserialized] private void OnDeserialized(StreamingContext context) { _stackTrace = null; #if !MONO // We wont serialize or deserialize the IP for Watson bucketing since // we dont know where the deserialized object will be used in. // Using it across process or an AppDomain could be invalid and result // in AV in the runtime. // // Hence, we set it to zero when deserialization takes place. _ipForWatsonBuckets = UIntPtr.Zero; #endif #if FEATURE_SERIALIZATION if (_safeSerializationManager == null) { _safeSerializationManager = new SafeSerializationManager(); } else { _safeSerializationManager.CompleteDeserialization(this); } #endif // FEATURE_SERIALIZATION } // This is used by the runtime when re-throwing a managed exception. It will // copy the stack trace to _remoteStackTraceString. #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif internal void InternalPreserveStackTrace() { string tmpStackTraceString; #if FEATURE_APPX if (AppDomain.IsAppXModel()) { // Call our internal GetStackTrace in AppX so we can parse the result should // we need to strip file/line info from it to make it PII-free. Calling the // public and overridable StackTrace getter here was probably not intended. tmpStackTraceString = GetStackTrace(true); // Make sure that the _source field is initialized if Source is not overriden. // We want it to contain the original faulting point. string source = Source; } else #else // FEATURE_APPX #if FEATURE_CORESYSTEM // Preinitialize _source on CoreSystem as well. The legacy behavior is not ideal and // we keep it for back compat but we can afford to make the change on the Phone. string source = Source; #endif // FEATURE_CORESYSTEM #endif // FEATURE_APPX { // Call the StackTrace getter in classic for compat. tmpStackTraceString = StackTrace; } if (tmpStackTraceString != null && tmpStackTraceString.Length > 0) { _remoteStackTraceString = tmpStackTraceString + Environment.NewLine; } _stackTrace = null; _stackTraceString = null; } #if FEATURE_EXCEPTIONDISPATCHINFO // This is the object against which a lock will be taken // when attempt to restore the EDI. Since its static, its possible // that unrelated exception object restorations could get blocked // for a small duration but that sounds reasonable considering // such scenarios are going to be extremely rare, where timing // matches precisely. [OptionalField] private static object s_EDILock = new object(); #if !MONO internal UIntPtr IPForWatsonBuckets { get { return _ipForWatsonBuckets; } } internal object WatsonBuckets { get { return _watsonBuckets; } } #endif internal string RemoteStackTrace { get { return _remoteStackTraceString; } } #if MONO // This is only needed for Watson support private string StripFileInfo(string stackTrace, bool isRemoteStackTrace) { return stackTrace; } #else [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void PrepareForForeignExceptionRaise(); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern object CopyStackTrace(object currentStackTrace); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern object CopyDynamicMethods(object currentDynamicMethods); #if !FEATURE_CORECLR [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern string StripFileInfo(string stackTrace, bool isRemoteStackTrace); #endif // !FEATURE_CORECLR [SecuritySafeCritical] internal object DeepCopyStackTrace(object currentStackTrace) { if (currentStackTrace != null) { return CopyStackTrace(currentStackTrace); } else { return null; } } [SecuritySafeCritical] internal object DeepCopyDynamicMethods(object currentDynamicMethods) { if (currentDynamicMethods != null) { return CopyDynamicMethods(currentDynamicMethods); } else { return null; } } [SecuritySafeCritical] internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray) { GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray); } #endif // This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the // exception, just before the exception is "rethrown". [SecuritySafeCritical] internal void RestoreExceptionDispatchInfo(System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo) { #if MONO captured_traces = (StackTrace[]) exceptionDispatchInfo.BinaryStackTraceArray; _stackTrace = null; _stackTraceString = null; #else bool fCanProcessException = !(IsImmutableAgileException(this)); // Restore only for non-preallocated exceptions if (fCanProcessException) { // Take a lock to ensure only one thread can restore the details // at a time against this exception object that could have // multiple ExceptionDispatchInfo instances associated with it. // // We do this inside a finally clause to ensure ThreadAbort cannot // be injected while we have taken the lock. This is to prevent // unrelated exception restorations from getting blocked due to TAE. try{} finally { // When restoring back the fields, we again create a copy and set reference to them // in the exception object. This will ensure that when this exception is thrown and these // fields are modified, then EDI's references remain intact. // // Since deep copying can throw on OOM, try to get the copies // outside the lock. object _stackTraceCopy = (exceptionDispatchInfo.BinaryStackTraceArray == null)?null:DeepCopyStackTrace(exceptionDispatchInfo.BinaryStackTraceArray); object _dynamicMethodsCopy = (exceptionDispatchInfo.DynamicMethodArray == null)?null:DeepCopyDynamicMethods(exceptionDispatchInfo.DynamicMethodArray); // Finally, restore the information. // // Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance, // they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock. lock(Exception.s_EDILock) { #if !MONO _watsonBuckets = exceptionDispatchInfo.WatsonBuckets; _ipForWatsonBuckets = exceptionDispatchInfo.IPForWatsonBuckets; #endif _remoteStackTraceString = exceptionDispatchInfo.RemoteStackTrace; SaveStackTracesFromDeepCopy(this, _stackTraceCopy, _dynamicMethodsCopy); } _stackTraceString = null; // Marks the TES state to indicate we have restored foreign exception // dispatch information. Exception.PrepareForForeignExceptionRaise(); } } #endif } #endif // FEATURE_EXCEPTIONDISPATCHINFO private String _className; //Needed for serialization. #if !MONO // See TargetSite comments private MethodBase _exceptionMethod; //Needed for serialization. private String _exceptionMethodString; //Needed for serialization. #endif internal String _message; private IDictionary _data; private Exception _innerException; private String _helpURL; private Object _stackTrace; #if !MONO // Watson is Microsoft's online crash reporting system [OptionalField] // This isnt present in pre-V4 exception objects that would be serialized. private Object _watsonBuckets; #endif private String _stackTraceString; //Needed for serialization. private String _remoteStackTraceString; private int _remoteStackIndex; #pragma warning disable 414 // Field is not used from managed. // _dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of the exception. We do this because // the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed // unless a System.Resolver object roots it. private Object _dynamicMethods; #pragma warning restore 414 // @MANAGED: HResult is used from within the EE! Rename with care - check VM directory internal int _HResult; // HResult public int HResult { get { return _HResult; } protected set { _HResult = value; } } private String _source; // Mainly used by VB. #if !MONO // WARNING: Don't delete/rename _xptrs and _xcode - used by functions // on Marshal class. Native functions are in COMUtilNative.cpp & AppDomain private IntPtr _xptrs; // Internal EE stuff #pragma warning disable 414 // Field is not used from managed. private int _xcode; // Internal EE stuff #pragma warning restore 414 [OptionalField] private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing #endif #if FEATURE_SERIALIZATION [OptionalField(VersionAdded = 4)] private SafeSerializationManager _safeSerializationManager; #endif // FEATURE_SERIALIZATION #if MONO // Mono: Used when rethrowing exception internal StackTrace[] captured_traces; // Mono addition: Used on iPhone IntPtr[] native_trace_ips; #endif // See clr\src\vm\excep.h's EXCEPTION_COMPLUS definition: private const int _COMPlusExceptionCode = unchecked((int)0xe0434352); // Win32 exception code for COM+ exceptions // InternalToString is called by the runtime to get the exception text // and create a corresponding CrossAppDomainMarshaledException [System.Security.SecurityCritical] // auto-generated internal virtual String InternalToString() { try { #pragma warning disable 618 SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy); #pragma warning restore 618 sp.Assert(); } catch { //under normal conditions there should be no exceptions //however if something wrong happens we still can call the usual ToString } // Get the current stack trace string. On CoreCLR we don't bother // to try and include file/line-number information because all AppDomains // are sandboxed, and so this won't succeed in most (or all) cases. Therefore the // Demand and exception overhead is a waste. // We currently have some bugs in watson bucket generation where the SecurityException // here causes us to lose saved bucket parameters. By not even doing the demand // we avoid those problems (although there are deep underlying problems that need to // be fixed there - relying on this to avoid problems is incomplete and brittle). bool fGetFileLineInfo = true; #if FEATURE_CORECLR fGetFileLineInfo = false; #endif return ToString(fGetFileLineInfo, true); } #if !FEATURE_CORECLR // this method is required so Object.GetType is not made virtual by the compiler // _Exception.GetType() public new Type GetType() { return base.GetType(); } #endif internal bool IsTransient { [System.Security.SecuritySafeCritical] // auto-generated get { return nIsTransient(_HResult); } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool nIsTransient(int hr); // This piece of infrastructure exists to help avoid deadlocks // between parts of mscorlib that might throw an exception while // holding a lock that are also used by mscorlib's ResourceManager // instance. As a special case of code that may throw while holding // a lock, we also need to fix our asynchronous exceptions to use // Win32 resources as well (assuming we ever call a managed // constructor on instances of them). We should grow this set of // exception messages as we discover problems, then move the resources // involved to native code. internal enum ExceptionMessageKind { ThreadAbort = 1, ThreadInterrupted = 2, OutOfMemory = 3 } // See comment on ExceptionMessageKind [System.Security.SecuritySafeCritical] // auto-generated internal static String GetMessageFromNativeResources(ExceptionMessageKind kind) { #if MONO switch (kind) { case ExceptionMessageKind.ThreadAbort: return ""; case ExceptionMessageKind.ThreadInterrupted: return ""; case ExceptionMessageKind.OutOfMemory: return "Out of memory"; } return ""; #else string retMesg = null; GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg)); return retMesg; #endif } #if !MONO [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg); #endif #if MONO // Exposed to support Mono BCL classes internal void SetMessage (string s) { _message = s; } internal void SetStackTrace (string s) { _stackTraceString = s; } // Support for a System.Runtime.Remoting.Proxies.RealProxy edge case internal Exception FixRemotingException () { string message = (0 == _remoteStackIndex) ? Locale.GetText ("{0}{0}Server stack trace: {0}{1}{0}{0}Exception rethrown at [{2}]: {0}") : Locale.GetText ("{1}{0}{0}Exception rethrown at [{2}]: {0}"); string tmp = String.Format (message, Environment.NewLine, StackTrace, _remoteStackIndex); _remoteStackTraceString = tmp; _remoteStackIndex++; _stackTraceString = null; return this; } #endif } #if FEATURE_CORECLR //-------------------------------------------------------------------------- // Telesto: Telesto doesn't support appdomain marshaling of objects so // managed exceptions that leak across appdomain boundaries are flatted to // its ToString() output and rethrown as an CrossAppDomainMarshaledException. // The Message field is set to the ToString() output of the original exception. //-------------------------------------------------------------------------- [Serializable] internal sealed class CrossAppDomainMarshaledException : SystemException { public CrossAppDomainMarshaledException(String message, int errorCode) : base(message) { SetErrorCode(errorCode); } // Normally, only Telesto's UEF will see these exceptions. // This override prints out the original Exception's ToString() // output and hides the fact that it is wrapped inside another excepton. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal override String InternalToString() { return Message; } } #endif }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog { using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using NLog.Internal; using NLog.Time; /// <summary> /// TraceListener which routes all messages through NLog. /// </summary> public class NLogTraceListener : TraceListener { private static readonly Assembly systemAssembly = typeof(Trace).Assembly; private LogFactory logFactory; private LogLevel defaultLogLevel = LogLevel.Debug; private bool attributesLoaded; private bool autoLoggerName; private LogLevel forceLogLevel; private bool disableFlush; /// <summary> /// Initializes a new instance of the <see cref="NLogTraceListener"/> class. /// </summary> public NLogTraceListener() { } /// <summary> /// Gets or sets the log factory to use when outputting messages (null - use LogManager). /// </summary> public LogFactory LogFactory { get { this.InitAttributes(); return this.logFactory; } set { this.attributesLoaded = true; this.logFactory = value; } } /// <summary> /// Gets or sets the default log level. /// </summary> public LogLevel DefaultLogLevel { get { this.InitAttributes(); return this.defaultLogLevel; } set { this.attributesLoaded = true; this.defaultLogLevel = value; } } /// <summary> /// Gets or sets the log which should be always used regardless of source level. /// </summary> public LogLevel ForceLogLevel { get { this.InitAttributes(); return this.forceLogLevel; } set { this.attributesLoaded = true; this.forceLogLevel = value; } } /// <summary> /// Gets or sets a value indicating whether flush calls from trace sources should be ignored. /// </summary> public bool DisableFlush { get { this.InitAttributes(); return this.disableFlush; } set { this.attributesLoaded = true; this.disableFlush = value; } } /// <summary> /// Gets a value indicating whether the trace listener is thread safe. /// </summary> /// <value></value> /// <returns>true if the trace listener is thread safe; otherwise, false. The default is false.</returns> public override bool IsThreadSafe { get { return true; } } /// <summary> /// Gets or sets a value indicating whether to use auto logger name detected from the stack trace. /// </summary> public bool AutoLoggerName { get { this.InitAttributes(); return this.autoLoggerName; } set { this.attributesLoaded = true; this.autoLoggerName = value; } } /// <summary> /// When overridden in a derived class, writes the specified message to the listener you create in the derived class. /// </summary> /// <param name="message">A message to write.</param> public override void Write(string message) { this.ProcessLogEventInfo(this.DefaultLogLevel, null, message, null, null, TraceEventType.Resume, null); } /// <summary> /// When overridden in a derived class, writes a message to the listener you create in the derived class, followed by a line terminator. /// </summary> /// <param name="message">A message to write.</param> public override void WriteLine(string message) { this.ProcessLogEventInfo(this.DefaultLogLevel, null, message, null, null, TraceEventType.Resume, null); } /// <summary> /// When overridden in a derived class, closes the output stream so it no longer receives tracing or debugging output. /// </summary> public override void Close() { } /// <summary> /// Emits an error message. /// </summary> /// <param name="message">A message to emit.</param> public override void Fail(string message) { this.ProcessLogEventInfo(LogLevel.Error, null, message, null, null, TraceEventType.Error, null); } /// <summary> /// Emits an error message and a detailed error message. /// </summary> /// <param name="message">A message to emit.</param> /// <param name="detailMessage">A detailed message to emit.</param> public override void Fail(string message, string detailMessage) { this.ProcessLogEventInfo(LogLevel.Error, null, message + " " + detailMessage, null, null, TraceEventType.Error, null); } /// <summary> /// Flushes the output buffer. /// </summary> public override void Flush() { if (!this.DisableFlush) { if (this.LogFactory != null) { this.LogFactory.Flush(); } else { LogManager.Flush(); } } } /// <summary> /// Writes trace information, a data object and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">The trace data to emit.</param> public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { this.TraceData(eventCache, source, eventType, id, new object[] { data }); } /// <summary> /// Writes trace information, an array of data objects and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="data">An array of objects to emit as data.</param> public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { var sb = new StringBuilder(); for (int i = 0; i < data.Length; ++i) { if (i > 0) { sb.Append(", "); } sb.Append("{"); sb.Append(i); sb.Append("}"); } this.ProcessLogEventInfo(TranslateLogLevel(eventType), source, sb.ToString(), data, id, eventType, null); } /// <summary> /// Writes trace and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { this.ProcessLogEventInfo(TranslateLogLevel(eventType), source, string.Empty, null, id, eventType, null); } /// <summary> /// Writes trace information, a formatted array of objects and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="format">A format string that contains zero or more format items, which correspond to objects in the <paramref name="args"/> array.</param> /// <param name="args">An object array containing zero or more objects to format.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { this.ProcessLogEventInfo(TranslateLogLevel(eventType), source, format, args, id, eventType, null); } /// <summary> /// Writes trace information, a message, and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="eventType">One of the <see cref="T:System.Diagnostics.TraceEventType"/> values specifying the type of event that has caused the trace.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="message">A message to write.</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { this.ProcessLogEventInfo(TranslateLogLevel(eventType), source, message, null, id, eventType, null); } /// <summary> /// Writes trace information, a message, a related activity identity and event information to the listener specific output. /// </summary> /// <param name="eventCache">A <see cref="T:System.Diagnostics.TraceEventCache"/> object that contains the current process ID, thread ID, and stack trace information.</param> /// <param name="source">A name used to identify the output, typically the name of the application that generated the trace event.</param> /// <param name="id">A numeric identifier for the event.</param> /// <param name="message">A message to write.</param> /// <param name="relatedActivityId">A <see cref="T:System.Guid"/> object identifying a related activity.</param> public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId) { this.ProcessLogEventInfo(LogLevel.Debug, source, message, null, id, TraceEventType.Transfer, relatedActivityId); } /// <summary> /// Gets the custom attributes supported by the trace listener. /// </summary> /// <returns> /// A string array naming the custom attributes supported by the trace listener, or null if there are no custom attributes. /// </returns> protected override string[] GetSupportedAttributes() { return new[] { "defaultLogLevel", "autoLoggerName", "forceLogLevel", "disableFlush" }; } /// <summary> /// Translates the event type to level from <see cref="TraceEventType"/>. /// </summary> /// <param name="eventType">Type of the event.</param> /// <returns>Translated log level.</returns> private static LogLevel TranslateLogLevel(TraceEventType eventType) { switch (eventType) { case TraceEventType.Verbose: return LogLevel.Trace; case TraceEventType.Information: return LogLevel.Info; case TraceEventType.Warning: return LogLevel.Warn; case TraceEventType.Error: return LogLevel.Error; case TraceEventType.Critical: return LogLevel.Fatal; default: return LogLevel.Debug; } } /// <summary> /// Process the log event /// <param name="logLevel">The log level.</param> /// <param name="loggerName">The name of the logger.</param> /// <param name="message">The log message.</param> /// <param name="arguments">The log parameters.</param> /// <param name="eventId">The event id.</param> /// <param name="eventType">The event type.</param> /// <param name="relatedActiviyId">The related activity id.</param> /// </summary> protected virtual void ProcessLogEventInfo(LogLevel logLevel, string loggerName, [Localizable(false)] string message, object[] arguments, int? eventId, TraceEventType? eventType, Guid? relatedActiviyId) { var ev = new LogEventInfo(); ev.LoggerName = (loggerName ?? this.Name) ?? string.Empty; if (this.AutoLoggerName) { var stack = new StackTrace(); int userFrameIndex = -1; MethodBase userMethod = null; for (int i = 0; i < stack.FrameCount; ++i) { var frame = stack.GetFrame(i); var method = frame.GetMethod(); if (method.DeclaringType == this.GetType()) { // skip all methods of this type continue; } if (method.DeclaringType.Assembly == systemAssembly) { // skip all methods from System.dll continue; } userFrameIndex = i; userMethod = method; break; } if (userFrameIndex >= 0) { ev.SetStackTrace(stack, userFrameIndex); if (userMethod.DeclaringType != null) { ev.LoggerName = userMethod.DeclaringType.FullName; } } } if (eventType.HasValue) { ev.Properties.Add("EventType", eventType.Value); } if (relatedActiviyId.HasValue) { ev.Properties.Add("RelatedActivityID", relatedActiviyId.Value); } ev.TimeStamp = TimeSource.Current.Time; ev.Message = message; ev.Parameters = arguments; ev.Level = this.forceLogLevel ?? logLevel; if (eventId.HasValue) { ev.Properties.Add("EventID", eventId.Value); } ILogger logger; if (this.LogFactory != null) { logger = this.LogFactory.GetLogger(ev.LoggerName); } else { logger = LogManager.GetLogger(ev.LoggerName); } logger.Log(ev); } private void InitAttributes() { if (!this.attributesLoaded) { this.attributesLoaded = true; foreach (DictionaryEntry de in this.Attributes) { var key = (string)de.Key; var value = (string)de.Value; switch (key.ToUpperInvariant()) { case "DEFAULTLOGLEVEL": this.defaultLogLevel = LogLevel.FromString(value); break; case "FORCELOGLEVEL": this.forceLogLevel = LogLevel.FromString(value); break; case "AUTOLOGGERNAME": this.AutoLoggerName = XmlConvert.ToBoolean(value); break; case "DISABLEFLUSH": this.disableFlush = Boolean.Parse(value); break; } } } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography.Pal; using System.Diagnostics; using System.Globalization; namespace System.Security.Cryptography.X509Certificates { public sealed class X509Store : IDisposable { private IStorePal _storePal; public X509Store() : this(StoreName.My, StoreLocation.CurrentUser) { } public X509Store(string storeName) : this(storeName, StoreLocation.CurrentUser) { } public X509Store(StoreName storeName) : this(storeName, StoreLocation.CurrentUser) { } public X509Store(StoreLocation storeLocation) : this(StoreName.My, storeLocation) { } public X509Store(StoreName storeName, StoreLocation storeLocation) { if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeLocation))); switch (storeName) { case StoreName.AddressBook: Name = "AddressBook"; break; case StoreName.AuthRoot: Name = "AuthRoot"; break; case StoreName.CertificateAuthority: Name = "CA"; break; case StoreName.Disallowed: Name = "Disallowed"; break; case StoreName.My: Name = "My"; break; case StoreName.Root: Name = "Root"; break; case StoreName.TrustedPeople: Name = "TrustedPeople"; break; case StoreName.TrustedPublisher: Name = "TrustedPublisher"; break; default: throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeName))); } Location = storeLocation; } public X509Store(StoreName storeName, StoreLocation storeLocation, OpenFlags flags) : this(storeName, storeLocation) { Open(flags); } public X509Store(string storeName, StoreLocation storeLocation) { if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeLocation))); Location = storeLocation; Name = storeName; } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.OpenFlags flags) : this(storeName, storeLocation) { Open(flags); } public X509Store(IntPtr storeHandle) { _storePal = StorePal.FromHandle(storeHandle); Debug.Assert(_storePal != null); } public IntPtr StoreHandle { get { if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); // The Pal layer may return null (Unix) or throw exception (Windows) if (_storePal.SafeHandle == null) return IntPtr.Zero; return _storePal.SafeHandle.DangerousGetHandle(); } } public StoreLocation Location { get; private set; } public string Name { get; private set; } public void Open(OpenFlags flags) { Close(); _storePal = StorePal.FromSystemStore(Name, Location, flags); } public X509Certificate2Collection Certificates { get { X509Certificate2Collection certificates = new X509Certificate2Collection(); if (_storePal != null) { _storePal.CloneTo(certificates); } return certificates; } } public bool IsOpen { get { return _storePal != null; } } public void Add(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); if (certificate.Handle == IntPtr.Zero) throw new CryptographicException(SR.Cryptography_InvalidHandle, "pCertContext"); _storePal.Add(certificate.Pal); } public void AddRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { foreach (X509Certificate2 certificate in certificates) { Add(certificate); i++; } } catch { // For desktop compat, we keep the exception semantics even though they are not ideal // because an exception may cause certs to be removed even if they weren't there before. for (int j = 0; j < i; j++) { Remove(certificates[j]); } throw; } } public void Remove(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); _storePal.Remove(certificate.Pal); } public void RemoveRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { foreach (X509Certificate2 certificate in certificates) { Remove(certificate); i++; } } catch { // For desktop compat, we keep the exception semantics even though they are not ideal // because an exception above may cause certs to be added even if they weren't there before // and an exception here may cause certs not to be re-added. for (int j = 0; j < i; j++) { Add(certificates[j]); } throw; } } public void Dispose() { Close(); } public void Close() { IStorePal storePal = _storePal; _storePal = null; if (storePal != null) { storePal.Dispose(); } } } }
//--------------------------------------------------------------------- // <copyright file="ForeignConstraint.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Generic; using System.Data.Common.Utils; using System.Data.Entity; using System.Data.Mapping.ViewGeneration.QueryRewriting; using System.Data.Mapping.ViewGeneration.Structures; using System.Data.Mapping.ViewGeneration.Utils; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using System.Text; namespace System.Data.Mapping.ViewGeneration.Validation { // An abstraction that captures a foreign key constraint: // <child, columns> --> <parent, columns> internal class ForeignConstraint : InternalBase { #region Constructor // effects: Creates a foreign key constraint of the form: // <i_childTable, i_childColumns> --> <i_parentTable, i_childColumns> // i_fkeySet is the name of the constraint internal ForeignConstraint(AssociationSet i_fkeySet, EntitySet i_parentTable, EntitySet i_childTable, ReadOnlyMetadataCollection<EdmProperty> i_parentColumns, ReadOnlyMetadataCollection<EdmProperty> i_childColumns) { m_fKeySet = i_fkeySet; m_parentTable = i_parentTable; m_childTable = i_childTable; m_childColumns = new List<MemberPath>(); // Create parent and child paths using the table names foreach (EdmProperty property in i_childColumns) { MemberPath path = new MemberPath(m_childTable, property); m_childColumns.Add(path); } m_parentColumns = new List<MemberPath>(); foreach (EdmProperty property in i_parentColumns) { MemberPath path = new MemberPath(m_parentTable, property); m_parentColumns.Add(path); } } #endregion #region Fields private AssociationSet m_fKeySet; // Just for debugging private EntitySet m_parentTable; private EntitySet m_childTable; private List<MemberPath> m_parentColumns; private List<MemberPath> m_childColumns; #endregion #region Properties internal EntitySet ParentTable { get { return m_parentTable; } } internal EntitySet ChildTable { get { return m_childTable; } } internal IEnumerable<MemberPath> ChildColumns { get { return m_childColumns; } } internal IEnumerable<MemberPath> ParentColumns { get { return m_parentColumns; } } #endregion #region Externally available Methods // effects: Given a store-side container, returns all the foreign key // constraints specified for different tables internal static List<ForeignConstraint> GetForeignConstraints(EntityContainer container) { List<ForeignConstraint> foreignKeyConstraints = new List<ForeignConstraint>(); // Go through all the extents and get the associations foreach (EntitySetBase extent in container.BaseEntitySets) { AssociationSet relationSet = extent as AssociationSet; if (relationSet == null) continue; // Keep track of the end to EntitySet mapping Dictionary<string, EntitySet> endToExtents = new Dictionary<string, EntitySet>(); foreach (AssociationSetEnd end in relationSet.AssociationSetEnds) { endToExtents.Add(end.Name, end.EntitySet); } AssociationType relationType = relationSet.ElementType; // Go through each referential constraint, determine the name // of the tables that the constraint refers to and then // create the foreign key constraint between the tables // Wow! We go to great lengths to make it cumbersome for a // programmer to deal with foreign keys foreach (ReferentialConstraint constraint in relationType.ReferentialConstraints) { // Note: We are correlating the constraint's roles with // the ends above using the role names, i.e., // FromRole.Name and ToRole.Name here and end.Role above EntitySet parentExtent = endToExtents[constraint.FromRole.Name]; EntitySet childExtent = endToExtents[constraint.ToRole.Name]; ForeignConstraint foreignKeyConstraint = new ForeignConstraint(relationSet, parentExtent, childExtent, constraint.FromProperties, constraint.ToProperties); foreignKeyConstraints.Add(foreignKeyConstraint); } } return foreignKeyConstraints; } // effects: Checks that this foreign key constraints for all the // tables are being ensured on the C-side as well. If not, adds // errors to the errorLog internal void CheckConstraint(Set<Cell> cells, QueryRewriter childRewriter, QueryRewriter parentRewriter, ErrorLog errorLog, ConfigViewGenerator config) { if (IsConstraintRelevantForCells(cells) == false) { // if the constraint does not deal with any cell in this group, ignore it return; } if (config.IsNormalTracing) { Trace.WriteLine(String.Empty); Trace.WriteLine(String.Empty); Trace.Write("Checking: "); Trace.WriteLine(this); } if (childRewriter == null && parentRewriter == null) { // Neither table is mapped - so we are fine return; } // If the child table has not been mapped, we used to say that we // are fine. However, if we have SPerson(pid) and SAddress(aid, // pid), where pid is an FK into SPerson, we are in trouble if // SAddress is not mapped - SPerson could get deleted. So we // check for it as well // if the parent table is not mapped, we also have a problem if (childRewriter == null) { string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_Missing_Table_Mapping( ToUserString(), ChildTable.Name); // Get the cells from the parent table ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyMissingTableMapping, message, parentRewriter.UsedCells, String.Empty); errorLog.AddEntry(record); return; } if (parentRewriter == null) { string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_Missing_Table_Mapping( ToUserString(), ParentTable.Name); // Get the cells from the child table ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyMissingTableMapping, message, childRewriter.UsedCells, String.Empty); errorLog.AddEntry(record); return; } // Note: we do not check if the parent columns correspond to the // table's keys - metadata checks for that //First check if the FK is covered by Foreign Key Association //If we find this, we don't need to check for independent associations. If user maps the Fk to both FK and independent associations, //the regular round tripping validation will catch the error. if (CheckIfConstraintMappedToForeignKeyAssociation(childRewriter, parentRewriter, cells, errorLog)) { return; } // Check if the foreign key in the child table corresponds to the primary key, i.e., if // the foreign key (e.g., pid, pid2) is a superset of the actual key members (e.g., pid), it means // that the foreign key is also the primary key for this table -- so we can propagate the queries upto C-Space // rather than doing the cell check int initialErrorLogSize = errorLog.Count; if (IsForeignKeySuperSetOfPrimaryKeyInChildTable()) { GuaranteeForeignKeyConstraintInCSpace(childRewriter, parentRewriter, errorLog, config); } else { GuaranteeMappedRelationshipForForeignKey(childRewriter, parentRewriter, cells, errorLog, config); } if (initialErrorLogSize == errorLog.Count) { // Check if the order of columns in foreign key correponds to the // mappings in m_cellGroup, e.g., if <pid1, pid2> in SAddress is // a foreign key into <pid1, pid2> of the SPerson table, make // sure that this order is preserved through the mappings in m_cellGroup CheckForeignKeyColumnOrder(cells, errorLog); } } #endregion #region Methods (mostly) for Query Containment Check via Keys // requires: constraint.ChildColumns form a key in // constraint.ChildTable (actually they should subsume the primary key) private void GuaranteeForeignKeyConstraintInCSpace(QueryRewriter childRewriter, QueryRewriter parentRewriter, ErrorLog errorLog, ConfigViewGenerator config) { ViewgenContext childContext = childRewriter.ViewgenContext; ViewgenContext parentContext = parentRewriter.ViewgenContext; CellTreeNode cNode = childRewriter.BasicView; CellTreeNode pNode = parentRewriter.BasicView; FragmentQueryProcessor qp = FragmentQueryProcessor.Merge(childContext.RightFragmentQP, parentContext.RightFragmentQP); bool cImpliesP = qp.IsContainedIn(cNode.RightFragmentQuery, pNode.RightFragmentQuery); if (false == cImpliesP) { // Foreign key constraint not being ensured in C-space string childExtents = LeftCellWrapper.GetExtentListAsUserString(cNode.GetLeaves()); string parentExtents = LeftCellWrapper.GetExtentListAsUserString(pNode.GetLeaves()); string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_Not_Guaranteed_InCSpace( ToUserString()); // Add all wrappers into allWrappers Set<LeftCellWrapper> allWrappers = new Set<LeftCellWrapper>(pNode.GetLeaves()); allWrappers.AddRange(cNode.GetLeaves()); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyNotGuaranteedInCSpace, message, allWrappers, String.Empty); errorLog.AddEntry(record); } } #endregion #region Methods for Foreign Keys mapped to association // effects: Ensures that there is a relationship mapped into the C-space for some cell in m_cellGroup. Else // adds an error to errorLog private void GuaranteeMappedRelationshipForForeignKey(QueryRewriter childRewriter, QueryRewriter parentRewriter, IEnumerable<Cell> cells, ErrorLog errorLog, ConfigViewGenerator config) { ViewgenContext childContext = childRewriter.ViewgenContext; ViewgenContext parentContext = parentRewriter.ViewgenContext; // Find a cell where this foreign key is mapped as a relationship MemberPath prefix = new MemberPath(ChildTable); ExtentKey primaryKey = ExtentKey.GetPrimaryKeyForEntityType(prefix, ChildTable.ElementType); IEnumerable<MemberPath> primaryKeyFields = primaryKey.KeyFields; bool foundCell = false; bool foundValidParentColumnsForForeignKey = false; //we need to find only one, dont error on any one check being false List<ErrorLog.Record> errorListForInvalidParentColumnsForForeignKey = null; foreach (Cell cell in cells) { if (cell.SQuery.Extent.Equals(ChildTable) == false) { continue; } // The childtable is mapped to a relationship in the C-space in cell // Check that all the columns of the foreign key and the primary key in the child table are mapped to some // property in the C-space AssociationEndMember parentEnd = GetRelationEndForColumns(cell, ChildColumns); if (parentEnd != null && CheckParentColumnsForForeignKey(cell, cells, parentEnd, ref errorListForInvalidParentColumnsForForeignKey) == false) { // Not an error unless we find no valid case continue; } else { foundValidParentColumnsForForeignKey = true; } AssociationEndMember childEnd = GetRelationEndForColumns(cell, primaryKeyFields); Debug.Assert(childEnd == null || parentEnd != childEnd, "Ends are same => PKey and child columns are same - code should gone to other method"); // Note: If both of them are not-null, they are mapped to the // same association set -- since we checked that particular cell if (childEnd != null && parentEnd != null && FindEntitySetForColumnsMappedToEntityKeys(cells, primaryKeyFields) != null) { foundCell = true; CheckConstraintWhenParentChildMapped(cell, errorLog, parentEnd, config); break; // Done processing for the foreign key - either it was mapped correctly or it was not } else if (parentEnd != null) { // At this point, we know cell corresponds to an association set AssociationSet assocSet = (AssociationSet)cell.CQuery.Extent; EntitySet parentSet = MetadataHelper.GetEntitySetAtEnd(assocSet, parentEnd); foundCell = CheckConstraintWhenOnlyParentMapped(cell, parentSet, assocSet, parentEnd, childRewriter, parentRewriter, config); if (foundCell) { break; } } } //CheckParentColumnsForForeignKey has returned no matches, Error. if (!foundValidParentColumnsForForeignKey) { Debug.Assert(errorListForInvalidParentColumnsForForeignKey != null && errorListForInvalidParentColumnsForForeignKey.Count > 0); foreach (var errorRecord in errorListForInvalidParentColumnsForForeignKey) { errorLog.AddEntry(errorRecord); } return; } if (foundCell == false) { // No cell found -- Declare error string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_Missing_Relationship_Mapping(ToUserString()); IEnumerable<LeftCellWrapper> parentWrappers = GetWrappersFromContext(parentContext, ParentTable); IEnumerable<LeftCellWrapper> childWrappers = GetWrappersFromContext(childContext, ChildTable); Set<LeftCellWrapper> bothExtentWrappers = new Set<LeftCellWrapper>(parentWrappers); bothExtentWrappers.AddRange(childWrappers); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyMissingRelationshipMapping, message, bothExtentWrappers, String.Empty); errorLog.AddEntry(record); } } private bool CheckIfConstraintMappedToForeignKeyAssociation(QueryRewriter childRewriter, QueryRewriter parentRewriter, Set<Cell> cells, ErrorLog errorLog) { ViewgenContext childContext = childRewriter.ViewgenContext; ViewgenContext parentContext = parentRewriter.ViewgenContext; //First collect the sets of properties that the principal and dependant ends of this FK //are mapped to in the Edm side. var childPropertiesSet = new List<Set<EdmProperty>>(); var parentPropertiesSet = new List<Set<EdmProperty>>(); foreach (Cell cell in cells) { if (cell.CQuery.Extent.BuiltInTypeKind != BuiltInTypeKind.AssociationSet) { var childProperties = cell.GetCSlotsForTableColumns(ChildColumns); if ( (childProperties != null) && (childProperties.Count != 0)) { childPropertiesSet.Add(childProperties); } var parentProperties = cell.GetCSlotsForTableColumns(ParentColumns); if ((parentProperties != null) && (parentProperties.Count != 0)) { parentPropertiesSet.Add(parentProperties); } } } //Now Check if the properties on the Edm side are connected via an FK relationship. if ((childPropertiesSet.Count != 0) && (parentPropertiesSet.Count != 0)) { var foreignKeyAssociations = childContext.EntityContainerMapping.EdmEntityContainer.BaseEntitySets.OfType<AssociationSet>().Where(it => it.ElementType.IsForeignKey).Select(it => it.ElementType); foreach (AssociationType association in foreignKeyAssociations) { ReferentialConstraint refConstraint = association.ReferentialConstraints.FirstOrDefault(); //We need to check to see if the dependent properties that were mapped from S side are present as //dependant properties of this ref constraint on the Edm side. We need to do the same for principal side but //we can not enforce equality since the order of the properties participating in the constraint on the S side and //C side could be different. This is OK as long as they are mapped appropriately. We also can not use Existance as a sufficient //condition since it will allow invalid mapping where FK columns could have been flipped when mapping to the Edm side. So //we make sure that the index of the properties in the principal and dependant are same on the Edm side even if they are in //different order for ref constraints for Edm and store side. var childRefPropertiesCollection = childPropertiesSet.Where(it => it.SetEquals(new Set<EdmProperty>(refConstraint.ToProperties))); var parentRefPropertiesCollection = parentPropertiesSet.Where(it => it.SetEquals(new Set<EdmProperty>(refConstraint.FromProperties))); if ((childRefPropertiesCollection.Count() != 0 && parentRefPropertiesCollection.Count() != 0)) { foreach (var parentRefProperties in parentRefPropertiesCollection) { var parentIndexes = GetPropertyIndexes(parentRefProperties, refConstraint.FromProperties); foreach (var childRefProperties in childRefPropertiesCollection) { var childIndexes = GetPropertyIndexes(childRefProperties, refConstraint.ToProperties); if (childIndexes.SequenceEqual(parentIndexes)) { return true; } } } } } } return false; } //Return a set of integers that represent the indexes of first set of properties in the second set private Set<int> GetPropertyIndexes(IEnumerable<EdmProperty> properties1, ReadOnlyMetadataCollection<EdmProperty> properties2) { var propertyIndexes = new Set<int>(); foreach (var prop in properties1) { propertyIndexes.Add(properties2.IndexOf(prop)); } return propertyIndexes; } // requires: IsForeignKeySuperSetOfPrimaryKeyInChildTable() is false // and primaryKeys of ChildTable are not mapped in cell. cell // corresponds to an association set. parentSet is the set // corresponding to the end that we are looking at // effects: Checks if the constraint is correctly maintained in // C-space via an association set (being a subset of the // corresponding entitySet) private bool CheckConstraintWhenOnlyParentMapped(Cell cell, EntitySet parentSet, AssociationSet assocSet, AssociationEndMember endMember, QueryRewriter childRewriter, QueryRewriter parentRewriter, ConfigViewGenerator config) { ViewgenContext childContext = childRewriter.ViewgenContext; ViewgenContext parentContext = parentRewriter.ViewgenContext; CellTreeNode pNode = parentRewriter.BasicView; Debug.Assert(pNode != null); RoleBoolean endRoleBoolean = new RoleBoolean(assocSet.AssociationSetEnds[endMember.Name]); // use query in pNode as a factory to create a bool expression for the endRoleBoolean BoolExpression endCondition = pNode.RightFragmentQuery.Condition.Create(endRoleBoolean); FragmentQuery cNodeQuery = FragmentQuery.Create(pNode.RightFragmentQuery.Attributes, endCondition); FragmentQueryProcessor qp = FragmentQueryProcessor.Merge(childContext.RightFragmentQP, parentContext.RightFragmentQP); bool cImpliesP = qp.IsContainedIn(cNodeQuery, pNode.RightFragmentQuery); return cImpliesP; } // requires: IsForeignKeySuperSetOfPrimaryKeyInChildTable() is false // effects: Given that both the ChildColumns in this and the // primaryKey of ChildTable are mapped. Return true iff no error occurred private bool CheckConstraintWhenParentChildMapped(Cell cell, ErrorLog errorLog, AssociationEndMember parentEnd, ConfigViewGenerator config) { bool ok = true; // The foreign key constraint has been mapped to a // relationship. Check if the multiplicities are consistent // If all columns in the child table (corresponding to // the constraint) are nullable, the parent end can be // 0..1 or 1..1. Else if must be 1..1 if (parentEnd.RelationshipMultiplicity == RelationshipMultiplicity.Many) { // Parent should at most one since we are talking // about foreign keys here string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_UpperBound_MustBeOne(ToUserString(), cell.CQuery.Extent.Name, parentEnd.Name); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyUpperBoundMustBeOne, message, cell, String.Empty); errorLog.AddEntry(record); ok = false; } if (MemberPath.AreAllMembersNullable(ChildColumns) == false && parentEnd.RelationshipMultiplicity != RelationshipMultiplicity.One) { // Some column in the constraint in the child table // is non-nullable and lower bound is not 1 string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_LowerBound_MustBeOne(ToUserString(), cell.CQuery.Extent.Name, parentEnd.Name); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyLowerBoundMustBeOne, message, cell, String.Empty); errorLog.AddEntry(record); ok = false; } if (config.IsNormalTracing && ok) { Trace.WriteLine("Foreign key mapped to relationship " + cell.CQuery.Extent.Name); } return ok; } // effects: Given the foreign key constraint, checks if the // constraint.ParentColumns are mapped to the entity set E'e keys in // C-space where E corresponds to the entity set corresponding to end // Returns true iff such a mapping exists in cell private bool CheckParentColumnsForForeignKey(Cell cell, IEnumerable<Cell> cells, AssociationEndMember parentEnd, ref List<ErrorLog.Record> errorList) { // The child columns are mapped to some end of cell.CQuery.Extent. ParentColumns // must correspond to the EntitySet for this end AssociationSet relationSet = (AssociationSet)cell.CQuery.Extent; EntitySet endSet = MetadataHelper.GetEntitySetAtEnd(relationSet, parentEnd); // Check if the ParentColumns are mapped to endSet's keys // Find the entity set that they map to - if any EntitySet entitySet = FindEntitySetForColumnsMappedToEntityKeys(cells, ParentColumns); if (entitySet == null || endSet.Equals(entitySet) == false) { if (errorList == null) //lazily initialize only if there is an error { errorList = new List<ErrorLog.Record>(); } // childColumns are mapped to parentEnd but ParentColumns are not mapped to the end // corresponding to the parentEnd -- this is an error string message = System.Data.Entity.Strings.ViewGen_Foreign_Key_ParentTable_NotMappedToEnd( ToUserString(), ChildTable.Name, cell.CQuery.Extent.Name, parentEnd.Name, ParentTable.Name, endSet.Name); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyParentTableNotMappedToEnd, message, cell, String.Empty); errorList.Add(record); return false; } return true; } #endregion #region Static Helper Methods // effects: Returns the entity set to which tableFields are mapped // and if the mapped fields correspond precisely to the entity set's // keys. Else returns null private static EntitySet FindEntitySetForColumnsMappedToEntityKeys(IEnumerable<Cell> cells, IEnumerable<MemberPath> tableColumns) { foreach (Cell cell in cells) { CellQuery cQuery = cell.CQuery; if (cQuery.Extent is AssociationSet) { continue; } Set<EdmProperty> cSideMembers = cell.GetCSlotsForTableColumns(tableColumns); if (cSideMembers == null) { continue; } // Now check if these fields correspond to the key fields of // the entity set EntitySet entitySet = cQuery.Extent as EntitySet; // Construct a List<EdmMember> List<EdmProperty> propertyList = new List<EdmProperty>(); foreach (EdmProperty property in entitySet.ElementType.KeyMembers) { propertyList.Add(property); } Set<EdmProperty> keyMembers = new Set<EdmProperty>(propertyList).MakeReadOnly(); if (keyMembers.SetEquals(cSideMembers)) { return entitySet; } } return null; } // effects: Returns the end to which columns are exactly mapped in the // relationship set given by cell.CQuery.Extent -- if this extent is // an entityset returns null. If the columns are not mapped in this cell to an // end exactly or columns are not projected in cell, returns null private static AssociationEndMember GetRelationEndForColumns(Cell cell, IEnumerable<MemberPath> columns) { if (cell.CQuery.Extent is EntitySet) { return null; } AssociationSet relationSet = (AssociationSet)cell.CQuery.Extent; // Go through all the ends and see if they are mapped in this cell foreach (AssociationSetEnd relationEnd in relationSet.AssociationSetEnds) { AssociationEndMember endMember = relationEnd.CorrespondingAssociationEndMember; MemberPath prefix = new MemberPath(relationSet, endMember); // Note: primaryKey is the key for the entity set but // prefixed with the relationship's path - we are trying to // check if the entity's keys are mapped in this cell as an end ExtentKey primaryKey = ExtentKey.GetPrimaryKeyForEntityType(prefix, relationEnd.EntitySet.ElementType); // Check if this end is mapped in this cell -- we are // checking on the C-side -- we get all the indexes of the // end's keyfields List<int> endIndexes = cell.CQuery.GetProjectedPositions(primaryKey.KeyFields); if (endIndexes != null) { // Get all the slots corresponding to the columns // But stick to the slots with in these ends since the same column might be //projected twice in different ends List<int> columnIndexes = cell.SQuery.GetProjectedPositions(columns, endIndexes); if (columnIndexes == null) { continue; // columns are not projected with in this end } // Note that the positions need not match exactly - we have a // separate test that will do that for us: CheckForeignKeyColumnOrder if (Helpers.IsSetEqual(columnIndexes, endIndexes, EqualityComparer<int>.Default)) { // The columns map exactly to this end -- return it return endMember; } } } return null; } // effects: Returns wrappers for extent if there are some available in the context. Else returns an empty enumeration private static List<LeftCellWrapper> GetWrappersFromContext(ViewgenContext context, EntitySetBase extent) { List<LeftCellWrapper> wrappers; if (context == null) { wrappers = new List<LeftCellWrapper>(); } else { Debug.Assert(context.Extent.Equals(extent), "ViewgenContext extent and expected extent different"); wrappers = context.AllWrappersForExtent; } return wrappers; } #endregion #region Regular Helper Methods // requires: all columns in constraint.ParentColumns and // constraint.ChildColumns must have been mapped in some cell in m_cellGroup // effects: Given the foreign key constraint, checks if the // constraint.ChildColumns are mapped to the constraint.ParentColumns // in m_cellGroup in the right oder. If not, adds an error to m_errorLog and returns // false. Else returns true private bool CheckForeignKeyColumnOrder(Set<Cell> cells, ErrorLog errorLog) { // Go through every cell and find the cells that are relevant to // parent and those that are relevant to child // Then for each cell pair (parent, child) make sure that the // projected foreign keys columns in C-space are aligned List<Cell> parentCells = new List<Cell>(); List<Cell> childCells = new List<Cell>(); foreach (Cell cell in cells) { if (cell.SQuery.Extent.Equals(ChildTable)) { childCells.Add(cell); } if (cell.SQuery.Extent.Equals(ParentTable)) { parentCells.Add(cell); } } // Make sure that all child cells and parent cells align on // the columns, i.e., for each DISTINCT pair C and P, get the columns // on the S-side. Then get the corresponding fields on the // C-side. The fields on the C-side should match bool foundParentCell = false; bool foundChildCell = false; foreach (Cell childCell in childCells) { List<List<int>> allChildSlotNums = GetSlotNumsForColumns(childCell, ChildColumns); if (allChildSlotNums.Count == 0) { // slots in present in S-side, ignore continue; } List<MemberPath> childPaths = null; List<MemberPath> parentPaths = null; Cell errorParentCell = null; foreach (List<int> childSlotNums in allChildSlotNums) { foundChildCell = true; // Get the fields on the C-side childPaths = new List<MemberPath>(childSlotNums.Count); foreach (int childSlotNum in childSlotNums) { // Initial slots only have JoinTreeSlots MemberProjectedSlot childSlot = (MemberProjectedSlot)childCell.CQuery.ProjectedSlotAt(childSlotNum); Debug.Assert(childSlot != null); childPaths.Add(childSlot.MemberPath); } foreach (Cell parentCell in parentCells) { List<List<int>> allParentSlotNums = GetSlotNumsForColumns(parentCell, ParentColumns); if (allParentSlotNums.Count == 0) { // * Parent and child cell are the same - we do not // need to check since we want to check the foreign // key constraint mapping across cells // * Some slots not in present in S-side, ignore continue; } foreach (List<int> parentSlotNums in allParentSlotNums) { foundParentCell = true; parentPaths = new List<MemberPath>(parentSlotNums.Count); foreach (int parentSlotNum in parentSlotNums) { MemberProjectedSlot parentSlot = (MemberProjectedSlot)parentCell.CQuery.ProjectedSlotAt(parentSlotNum); Debug.Assert(parentSlot != null); parentPaths.Add(parentSlot.MemberPath); } // Make sure that the last member of each of these is the same // or the paths are essentially equivalent via referential constraints // We need to check that the last member is essentially the same because it could // be a regular scenario where aid is mapped to PersonAddress and Address - there // is no ref constraint. So when projected into C-Space, we will get Address.aid // and PersonAddress.Address.aid if (childPaths.Count == parentPaths.Count) { bool notAllPathsMatched = false; for (int i = 0; i < childPaths.Count && !notAllPathsMatched; i++) { MemberPath parentPath = parentPaths[i]; MemberPath childPath = childPaths[i]; if (!parentPath.LeafEdmMember.Equals(childPath.LeafEdmMember)) //Child path did not match { if (parentPath.IsEquivalentViaRefConstraint(childPath)) { //Specifying the referential constraint once in the C space should be enough. //This is the only way possible today. //We might be able to derive more knowledge by using boolean logic return true; } else { notAllPathsMatched = true; } } } if (!notAllPathsMatched) { return true; //all childPaths matched parentPaths } else { //If not this one, some other Parent Cell may match. errorParentCell = parentCell; } } } } //foreach parentCell } //If execution is at this point, no parent cell's end has matched (otherwise it would have returned true) Debug.Assert(childPaths != null, "child paths should be set"); Debug.Assert(parentPaths != null, "parent paths should be set"); Debug.Assert(errorParentCell != null, "errorParentCell should be set"); // using EntityRes. instead of Strings. because the generated method includes 6 instead of 9 parameters string message = EntityRes.GetString(EntityRes.ViewGen_Foreign_Key_ColumnOrder_Incorrect, ToUserString(), MemberPath.PropertiesToUserString(ChildColumns, false), ChildTable.Name, MemberPath.PropertiesToUserString(childPaths, false), childCell.CQuery.Extent.Name, MemberPath.PropertiesToUserString(ParentColumns, false), ParentTable.Name, MemberPath.PropertiesToUserString(parentPaths, false), errorParentCell.CQuery.Extent.Name); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.ForeignKeyColumnOrderIncorrect, message, new Cell[] { errorParentCell, childCell }, String.Empty); errorLog.AddEntry(record); return false; } Debug.Assert(foundParentCell == true, "Some cell that mapped the parent's key must be present!"); Debug.Assert(foundChildCell == true, "Some cell that mapped the child's foreign key must be present according to the requires clause!"); return true; } private static List<List<int>> GetSlotNumsForColumns(Cell cell, IEnumerable<MemberPath> columns) { List<List<int>> slotNums = new List<List<int>>(); AssociationSet set = cell.CQuery.Extent as AssociationSet; //If it is an association set, the columns could be projected //in either end so get the slotNums from both the ends if (set != null) { foreach (AssociationSetEnd setEnd in set.AssociationSetEnds) { List<int> endSlots = cell.CQuery.GetAssociationEndSlots(setEnd.CorrespondingAssociationEndMember); Debug.Assert(endSlots.Count > 0); List<int> localslotNums = cell.SQuery.GetProjectedPositions(columns, endSlots); if (localslotNums != null) { slotNums.Add(localslotNums); } } } else { List<int> localslotNums = cell.SQuery.GetProjectedPositions(columns); if (localslotNums != null) { slotNums.Add(localslotNums); } } return slotNums; } // effects: Returns true iff the foreign keys "cover" the primary key // in the child table, e.g., <k1, k2> covers <k2> (if k2 is the key // of the child table) private bool IsForeignKeySuperSetOfPrimaryKeyInChildTable() { bool isForeignKeySuperSet = true; foreach (EdmProperty keyMember in m_childTable.ElementType.KeyMembers) { // Look for this member in the foreign key members bool memberFound = false; foreach (MemberPath foreignKeyMember in m_childColumns) { // Getting the last member is good enough since it // effectively captures the path (we are not comparing // string names here) if (foreignKeyMember.LeafEdmMember.Equals(keyMember)) { memberFound = true; break; } } if (memberFound == false) { isForeignKeySuperSet = false; break; } } return isForeignKeySuperSet; } // effects: Returns true iff some cell in this refers to the // constraint's parent table or child table private bool IsConstraintRelevantForCells(IEnumerable<Cell> cells) { // if the constraint does not deal with any cell in this group, // return false bool found = false; foreach (Cell cell in cells) { EntitySetBase table = cell.SQuery.Extent; if (table.Equals(m_parentTable) || table.Equals(m_childTable)) { found = true; break; } } return found; } #endregion #region String methods internal string ToUserString() { string childColsString = MemberPath.PropertiesToUserString(m_childColumns, false); string parentColsString = MemberPath.PropertiesToUserString(m_parentColumns, false); string result = System.Data.Entity.Strings.ViewGen_Foreign_Key(m_fKeySet.Name, m_childTable.Name, childColsString, m_parentTable.Name, parentColsString); return result; } internal override void ToCompactString(StringBuilder builder) { builder.Append(m_fKeySet.Name + ": "); builder.Append(ToUserString()); } #endregion } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using Glass.Mapper.Sc.DataMappers; using Glass.Mapper.Sc.IoC; using NSubstitute; using NUnit.Framework; using Sitecore.Data; using Sitecore.FakeDb; using Image = Glass.Mapper.Sc.Fields.Image; namespace Glass.Mapper.Sc.FakeDb.DataMappers { [TestFixture] public class SitecoreFieldImageMapperFixture { protected const string FieldName = "Field"; #region Method - GetField [Test] public void GetField_ImageInField_ReturnsImageObject() { //Assign var fieldValue = "<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" mediapath=\"/Files/20121222_001405\" src=\"~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx\" hspace=\"15\" vspace=\"20\" />"; var mediaId = new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"); using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } }, new Sitecore.FakeDb.DbItem("MediaItem", mediaId) { new DbField("alt") {Value = "test alt"}, new DbField("height") {Value = "480"}, new DbField("width") {Value = "640"}, } }) { Sitecore.Resources.Media.MediaProvider mediaProvider = Substitute.For<Sitecore.Resources.Media.MediaProvider>(); mediaProvider .GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId)) .Returns("/~/media/Test.ashx"); using (new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider)) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldImageMapper(); //Act var result = mapper.GetField(field, null, null) as Image; //Assert Assert.AreEqual("test alt", result.Alt); // Assert.Equals(null, result.Border); Assert.AreEqual(string.Empty, result.Class); Assert.AreEqual(15, result.HSpace); Assert.AreEqual(480, result.Height); Assert.AreEqual(new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), result.MediaId); Assert.IsTrue(result.Src.EndsWith("/~/media/Test.ashx")); Assert.AreEqual(20, result.VSpace); Assert.AreEqual(640, result.Width); } } } [Test] public void GetField_ImageFieldEmpty_ReturnsNull() { //Assign var fieldValue = string.Empty; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var context = Context.Create(new DependencyResolver(new Config())); var service = new SitecoreService(database.Database, context); //Act var result = service.GetItem<StubImage>("/sitecore/content/TestItem"); //Assert Assert.IsNull(result.Field); } } [Test] public void GetField_FieldIsEmpty_ReturnsNullImageObject() { //Assign var fieldValue = string.Empty; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldImageMapper(); var service = Substitute.For<ISitecoreService>(); service.Config = new Config(); var context = new SitecoreDataMappingContext(null, null, service); //Act var result = mapper.GetField(field, null, context) as Image; //Assert Assert.IsNull(result); } } [Test] public void GetField_FieldIsNull_ReturnsNullImageObject() { //Assign string fieldValue = null; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldImageMapper(); var service = Substitute.For<ISitecoreService>(); service.Config = new Config(); var context = new SitecoreDataMappingContext(null, null, service); //Act var result = mapper.GetField(field, null, context) as Image; //Assert Assert.IsNull(result); } } #endregion #region Method - SetField [Test] public void SetField_ImagePassed_ReturnsPopulatedField() { //Assign var expected = "<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" width=\"640\" vspace=\"50\" height=\"480\" hspace=\"30\" alt=\"test alt\" />"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) }, new Sitecore.FakeDb.DbItem("MediaItem", new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}")) }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldImageMapper(); var image = new Image() { Alt = "test alt", HSpace = 30, Height = 480, MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), VSpace = 50, Width = 640, Border = String.Empty, Class = String.Empty }; using (new ItemEditing(item, true)) { field.Value = string.Empty; } //Act using (new ItemEditing(item, true)) { mapper.SetField(field, image, null, null); } //Assert AssertHtml.AreHtmlElementsEqual(expected, field.Value, "image"); } } [Test] public void SetField_JustImageId_ReturnsPopulatedField() { //Assign var expected = "<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" />"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) }, new Sitecore.FakeDb.DbItem("MediaItem", new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}")) }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldImageMapper(); var image = new Image() { MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), }; using (new ItemEditing(item, true)) { field.Value = string.Empty; } //Act using (new ItemEditing(item, true)) { mapper.SetField(field, image, null, null); } //Assert AssertHtml.AreHtmlElementsEqual(expected, field.Value, "image"); } } #endregion #region Stubs public class StubImage { public virtual Image Field { get; set; } } #endregion } }
namespace android.app { [global::MonoJavaBridge.JavaClass()] public partial class Activity : android.view.ContextThemeWrapper, android.view.LayoutInflater.Factory, android.view.Window.Callback, android.view.KeyEvent.Callback, android.view.View.OnCreateContextMenuListener, android.content.ComponentCallbacks { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Activity(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } public new global::android.app.Activity Parent { get { return getParent(); } } private static global::MonoJavaBridge.MethodId _m0; public virtual global::android.app.Activity getParent() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getParent", "()Landroid/app/Activity;", ref global::android.app.Activity._m0) as android.app.Activity; } public new global::android.app.Application Application { get { return getApplication(); } } private static global::MonoJavaBridge.MethodId _m1; public virtual global::android.app.Application getApplication() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getApplication", "()Landroid/app/Application;", ref global::android.app.Activity._m1) as android.app.Application; } private static global::MonoJavaBridge.MethodId _m2; protected virtual void onCreate(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onCreate", "(Landroid/os/Bundle;)V", ref global::android.app.Activity._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; protected virtual void onStart() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onStart", "()V", ref global::android.app.Activity._m3); } private static global::MonoJavaBridge.MethodId _m4; protected virtual void onDestroy() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onDestroy", "()V", ref global::android.app.Activity._m4); } private static global::MonoJavaBridge.MethodId _m5; public virtual void onConfigurationChanged(android.content.res.Configuration arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onConfigurationChanged", "(Landroid/content/res/Configuration;)V", ref global::android.app.Activity._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void onLowMemory() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onLowMemory", "()V", ref global::android.app.Activity._m6); } public new int WallpaperDesiredMinimumWidth { get { return getWallpaperDesiredMinimumWidth(); } } private static global::MonoJavaBridge.MethodId _m7; public override int getWallpaperDesiredMinimumWidth() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getWallpaperDesiredMinimumWidth", "()I", ref global::android.app.Activity._m7); } public new int WallpaperDesiredMinimumHeight { get { return getWallpaperDesiredMinimumHeight(); } } private static global::MonoJavaBridge.MethodId _m8; public override int getWallpaperDesiredMinimumHeight() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getWallpaperDesiredMinimumHeight", "()I", ref global::android.app.Activity._m8); } private static global::MonoJavaBridge.MethodId _m9; public override void startActivity(android.content.Intent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startActivity", "(Landroid/content/Intent;)V", ref global::android.app.Activity._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m10; public override void startIntentSender(android.content.IntentSender arg0, android.content.Intent arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startIntentSender", "(Landroid/content/IntentSender;Landroid/content/Intent;III)V", ref global::android.app.Activity._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m11; public override global::java.lang.Object getSystemService(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", ref global::android.app.Activity._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } public new global::android.content.Intent Intent { get { return getIntent(); } set { setIntent(value); } } private static global::MonoJavaBridge.MethodId _m12; public virtual global::android.content.Intent getIntent() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getIntent", "()Landroid/content/Intent;", ref global::android.app.Activity._m12) as android.content.Intent; } public new int ChangingConfigurations { get { return getChangingConfigurations(); } } private static global::MonoJavaBridge.MethodId _m13; public virtual int getChangingConfigurations() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getChangingConfigurations", "()I", ref global::android.app.Activity._m13); } public new bool Visible { set { setVisible(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual void setVisible(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setVisible", "(Z)V", ref global::android.app.Activity._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Result { set { setResult(value); } } private static global::MonoJavaBridge.MethodId _m15; public virtual void setResult(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setResult", "(I)V", ref global::android.app.Activity._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setResult(int arg0, android.content.Intent arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setResult", "(ILandroid/content/Intent;)V", ref global::android.app.Activity._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; public virtual void finish() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "finish", "()V", ref global::android.app.Activity._m17); } public static long InstanceCount { get { return getInstanceCount(); } } private static global::MonoJavaBridge.MethodId _m18; public static long getInstanceCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.app.Activity._m18.native == global::System.IntPtr.Zero) global::android.app.Activity._m18 = @__env.GetStaticMethodIDNoThrow(global::android.app.Activity.staticClass, "getInstanceCount", "()J"); return @__env.CallStaticLongMethod(android.app.Activity.staticClass, global::android.app.Activity._m18); } private static global::MonoJavaBridge.MethodId _m19; public virtual void setIntent(android.content.Intent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setIntent", "(Landroid/content/Intent;)V", ref global::android.app.Activity._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public virtual bool isChild() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "isChild", "()Z", ref global::android.app.Activity._m20); } public new global::android.view.WindowManager WindowManager { get { return getWindowManager(); } } private static global::MonoJavaBridge.MethodId _m21; public virtual global::android.view.WindowManager getWindowManager() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.WindowManager>(this, global::android.app.Activity.staticClass, "getWindowManager", "()Landroid/view/WindowManager;", ref global::android.app.Activity._m21) as android.view.WindowManager; } public new global::android.view.Window Window { get { return getWindow(); } } private static global::MonoJavaBridge.MethodId _m22; public virtual global::android.view.Window getWindow() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getWindow", "()Landroid/view/Window;", ref global::android.app.Activity._m22) as android.view.Window; } public new global::android.view.View CurrentFocus { get { return getCurrentFocus(); } } private static global::MonoJavaBridge.MethodId _m23; public virtual global::android.view.View getCurrentFocus() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getCurrentFocus", "()Landroid/view/View;", ref global::android.app.Activity._m23) as android.view.View; } private static global::MonoJavaBridge.MethodId _m24; protected virtual void onRestoreInstanceState(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onRestoreInstanceState", "(Landroid/os/Bundle;)V", ref global::android.app.Activity._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m25; protected virtual void onPostCreate(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onPostCreate", "(Landroid/os/Bundle;)V", ref global::android.app.Activity._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; protected virtual void onRestart() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onRestart", "()V", ref global::android.app.Activity._m26); } private static global::MonoJavaBridge.MethodId _m27; protected virtual void onResume() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onResume", "()V", ref global::android.app.Activity._m27); } private static global::MonoJavaBridge.MethodId _m28; protected virtual void onPostResume() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onPostResume", "()V", ref global::android.app.Activity._m28); } private static global::MonoJavaBridge.MethodId _m29; protected virtual void onNewIntent(android.content.Intent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onNewIntent", "(Landroid/content/Intent;)V", ref global::android.app.Activity._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; protected virtual void onSaveInstanceState(android.os.Bundle arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onSaveInstanceState", "(Landroid/os/Bundle;)V", ref global::android.app.Activity._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; protected virtual void onPause() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onPause", "()V", ref global::android.app.Activity._m31); } private static global::MonoJavaBridge.MethodId _m32; protected virtual void onUserLeaveHint() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onUserLeaveHint", "()V", ref global::android.app.Activity._m32); } private static global::MonoJavaBridge.MethodId _m33; public virtual bool onCreateThumbnail(android.graphics.Bitmap arg0, android.graphics.Canvas arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onCreateThumbnail", "(Landroid/graphics/Bitmap;Landroid/graphics/Canvas;)Z", ref global::android.app.Activity._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m34; public virtual global::java.lang.CharSequence onCreateDescription() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.app.Activity.staticClass, "onCreateDescription", "()Ljava/lang/CharSequence;", ref global::android.app.Activity._m34) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m35; protected virtual void onStop() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onStop", "()V", ref global::android.app.Activity._m35); } public new global::java.lang.Object LastNonConfigurationInstance { get { return getLastNonConfigurationInstance(); } } private static global::MonoJavaBridge.MethodId _m36; public virtual global::java.lang.Object getLastNonConfigurationInstance() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getLastNonConfigurationInstance", "()Ljava/lang/Object;", ref global::android.app.Activity._m36) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m37; public virtual global::java.lang.Object onRetainNonConfigurationInstance() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "onRetainNonConfigurationInstance", "()Ljava/lang/Object;", ref global::android.app.Activity._m37) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m38; public virtual global::android.database.Cursor managedQuery(android.net.Uri arg0, java.lang.String[] arg1, java.lang.String arg2, java.lang.String[] arg3, java.lang.String arg4) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.database.Cursor>(this, global::android.app.Activity.staticClass, "managedQuery", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", ref global::android.app.Activity._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)) as android.database.Cursor; } private static global::MonoJavaBridge.MethodId _m39; public virtual void startManagingCursor(android.database.Cursor arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startManagingCursor", "(Landroid/database/Cursor;)V", ref global::android.app.Activity._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m40; public virtual void stopManagingCursor(android.database.Cursor arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "stopManagingCursor", "(Landroid/database/Cursor;)V", ref global::android.app.Activity._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool Persistent { set { setPersistent(value); } } private static global::MonoJavaBridge.MethodId _m41; public virtual void setPersistent(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setPersistent", "(Z)V", ref global::android.app.Activity._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m42; public virtual global::android.view.View findViewById(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "findViewById", "(I)Landroid/view/View;", ref global::android.app.Activity._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.View; } private static global::MonoJavaBridge.MethodId _m43; public virtual void setContentView(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setContentView", "(I)V", ref global::android.app.Activity._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m44; public virtual void setContentView(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setContentView", "(Landroid/view/View;)V", ref global::android.app.Activity._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m45; public virtual void setContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setContentView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", ref global::android.app.Activity._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m46; public virtual void addContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "addContentView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", ref global::android.app.Activity._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new int DefaultKeyMode { set { setDefaultKeyMode(value); } } private static global::MonoJavaBridge.MethodId _m47; public virtual void setDefaultKeyMode(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setDefaultKeyMode", "(I)V", ref global::android.app.Activity._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m48; public virtual bool onKeyDown(int arg0, android.view.KeyEvent arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z", ref global::android.app.Activity._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m49; public virtual bool onKeyLongPress(int arg0, android.view.KeyEvent arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onKeyLongPress", "(ILandroid/view/KeyEvent;)Z", ref global::android.app.Activity._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m50; public virtual bool onKeyUp(int arg0, android.view.KeyEvent arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z", ref global::android.app.Activity._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m51; public virtual bool onKeyMultiple(int arg0, int arg1, android.view.KeyEvent arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onKeyMultiple", "(IILandroid/view/KeyEvent;)Z", ref global::android.app.Activity._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m52; public virtual void onBackPressed() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onBackPressed", "()V", ref global::android.app.Activity._m52); } private static global::MonoJavaBridge.MethodId _m53; public virtual bool onTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.app.Activity._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m54; public virtual bool onTrackballEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onTrackballEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.app.Activity._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m55; public virtual void onUserInteraction() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onUserInteraction", "()V", ref global::android.app.Activity._m55); } private static global::MonoJavaBridge.MethodId _m56; public virtual void onWindowAttributesChanged(android.view.WindowManager_LayoutParams arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onWindowAttributesChanged", "(Landroid/view/WindowManager$LayoutParams;)V", ref global::android.app.Activity._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m57; public virtual void onContentChanged() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onContentChanged", "()V", ref global::android.app.Activity._m57); } private static global::MonoJavaBridge.MethodId _m58; public virtual void onWindowFocusChanged(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onWindowFocusChanged", "(Z)V", ref global::android.app.Activity._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m59; public virtual void onAttachedToWindow() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onAttachedToWindow", "()V", ref global::android.app.Activity._m59); } private static global::MonoJavaBridge.MethodId _m60; public virtual void onDetachedFromWindow() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onDetachedFromWindow", "()V", ref global::android.app.Activity._m60); } private static global::MonoJavaBridge.MethodId _m61; public virtual bool hasWindowFocus() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "hasWindowFocus", "()Z", ref global::android.app.Activity._m61); } private static global::MonoJavaBridge.MethodId _m62; public virtual bool dispatchKeyEvent(android.view.KeyEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.app.Activity._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m63; public virtual bool dispatchTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "dispatchTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.app.Activity._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m64; public virtual bool dispatchTrackballEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "dispatchTrackballEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.app.Activity._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m65; public virtual bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z", ref global::android.app.Activity._m65, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m66; public virtual global::android.view.View onCreatePanelView(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "onCreatePanelView", "(I)Landroid/view/View;", ref global::android.app.Activity._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.View; } private static global::MonoJavaBridge.MethodId _m67; public virtual bool onCreatePanelMenu(int arg0, android.view.Menu arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onCreatePanelMenu", "(ILandroid/view/Menu;)Z", ref global::android.app.Activity._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m68; public virtual bool onPreparePanel(int arg0, android.view.View arg1, android.view.Menu arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onPreparePanel", "(ILandroid/view/View;Landroid/view/Menu;)Z", ref global::android.app.Activity._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m69; public virtual bool onMenuOpened(int arg0, android.view.Menu arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onMenuOpened", "(ILandroid/view/Menu;)Z", ref global::android.app.Activity._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m70; public virtual bool onMenuItemSelected(int arg0, android.view.MenuItem arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onMenuItemSelected", "(ILandroid/view/MenuItem;)Z", ref global::android.app.Activity._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m71; public virtual void onPanelClosed(int arg0, android.view.Menu arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onPanelClosed", "(ILandroid/view/Menu;)V", ref global::android.app.Activity._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m72; public virtual bool onCreateOptionsMenu(android.view.Menu arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onCreateOptionsMenu", "(Landroid/view/Menu;)Z", ref global::android.app.Activity._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m73; public virtual bool onPrepareOptionsMenu(android.view.Menu arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onPrepareOptionsMenu", "(Landroid/view/Menu;)Z", ref global::android.app.Activity._m73, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m74; public virtual bool onOptionsItemSelected(android.view.MenuItem arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onOptionsItemSelected", "(Landroid/view/MenuItem;)Z", ref global::android.app.Activity._m74, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m75; public virtual void onOptionsMenuClosed(android.view.Menu arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onOptionsMenuClosed", "(Landroid/view/Menu;)V", ref global::android.app.Activity._m75, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m76; public virtual void openOptionsMenu() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "openOptionsMenu", "()V", ref global::android.app.Activity._m76); } private static global::MonoJavaBridge.MethodId _m77; public virtual void closeOptionsMenu() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "closeOptionsMenu", "()V", ref global::android.app.Activity._m77); } private static global::MonoJavaBridge.MethodId _m78; public virtual void onCreateContextMenu(android.view.ContextMenu arg0, android.view.View arg1, android.view.ContextMenu_ContextMenuInfo arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onCreateContextMenu", "(Landroid/view/ContextMenu;Landroid/view/View;Landroid/view/ContextMenu$ContextMenuInfo;)V", ref global::android.app.Activity._m78, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m79; public virtual void registerForContextMenu(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "registerForContextMenu", "(Landroid/view/View;)V", ref global::android.app.Activity._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m80; public virtual void unregisterForContextMenu(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "unregisterForContextMenu", "(Landroid/view/View;)V", ref global::android.app.Activity._m80, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m81; public virtual void openContextMenu(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "openContextMenu", "(Landroid/view/View;)V", ref global::android.app.Activity._m81, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m82; public virtual void closeContextMenu() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "closeContextMenu", "()V", ref global::android.app.Activity._m82); } private static global::MonoJavaBridge.MethodId _m83; public virtual bool onContextItemSelected(android.view.MenuItem arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onContextItemSelected", "(Landroid/view/MenuItem;)Z", ref global::android.app.Activity._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m84; public virtual void onContextMenuClosed(android.view.Menu arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onContextMenuClosed", "(Landroid/view/Menu;)V", ref global::android.app.Activity._m84, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m85; protected virtual global::android.app.Dialog onCreateDialog(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "onCreateDialog", "(I)Landroid/app/Dialog;", ref global::android.app.Activity._m85, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.Dialog; } private static global::MonoJavaBridge.MethodId _m86; protected virtual global::android.app.Dialog onCreateDialog(int arg0, android.os.Bundle arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "onCreateDialog", "(ILandroid/os/Bundle;)Landroid/app/Dialog;", ref global::android.app.Activity._m86, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.Dialog; } private static global::MonoJavaBridge.MethodId _m87; protected virtual void onPrepareDialog(int arg0, android.app.Dialog arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onPrepareDialog", "(ILandroid/app/Dialog;)V", ref global::android.app.Activity._m87, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m88; protected virtual void onPrepareDialog(int arg0, android.app.Dialog arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onPrepareDialog", "(ILandroid/app/Dialog;Landroid/os/Bundle;)V", ref global::android.app.Activity._m88, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m89; public virtual bool showDialog(int arg0, android.os.Bundle arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "showDialog", "(ILandroid/os/Bundle;)Z", ref global::android.app.Activity._m89, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m90; public virtual void showDialog(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "showDialog", "(I)V", ref global::android.app.Activity._m90, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m91; public virtual void dismissDialog(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "dismissDialog", "(I)V", ref global::android.app.Activity._m91, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m92; public virtual void removeDialog(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "removeDialog", "(I)V", ref global::android.app.Activity._m92, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m93; public virtual bool onSearchRequested() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "onSearchRequested", "()Z", ref global::android.app.Activity._m93); } private static global::MonoJavaBridge.MethodId _m94; public virtual void startSearch(java.lang.String arg0, bool arg1, android.os.Bundle arg2, bool arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startSearch", "(Ljava/lang/String;ZLandroid/os/Bundle;Z)V", ref global::android.app.Activity._m94, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m95; public virtual void triggerSearch(java.lang.String arg0, android.os.Bundle arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "triggerSearch", "(Ljava/lang/String;Landroid/os/Bundle;)V", ref global::android.app.Activity._m95, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m96; public virtual void takeKeyEvents(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "takeKeyEvents", "(Z)V", ref global::android.app.Activity._m96, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m97; public virtual bool requestWindowFeature(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "requestWindowFeature", "(I)Z", ref global::android.app.Activity._m97, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m98; public virtual void setFeatureDrawableResource(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setFeatureDrawableResource", "(II)V", ref global::android.app.Activity._m98, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m99; public virtual void setFeatureDrawableUri(int arg0, android.net.Uri arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setFeatureDrawableUri", "(ILandroid/net/Uri;)V", ref global::android.app.Activity._m99, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m100; public virtual void setFeatureDrawable(int arg0, android.graphics.drawable.Drawable arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setFeatureDrawable", "(ILandroid/graphics/drawable/Drawable;)V", ref global::android.app.Activity._m100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m101; public virtual void setFeatureDrawableAlpha(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setFeatureDrawableAlpha", "(II)V", ref global::android.app.Activity._m101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::android.view.LayoutInflater LayoutInflater { get { return getLayoutInflater(); } } private static global::MonoJavaBridge.MethodId _m102; public virtual global::android.view.LayoutInflater getLayoutInflater() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getLayoutInflater", "()Landroid/view/LayoutInflater;", ref global::android.app.Activity._m102) as android.view.LayoutInflater; } public new global::android.view.MenuInflater MenuInflater { get { return getMenuInflater(); } } private static global::MonoJavaBridge.MethodId _m103; public virtual global::android.view.MenuInflater getMenuInflater() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "getMenuInflater", "()Landroid/view/MenuInflater;", ref global::android.app.Activity._m103) as android.view.MenuInflater; } private static global::MonoJavaBridge.MethodId _m104; protected override void onApplyThemeResource(android.content.res.Resources.Theme arg0, int arg1, bool arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onApplyThemeResource", "(Landroid/content/res/Resources$Theme;IZ)V", ref global::android.app.Activity._m104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m105; public virtual void startActivityForResult(android.content.Intent arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startActivityForResult", "(Landroid/content/Intent;I)V", ref global::android.app.Activity._m105, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m106; public virtual void startIntentSenderForResult(android.content.IntentSender arg0, int arg1, android.content.Intent arg2, int arg3, int arg4, int arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startIntentSenderForResult", "(Landroid/content/IntentSender;ILandroid/content/Intent;III)V", ref global::android.app.Activity._m106, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } private static global::MonoJavaBridge.MethodId _m107; public virtual bool startActivityIfNeeded(android.content.Intent arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "startActivityIfNeeded", "(Landroid/content/Intent;I)Z", ref global::android.app.Activity._m107, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m108; public virtual bool startNextMatchingActivity(android.content.Intent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "startNextMatchingActivity", "(Landroid/content/Intent;)Z", ref global::android.app.Activity._m108, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m109; public virtual void startActivityFromChild(android.app.Activity arg0, android.content.Intent arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startActivityFromChild", "(Landroid/app/Activity;Landroid/content/Intent;I)V", ref global::android.app.Activity._m109, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m110; public virtual void startIntentSenderFromChild(android.app.Activity arg0, android.content.IntentSender arg1, int arg2, android.content.Intent arg3, int arg4, int arg5, int arg6) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "startIntentSenderFromChild", "(Landroid/app/Activity;Landroid/content/IntentSender;ILandroid/content/Intent;III)V", ref global::android.app.Activity._m110, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); } private static global::MonoJavaBridge.MethodId _m111; public virtual void overridePendingTransition(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "overridePendingTransition", "(II)V", ref global::android.app.Activity._m111, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::java.lang.String CallingPackage { get { return getCallingPackage(); } } private static global::MonoJavaBridge.MethodId _m112; public virtual global::java.lang.String getCallingPackage() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.app.Activity.staticClass, "getCallingPackage", "()Ljava/lang/String;", ref global::android.app.Activity._m112) as java.lang.String; } public new global::android.content.ComponentName CallingActivity { get { return getCallingActivity(); } } private static global::MonoJavaBridge.MethodId _m113; public virtual global::android.content.ComponentName getCallingActivity() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.content.ComponentName>(this, global::android.app.Activity.staticClass, "getCallingActivity", "()Landroid/content/ComponentName;", ref global::android.app.Activity._m113) as android.content.ComponentName; } private static global::MonoJavaBridge.MethodId _m114; public virtual bool isFinishing() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "isFinishing", "()Z", ref global::android.app.Activity._m114); } private static global::MonoJavaBridge.MethodId _m115; public virtual void finishFromChild(android.app.Activity arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "finishFromChild", "(Landroid/app/Activity;)V", ref global::android.app.Activity._m115, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m116; public virtual void finishActivity(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "finishActivity", "(I)V", ref global::android.app.Activity._m116, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m117; public virtual void finishActivityFromChild(android.app.Activity arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "finishActivityFromChild", "(Landroid/app/Activity;I)V", ref global::android.app.Activity._m117, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m118; protected virtual void onActivityResult(int arg0, int arg1, android.content.Intent arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onActivityResult", "(IILandroid/content/Intent;)V", ref global::android.app.Activity._m118, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m119; public virtual global::android.app.PendingIntent createPendingResult(int arg0, android.content.Intent arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.app.PendingIntent>(this, global::android.app.Activity.staticClass, "createPendingResult", "(ILandroid/content/Intent;I)Landroid/app/PendingIntent;", ref global::android.app.Activity._m119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.PendingIntent; } private static global::MonoJavaBridge.MethodId _m120; public virtual void setRequestedOrientation(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setRequestedOrientation", "(I)V", ref global::android.app.Activity._m120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int RequestedOrientation { get { return getRequestedOrientation(); } set { setRequestedOrientation(value); } } private static global::MonoJavaBridge.MethodId _m121; public virtual int getRequestedOrientation() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getRequestedOrientation", "()I", ref global::android.app.Activity._m121); } public new int TaskId { get { return getTaskId(); } } private static global::MonoJavaBridge.MethodId _m122; public virtual int getTaskId() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getTaskId", "()I", ref global::android.app.Activity._m122); } private static global::MonoJavaBridge.MethodId _m123; public virtual bool isTaskRoot() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "isTaskRoot", "()Z", ref global::android.app.Activity._m123); } private static global::MonoJavaBridge.MethodId _m124; public virtual bool moveTaskToBack(bool arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.Activity.staticClass, "moveTaskToBack", "(Z)Z", ref global::android.app.Activity._m124, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::java.lang.String LocalClassName { get { return getLocalClassName(); } } private static global::MonoJavaBridge.MethodId _m125; public virtual global::java.lang.String getLocalClassName() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.app.Activity.staticClass, "getLocalClassName", "()Ljava/lang/String;", ref global::android.app.Activity._m125) as java.lang.String; } public new global::android.content.ComponentName ComponentName { get { return getComponentName(); } } private static global::MonoJavaBridge.MethodId _m126; public virtual global::android.content.ComponentName getComponentName() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.content.ComponentName>(this, global::android.app.Activity.staticClass, "getComponentName", "()Landroid/content/ComponentName;", ref global::android.app.Activity._m126) as android.content.ComponentName; } private static global::MonoJavaBridge.MethodId _m127; public virtual global::android.content.SharedPreferences getPreferences(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.content.SharedPreferences>(this, global::android.app.Activity.staticClass, "getPreferences", "(I)Landroid/content/SharedPreferences;", ref global::android.app.Activity._m127, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.content.SharedPreferences; } private static global::MonoJavaBridge.MethodId _m128; public virtual void setTitle(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setTitle", "(I)V", ref global::android.app.Activity._m128, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m129; public virtual void setTitle(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setTitle", "(Ljava/lang/CharSequence;)V", ref global::android.app.Activity._m129, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setTitle(string arg0) { setTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0); } private static global::MonoJavaBridge.MethodId _m130; public virtual void setTitleColor(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setTitleColor", "(I)V", ref global::android.app.Activity._m130, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new string Title { get { return getTitle().toString(); } set { setTitle((global::java.lang.CharSequence)(global::java.lang.String)value); } } private static global::MonoJavaBridge.MethodId _m131; public virtual global::java.lang.CharSequence getTitle() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.app.Activity.staticClass, "getTitle", "()Ljava/lang/CharSequence;", ref global::android.app.Activity._m131) as java.lang.CharSequence; } public new int TitleColor { get { return getTitleColor(); } set { setTitleColor(value); } } private static global::MonoJavaBridge.MethodId _m132; public virtual int getTitleColor() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getTitleColor", "()I", ref global::android.app.Activity._m132); } private static global::MonoJavaBridge.MethodId _m133; protected virtual void onTitleChanged(java.lang.CharSequence arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onTitleChanged", "(Ljava/lang/CharSequence;I)V", ref global::android.app.Activity._m133, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } protected void onTitleChanged(string arg0, int arg1) { onTitleChanged((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m134; protected virtual void onChildTitleChanged(android.app.Activity arg0, java.lang.CharSequence arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "onChildTitleChanged", "(Landroid/app/Activity;Ljava/lang/CharSequence;)V", ref global::android.app.Activity._m134, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } protected void onChildTitleChanged(android.app.Activity arg0, string arg1) { onChildTitleChanged(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1); } public new bool ProgressBarVisibility { set { setProgressBarVisibility(value); } } private static global::MonoJavaBridge.MethodId _m135; public virtual void setProgressBarVisibility(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setProgressBarVisibility", "(Z)V", ref global::android.app.Activity._m135, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool ProgressBarIndeterminateVisibility { set { setProgressBarIndeterminateVisibility(value); } } private static global::MonoJavaBridge.MethodId _m136; public virtual void setProgressBarIndeterminateVisibility(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setProgressBarIndeterminateVisibility", "(Z)V", ref global::android.app.Activity._m136, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool ProgressBarIndeterminate { set { setProgressBarIndeterminate(value); } } private static global::MonoJavaBridge.MethodId _m137; public virtual void setProgressBarIndeterminate(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setProgressBarIndeterminate", "(Z)V", ref global::android.app.Activity._m137, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Progress { set { setProgress(value); } } private static global::MonoJavaBridge.MethodId _m138; public virtual void setProgress(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setProgress", "(I)V", ref global::android.app.Activity._m138, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int SecondaryProgress { set { setSecondaryProgress(value); } } private static global::MonoJavaBridge.MethodId _m139; public virtual void setSecondaryProgress(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setSecondaryProgress", "(I)V", ref global::android.app.Activity._m139, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m140; public virtual void setVolumeControlStream(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "setVolumeControlStream", "(I)V", ref global::android.app.Activity._m140, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int VolumeControlStream { get { return getVolumeControlStream(); } set { setVolumeControlStream(value); } } private static global::MonoJavaBridge.MethodId _m141; public virtual int getVolumeControlStream() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.app.Activity.staticClass, "getVolumeControlStream", "()I", ref global::android.app.Activity._m141); } private static global::MonoJavaBridge.MethodId _m142; public virtual void runOnUiThread(java.lang.Runnable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.Activity.staticClass, "runOnUiThread", "(Ljava/lang/Runnable;)V", ref global::android.app.Activity._m142, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void runOnUiThread(global::java.lang.RunnableDelegate arg0) { runOnUiThread((global::java.lang.RunnableDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m143; public virtual global::android.view.View onCreateView(java.lang.String arg0, android.content.Context arg1, android.util.AttributeSet arg2) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.Activity.staticClass, "onCreateView", "(Ljava/lang/String;Landroid/content/Context;Landroid/util/AttributeSet;)Landroid/view/View;", ref global::android.app.Activity._m143, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.view.View; } private static global::MonoJavaBridge.MethodId _m144; public Activity() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.app.Activity._m144.native == global::System.IntPtr.Zero) global::android.app.Activity._m144 = @__env.GetMethodIDNoThrow(global::android.app.Activity.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.Activity.staticClass, global::android.app.Activity._m144); Init(@__env, handle); } public static int RESULT_CANCELED { get { return 0; } } public static int RESULT_OK { get { return -1; } } public static int RESULT_FIRST_USER { get { return 1; } } public static int DEFAULT_KEYS_DISABLE { get { return 0; } } public static int DEFAULT_KEYS_DIALER { get { return 1; } } public static int DEFAULT_KEYS_SHORTCUT { get { return 2; } } public static int DEFAULT_KEYS_SEARCH_LOCAL { get { return 3; } } public static int DEFAULT_KEYS_SEARCH_GLOBAL { get { return 4; } } static Activity() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.Activity.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/Activity")); } } }
using Foundation; using System; using System.Collections.Generic; using System.Threading.Tasks; using UIKit; using zsquared; namespace vitavol { public partial class VC_SCSiteDefaults : UIViewController { // Input // SelectedSite // SelectedDayOfWeek C_Global Global; C_VitaSite SelectedSite; C_VitaUser LoggedInUser; int SelectedDayOfWeek; // a flag to tell if the user made changes bool Dirty; public VC_SCSiteDefaults(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); SelectedSite = Global.GetSiteFromSlugNoFetch(Global.SelectedSiteSlug); #if DEBUG if ((LoggedInUser == null) || (SelectedSite == null) ) throw new ApplicationException("Missing value(s)"); #endif B_Back.TouchUpInside += async (sender, e) => { if (Dirty) { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Save Changes?", "Changes were made. Save before leaving?", C_MessageBox.E_MessageBoxButtons.YesNo); if (mbres != C_MessageBox.E_MessageBoxResults.Yes) { PerformSegue("Segue_SCSiteDefaultsToSCSiteCalendar", this); return; } bool success = await SaveChanges(); } PerformSegue("Segue_SCSiteDefaultsToSCSiteCalendar", this); }; L_SiteName.Text = SelectedSite.Name; L_DayOfWeek.Text = "Site Defaults for " + C_YMD.DayOfWeekNames[SelectedDayOfWeek]; C_CalendarEntry calDefaults = SelectedSite.SiteCalendar[SelectedDayOfWeek]; SW_IsOpen.On = calDefaults.SiteIsOpen; SetEnableOnControls(SW_IsOpen.On); SW_IsOpen.ValueChanged += (sender, e) => { SetEnableOnControls(SW_IsOpen.On); Dirty = true; B_SaveDefaults.Enabled = true; }; B_SaveDefaults.TouchUpInside += async (sender, e) => { bool success = await SaveChanges(); PerformSegue("Segue_SCSiteDefaultsToSCSiteCalendar", this); }; B_NewShift.TouchUpInside += (sender, e) => { Dirty = true; B_SaveDefaults.Enabled = true; C_WorkShift newShift = new C_WorkShift() { CalendarId = calDefaults.id, SiteSlug = SelectedSite.Slug }; calDefaults.WorkShifts.Add(newShift); Global.SelectedShift = newShift; Global.ViewCameFrom = E_ViewCameFrom.CalDefaults; PerformSegue("Segue_SCSiteDefaultsToShiftDetails", this); }; // pre-populate the table view with the 3 shifts C_ShiftsTableSource signUpTableSource = new C_ShiftsTableSource(calDefaults.WorkShifts, Global, this); TV_Shifts.Source = signUpTableSource; TV_Shifts.ReloadData(); } private void EnableUI(bool en) { B_Back.Enabled = en; B_SaveDefaults.Enabled = en && Dirty; SW_IsOpen.Enabled = en; TV_Shifts.UserInteractionEnabled = en; } public override void ViewDidAppear(bool animated) { // set the standard background color View.BackgroundColor = C_Common.StandardBackground; } async Task<bool> SaveChanges() { // bool success = false; //try //{ // EnableUI(false); // AI_Busy.StartAnimating(); // success = await SelectedSite.UpdateDefaultCalendar(null, LoggedInUser.Token); // EnableUI(true); // AI_Busy.StopAnimating(); // if (success) // { // Dirty = false; // B_SaveDefaults.Enabled = false; // } // else // { // C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, // "Error", // "Failed to update the Site calendar", // C_MessageBox.E_MessageBoxButtons.Ok); // } //} //catch { } //// we only have a return value since an async MUST return a value...sigh return true; } private void SetEnableOnControls(bool enable) { TV_Shifts.UserInteractionEnabled = enable; } public class C_ShiftsTableSource : UITableViewSource { readonly List<C_WorkShift> Shifts; readonly C_Global Global; readonly UIViewController ourVC; const string CellIdentifier = "TableCell_ShiftsTableSource"; public C_ShiftsTableSource(List<C_WorkShift> shifts, C_Global global, UIViewController ovc) { Shifts = shifts; Global = global; ourVC = ovc; } public override nint RowsInSection(UITableView tableview, nint section) { return Shifts.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); //---- if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier); C_WorkShift shift = Shifts[indexPath.Row]; cell.TextLabel.Text = "Shift " + indexPath.Row.ToString(); cell.DetailTextLabel.Text = "Hours: " + shift.OpenTime.ToString("hh:mm p") + " - " + shift.CloseTime.ToString("hh:mm p") + " Basic: " + shift.NumBasicEFilers.ToString() + " Advanced: " + shift.NumAdvEFilers.ToString(); return cell; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { Global.SelectedShift = Shifts[indexPath.Row]; Global.ViewCameFrom = E_ViewCameFrom.CalDefaults; ourVC.PerformSegue("Segue_SCSiteDefaultsToShiftDetails", ourVC); } } } }
// Copyright 2012 Jacob Trimble // // 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.Diagnostics.SymbolStore; using System.Linq; using System.Reflection; using System.Reflection.Emit; using ModMaker.Lua.Parser; using ModMaker.Lua.Parser.Items; using ModMaker.Lua.Runtime; using ModMaker.Lua.Runtime.LuaValues; namespace ModMaker.Lua.Compiler { /// <summary> /// Helps build a chunk by managing nested types and scopes. Also generates some code to load /// locals and the current environment. /// </summary> sealed class ChunkBuilder { /// <summary> /// Defines a nested type for a nested function. Each nested function that also has nested /// methods will have a nested type. If a function does not have any nested functions it does /// not have a nested type. The function is defined in the parent nest and any local variables /// defined in this function that is captured is defined as a field in the nested type. Then /// any nested functions are defined in the nested type. This is how C# handles captures /// with lambda expressions. /// </summary> sealed class NestInfo { /// <summary> /// A static ID to generate unique names across all types. /// </summary> static int _id = 1; /// <summary> /// Defines the captures for this nest. /// </summary> readonly HashSet<NameItem> _captures; /// <summary> /// Contains the members that are defined in this type. /// </summary> public HashSet<string> Members; /// <summary> /// Gets a dictionary of local variables that can be reused indexed by the type of the /// variable. /// </summary> public Dictionary<Type, Stack<LocalBuilder>> FreeLocals { get; private set; } /// <summary> /// Gets the ILGenerator for this nest. This generator belongs to the type of the parent nest /// but is only used for generating code for this nest. /// </summary> public ILGenerator Generator { get; private set; } /// <summary> /// Gets the type definition for this nested type. It is created in the constructor. /// </summary> public TypeBuilder TypeDef { get; private set; } /// <summary> /// Gets the parent nest object, is null for the root nest object. /// </summary> public NestInfo Parent { get; private set; } /// <summary> /// Gets the field defined in this type that holds the parent instance. This may not exist if /// the type does not capture any locals from the parent type. /// </summary> public FieldBuilder ParentInst { get; private set; } /// <summary> /// Gets the local variable that holds an instance to this type. /// </summary> public LocalBuilder ThisInst { get; private set; } /// <summary> /// Gets the local variable definitions for this nest. These are the variables defined in the /// defining method. The indices in the list are the scopes of the variables and the /// dictionary maps the name to the field in the type. /// </summary> public Stack<Dictionary<string, IVarDefinition>> Locals { get; private set; } /// <summary> /// Creates a new nest with the given parent. /// </summary> /// <param name="parent">The parent nest.</param> /// <param name="gen">The generator used to generate code for this function.</param> /// <param name="storeParent"> /// True to create a field that stores the parent instance; otherwise false. /// </param> /// <param name="captures"> /// The local variables that have been captured by nested functions. /// </param> /// <param name="createType">True to create a nested type, otherwise false.</param> public NestInfo(NestInfo parent, ILGenerator gen, NameItem[] captures, bool createType, bool storeParent) { FreeLocals = new Dictionary<Type, Stack<LocalBuilder>>(); Members = new HashSet<string>(); _captures = new HashSet<NameItem>(captures); Parent = parent; Generator = gen; Locals = new Stack<Dictionary<string, IVarDefinition>>(); Locals.Push(new Dictionary<string, IVarDefinition>()); if (createType) { // create the type and constructor. TypeDef = parent.TypeDef.DefineNestedType( "<>c__DisplayClass" + (_id++), TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit); var ctor = TypeDef.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]); var cgen = ctor.GetILGenerator(); // base(); cgen.Emit(OpCodes.Ldarg_0); cgen.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0])); cgen.Emit(OpCodes.Ret); if (storeParent) { ParentInst = TypeDef.DefineField("CS$<>__locals", parent.TypeDef, FieldAttributes.Public); } else { ParentInst = null; } // create the local definition // ThisInst = new TypeDef(); ThisInst = gen.DeclareLocal(TypeDef); gen.Emit(OpCodes.Newobj, ctor); gen.Emit(OpCodes.Stloc, ThisInst); if (storeParent) { // ThisInst.ParentInst = this; gen.Emit(OpCodes.Ldloc, ThisInst); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Stfld, ParentInst); } } else { TypeDef = null; ThisInst = null; ParentInst = null; } } NestInfo(TypeBuilder tb) { FreeLocals = new Dictionary<Type, Stack<LocalBuilder>>(); _captures = new HashSet<NameItem>(); Members = new HashSet<string>(); Locals = new Stack<Dictionary<string, IVarDefinition>>(); Locals.Push(new Dictionary<string, IVarDefinition>()); Parent = null; ParentInst = null; Generator = null; TypeDef = tb; ThisInst = null; } /// <summary> /// Creates the root nest node from the given TypeBuilder. /// </summary> /// <param name="tb">The type builder to create for.</param> /// <param name="gen">The ILGenerator for the global function.</param> /// <param name="captures">The captures for the global function.</param> /// <param name="createType"> /// Whether to create a type for the global function. /// </param> /// <returns>The new root nest node.</returns> public static NestInfo Create(TypeBuilder tb, ILGenerator gen, NameItem[] captures, bool createType) { NestInfo temp = new NestInfo(tb); return new NestInfo(temp, gen, captures, createType, false); } /// <summary> /// Searches this type for a given local variable and returns an object to manipulate it's /// value. /// </summary> /// <param name="name">The Lua name of the variable.</param> /// <returns>A variable that will manipulate it's value or null if not found.</returns> public IVarDefinition FindLocal(NameItem name) { // The iterator will return in the order they would be pop'd. foreach (var item in Locals) { if (item.TryGetValue(name.Name, out IVarDefinition ret)) { return ret; } } return null; } /// <summary> /// Defines a new Local variable and returns the field that represents it. /// </summary> /// <param name="name">The Lua name of the variable.</param> /// <returns>The variable that represents the local.</returns> public IVarDefinition DefineLocal(NameItem name) { if (_captures.Contains(name)) { string mName = name.Name; if (Members.Contains(mName)) { int i = 0; while (Members.Contains(mName + "_" + i)) { i++; } mName += "_" + i; } Members.Add(mName); var field = TypeDef.DefineField(mName, typeof(ILuaValue), FieldAttributes.Public); return Locals.Peek()[name.Name] = new CapturedVarDef(Generator, ThisInst, field); } else { var loc = Generator.DeclareLocal(typeof(ILuaValue)); return Locals.Peek()[name.Name] = new LocalVarDef(Generator, loc); } } /// <summary> /// Returns an object that starts a new local block when created and will end it when Dispose /// is called. For use with 'using' keyword. /// </summary> /// <returns>A helper object that will end the scope when Dispose is called.</returns> public IDisposable LocalBlock() { Locals.Push(new Dictionary<string, IVarDefinition>()); return Helpers.Disposable(() => { Locals.Pop(); }); } } readonly LuaSettings _settings; readonly ModuleBuilder _mb; NestInfo _curNest; #if NETFRAMEWORK Dictionary<string, ISymbolDocumentWriter> _documents = new Dictionary<string, ISymbolDocumentWriter>(); #endif int _mid = 1; /// <summary> /// Creates a new ChunkBuilder and initializes the state. /// </summary> /// <param name="tb">The root type of this chunk.</param> /// <param name="captures">An array of the global captures.</param> /// <param name="createType"> /// True to create a nested type for the global function, this means that there are nested /// functions. /// </param> public ChunkBuilder(LuaSettings settings, ModuleBuilder mb, TypeBuilder tb, NameItem[] captures, bool createType) { //// ILuaEnviormnent $Env; var field = tb.DefineField("$Env", typeof(ILuaEnvironment), FieldAttributes.Private); //// ILuaMultiValue Invoke(ILuaEnvironment E, ILuaMultiValue args); var method = tb.DefineMethod( nameof(ILuaValue.Invoke), MethodAttributes.Public | MethodAttributes.HideBySig, typeof(LuaMultiValue), new[] { typeof(ILuaEnvironment), typeof(LuaMultiValue) }); _curNest = NestInfo.Create(tb, method.GetILGenerator(), captures, createType); _mb = mb; _settings = settings; _addInvoke(tb, method, field); _addConstructor(tb, field); _addAbstracts(tb); } /// <summary> /// Adds default implementation of abstract methods. /// </summary> /// <param name="tb">The type builder to add to.</param> static void _addAbstracts(TypeBuilder tb) { // bool Equals(ILuaValue other); var method = tb.DefineMethod( nameof(ILuaValue.Equals), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, typeof(bool), new[] { typeof(ILuaValue) }); var gen = method.GetILGenerator(); // return object.ReferenceEquals(this, other); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, typeof(object).GetMethod(nameof(object.ReferenceEquals), BindingFlags.Static | BindingFlags.Public)); gen.Emit(OpCodes.Ret); // ILuaValue Arithmetic(BinaryOperationType type, ILuaValue other); method = tb.DefineMethod( nameof(ILuaValue.Arithmetic), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, typeof(ILuaValue), new[] { typeof(BinaryOperationType), typeof(ILuaValue) }); gen = method.GetILGenerator(); // throw new NotImplementedException(); gen.ThrowException(typeof(NotImplementedException)); gen.Emit(OpCodes.Ret); // LuaValueType get_ValueType(); method = tb.DefineMethod( "get_" + nameof(ILuaValue.ValueType), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, typeof(LuaValueType), Type.EmptyTypes); gen = method.GetILGenerator(); // return LuaValueType.Function; gen.Emit(OpCodes.Ldc_I4, (int)LuaValueType.Function); gen.Emit(OpCodes.Ret); // ILuaValue Arithmetic<T>(BinaryOperationType type, LuaUserData<T> self); method = tb.DefineMethod( nameof(ILuaValue.Arithmetic), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual); var types = method.DefineGenericParameters("T"); method.SetParameters(typeof(BinaryOperationType), typeof(LuaUserData<>).MakeGenericType(types)); method.SetReturnType(typeof(ILuaValue)); gen = method.GetILGenerator(); // throw new NotImplementedException(); gen.ThrowException(typeof(NotImplementedException)); gen.Emit(OpCodes.Ret); } /// <summary> /// Adds a constructor that accepts a single ILuaEnvironment argument to the given type builder /// object. /// </summary> /// <param name="tb">The type builder to add to.</param> /// <param name="envField">The field that stores the environment.</param> static void _addConstructor(TypeBuilder tb, FieldBuilder envField) { //// .ctor(ILuaEnvironment/*!*/ E); var ctor = tb.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(ILuaEnvironment) }); var gen = ctor.GetILGenerator(); // this.$Env = E; gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Stfld, envField); gen.Emit(OpCodes.Ret); } /// <summary> /// Adds the two overloads of IMethod.Invoke that simply calls the given method. /// </summary> /// <param name="tb">The type builder to add to.</param> /// <param name="realMethod">The real method to call.</param> /// <param name="envField">The field that contains the environment.</param> static void _addInvoke(TypeBuilder tb, MethodBuilder realMethod, FieldBuilder envField) { //// ILuaMultiValue Invoke(ILuaValue self, bool memberCall, ILuaMultiValue args); MethodBuilder mb = tb.DefineMethod( nameof(ILuaValue.Invoke), MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(LuaMultiValue), new Type[] { typeof(ILuaValue), typeof(bool), typeof(LuaMultiValue) }); var gen = mb.GetILGenerator(); // return this.Invoke(this.Environment, args); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, envField); gen.Emit(OpCodes.Ldarg, 3); gen.Emit(OpCodes.Callvirt, realMethod); gen.Emit(OpCodes.Ret); } /// <summary> /// Gets the ILGenerator for the current function. /// </summary> public ILGenerator CurrentGenerator { get { return _curNest.Generator; } } public void MarkSequencePoint(DebugInfo info) { #if NETFRAMEWORK if (!_settings.AddNativeDebugSymbols || info.Path == null) return; if (!_documents.ContainsKey(info.Path)) { _documents.Add(info.Path, _mb.DefineDocument(info.Path, SymDocumentType.Text, SymLanguageType.ILAssembly, Guid.Empty)); } CurrentGenerator.MarkSequencePoint(_documents[info.Path], (int)info.StartLine, (int)info.StartPos, (int)info.EndLine, (int)info.EndPos); #endif } /// <summary> /// Compiles the current code into am IMethod. /// </summary> /// <param name="e">The current environment.</param> /// <returns>A new IMethod compiled from the current code.</returns> public ILuaValue CreateChunk(ILuaEnvironment e) { if (_curNest == null) { throw new InvalidOperationException(); } if (_curNest.TypeDef != null) { _curNest.TypeDef.CreateType(); } Type t = _curNest.Parent.TypeDef.CreateType(); return new LuaGlobalFunction(e, t); } /// <summary> /// Starts a local-variable scope block and returns an object that will end the scope when /// Dispose is called. This is to be used with the 'using' keyword. /// </summary> /// <returns> /// An object that will end the local block when 'Dispose' is called. /// </returns> public IDisposable LocalBlock() { return _curNest.LocalBlock(); } /// <summary> /// Implements a function definition based on a given function definition. /// </summary> /// <param name="funcName">The simple name of the function, can be null.</param> /// <param name="visitor">The current visitor object.</param> /// <param name="function">The function to generate for.</param> public void ImplementFunction(IParseItemVisitor visitor, FuncDefItem function, string funcName) { NameItem[] args = function.Arguments.ToArray(); if (function.InstanceName != null) { args = new[] { new NameItem("self") }.Concat(args).ToArray(); } // ILuaMultiValue function(ILuaEnvironment E, ILuaMultiValue args, ILuaValue target, // bool memberCall); funcName ??= "<>__" + (_mid++); string name = _curNest.Members.Contains(funcName) ? funcName + "_" + (_mid++) : funcName; MethodBuilder mb = _curNest.TypeDef.DefineMethod( name, MethodAttributes.Public, typeof(LuaMultiValue), new Type[] { typeof(ILuaEnvironment), typeof(LuaMultiValue), typeof(ILuaValue), typeof(bool) }); var gen = mb.GetILGenerator(); _curNest = new NestInfo( _curNest, gen, function.FunctionInformation.CapturedLocals, function.FunctionInformation.HasNested, function.FunctionInformation.CapturesParent); // if this is an instance method, create a BaseAccessor object to help types. if (function.InstanceName != null) { // TODO: Add base accessor back. //var field = curNest.DefineLocal(new NameItem("base")); } // If this was an instance call, the first Lua argument is the 'target'; // otherwise the it is the zero'th index in args. // int c = 0; var c = gen.DeclareLocal(typeof(int)); if (args.Length > 0) { var field = _curNest.DefineLocal(args[0]); var end = gen.DefineLabel(); var else_ = gen.DefineLabel(); // if (!memberCall) c = 1; // {field_0} = (memberCall ? target : args[0]); field.StartSet(); gen.Emit(OpCodes.Ldarg, 4); gen.Emit(OpCodes.Brfalse, else_); gen.Emit(OpCodes.Ldarg_3); gen.Emit(OpCodes.Br, end); gen.MarkLabel(else_); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Stloc, c); gen.Emit(OpCodes.Ldarg_2); if (args[0].Name != "...") { gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Call, typeof(LuaMultiValue).GetMethod("get_Item")); } else { if (args.Length != 1) { throw new InvalidOperationException( "Variable arguments (...) only valid at end of argument list."); } } gen.MarkLabel(end); field.EndSet(); } for (int i = 1; i < args.Length; i++) { var field = _curNest.DefineLocal(args[i]); if (args[i].Name == "...") { if (i != args.Length - 1) { throw new InvalidOperationException( "Variable arguments (...) only valid at end of argument list."); } // {field} = new LuaMultiValue(args.Skip({args.Length - 1}).ToArray()); field.StartSet(); gen.Emit(OpCodes.Ldarg_2); gen.Emit(OpCodes.Ldc_I4, args.Length - 1); gen.Emit(OpCodes.Call, typeof(Enumerable).GetMethod(nameof(Enumerable.Skip)) .MakeGenericMethod(typeof(ILuaValue))); gen.Emit(OpCodes.Call, typeof(Enumerable).GetMethod(nameof(Enumerable.ToArray)) .MakeGenericMethod(typeof(ILuaValue))); gen.Emit(OpCodes.Newobj, typeof(LuaMultiValue).GetConstructor(new[] { typeof(ILuaValue[]) })); field.EndSet(); } else { // {field} = args[{i - 1} + c]; field.StartSet(); gen.Emit(OpCodes.Ldarg_2); gen.Emit(OpCodes.Ldc_I4, i - 1); gen.Emit(OpCodes.Ldloc, c); gen.Emit(OpCodes.Add); gen.Emit(OpCodes.Call, typeof(LuaMultiValue).GetMethod("get_Item")); field.EndSet(); } } function.Block.Accept(visitor); if (_curNest.TypeDef != null) { _curNest.TypeDef.CreateType(); } _curNest = _curNest.Parent; // push a pointer to the new method onto the stack of the previous nest method // the above line restores the nest to the previous state and this code will // push the new method. //! push new LuaDefinedFunction({name}, {nest.TypeDef}.GetMethod({name}), // {nest.ThisInst != null ? nest.NestInst : this} ); _curNest.Generator.Emit(OpCodes.Ldarg_1); _curNest.Generator.Emit(OpCodes.Ldstr, name); _curNest.Generator.Emit(OpCodes.Ldtoken, _curNest.TypeDef); _curNest.Generator.Emit( OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle), new Type[] { typeof(RuntimeTypeHandle) })); _curNest.Generator.Emit(OpCodes.Ldstr, name); _curNest.Generator.Emit( OpCodes.Callvirt, typeof(Type).GetMethod(nameof(Type.GetMethod), new[] { typeof(string) })); if (_curNest.ThisInst != null) { _curNest.Generator.Emit(OpCodes.Ldloc, _curNest.ThisInst); } else { _curNest.Generator.Emit(OpCodes.Ldarg_0); } _curNest.Generator.Emit( OpCodes.Newobj, typeof(LuaDefinedFunction).GetConstructor(new[] { typeof(ILuaEnvironment), typeof(string), typeof(MethodInfo), typeof(object) })); } /// <summary> /// Searches for a variable with the given name and returns an object used to get/set it's /// value. There are three kinds of variables: Local, Captured, and Global. /// </summary> /// <param name="name">The name of the variable.</param> /// <returns>An object used to generate code for this variable.</returns> public IVarDefinition FindVariable(NameItem name) { // Search in the current nest var varDef = _curNest.FindLocal(name); if (varDef != null) { return varDef; } // Search for parent captures var fields = new List<FieldBuilder>(); var cur = _curNest.Parent; while (cur != null) { varDef = cur.FindLocal(name); if (varDef != null) { if (varDef is LocalVarDef) { throw new InvalidOperationException(); } fields.Add(((CapturedVarDef)varDef).Field); return new CapturedParVarDef(CurrentGenerator, fields.ToArray()); } fields.Add(cur.ParentInst); cur = cur.Parent; } // Still not found, it is a global variable return new GlobalVarDef(CurrentGenerator, name.Name); } /// <summary> /// Defines a new local variable and returns an object used to get/set it's value. There are /// two possible variable types: Local and Captured. Which one is chosen depends on whether the /// variable is captured in the FunctionInfo used to create the current function. /// </summary> /// <param name="name">The name of the variable.</param> /// <returns>An object used to get/set it's value.</returns> public IVarDefinition DefineLocal(NameItem name) { return _curNest.DefineLocal(name); } /// <summary> /// Creates a new temporary variable and returns the local used to use it. This may also use a /// variable from the cache. When the variable is no longer used, call /// RemoveTemporary(LocalBuilder). /// </summary> /// <param name="type">The type of the local variable.</param> /// <returns>The local builder that defines the variable.</returns> public LocalBuilder CreateTemporary(Type type) { if (_curNest.FreeLocals.ContainsKey(type)) { var temp = _curNest.FreeLocals[type]; if (temp.Count > 0) { return temp.Pop(); } } return CurrentGenerator.DeclareLocal(type); } /// <summary> /// Creates an array of the given type and stores it in a returned local. /// </summary> /// <param name="arrayType">The type of the array.</param> /// <param name="size">The size of the array.</param> /// <returns>A local builder that now contains the array.</returns> public LocalBuilder CreateArray(Type arrayType, int size) { var ret = CreateTemporary(arrayType.MakeArrayType()); CurrentGenerator.Emit(OpCodes.Ldc_I4, size); CurrentGenerator.Emit(OpCodes.Newarr, arrayType); CurrentGenerator.Emit(OpCodes.Stloc, ret); return ret; } /// <summary> /// Marks the given local variable as not being used anymore. This allows the variable to be /// used again in other code. /// </summary> /// <param name="local">The local variable that is no longer used.</param> public void RemoveTemporary(LocalBuilder local) { if (!_curNest.FreeLocals.ContainsKey(local.LocalType)) { _curNest.FreeLocals.Add(local.LocalType, new Stack<LocalBuilder>()); } _curNest.FreeLocals[local.LocalType].Push(local); } #region public interface VariableDefinition /// <summary> /// A helper interface used to generate code for different variable definitions. There are /// three scopes: Global, Local, and Captured. /// </summary> public interface IVarDefinition { /// <summary> /// Starts the setting of the variable. For example, pushing 'this' onto the stack. /// </summary> void StartSet(); /// <summary> /// Ends the setting of the variable. For example, emitting OpCodes.Stloc. /// </summary> void EndSet(); /// <summary> /// Pushes the value of the variable onto the stack. /// </summary> void Get(); } /// <summary> /// Defines a global variable. /// </summary> sealed class GlobalVarDef : IVarDefinition { readonly ILGenerator _gen; readonly string _name; public GlobalVarDef(ILGenerator gen, string name) { _gen = gen; _name = name; } public void StartSet() { // part of: // E.GlobalsTable.SetIndex(LuaValueBase.CreateValue({name}), value); _gen.Emit(OpCodes.Ldarg_1); _gen.Emit(OpCodes.Callvirt, typeof(ILuaEnvironment).GetProperty(nameof(ILuaEnvironment.GlobalsTable)) .GetGetMethod()); _gen.Emit(OpCodes.Ldstr, _name); _gen.Emit(OpCodes.Call, typeof(LuaValueBase).GetMethod(nameof(LuaValueBase.CreateValue))); } public void EndSet() { // end of: // E.GlobalsTable.SetIndex({name}, value); _gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.SetIndex))); } public void Get() { //! push E.GlobalsTable.GetIndex(LuaValueBase.CreateValue({name})) _gen.Emit(OpCodes.Ldarg_1); _gen.Emit(OpCodes.Callvirt, typeof(ILuaEnvironment).GetProperty(nameof(ILuaEnvironment.GlobalsTable)) .GetGetMethod()); _gen.Emit(OpCodes.Ldstr, _name); _gen.Emit(OpCodes.Call, typeof(LuaValueBase).GetMethod(nameof(LuaValueBase.CreateValue))); _gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.GetIndex))); } } /// <summary> /// Defines a local variable definition, one that is only referenced by the current function. /// </summary> sealed class LocalVarDef : IVarDefinition { readonly ILGenerator _gen; readonly LocalBuilder _local; public LocalVarDef(ILGenerator gen, LocalBuilder loc) { _gen = gen; _local = loc; } public void StartSet() { // do nothing. } public void EndSet() { // local = {value}; _gen.Emit(OpCodes.Stloc, _local); } public void Get() { _gen.Emit(OpCodes.Ldloc, _local); } } /// <summary> /// Defines a local variable that has been captured by nested functions and is stored in a field /// in a nested type. This version is used for when called from the defining function so only /// an instance to the child type is needed to access the variable. /// </summary> sealed class CapturedVarDef : IVarDefinition { readonly ILGenerator _gen; readonly LocalBuilder _thisInst; public FieldBuilder Field; public CapturedVarDef(ILGenerator gen, LocalBuilder thisInst, FieldBuilder field) { _gen = gen; _thisInst = thisInst; Field = field; } public void StartSet() { // part of: // thisInst.field = {value} _gen.Emit(OpCodes.Ldloc, _thisInst); } public void EndSet() { // part of: // thisInst.field = {value} _gen.Emit(OpCodes.Stfld, Field); } public void Get() { _gen.Emit(OpCodes.Ldloc, _thisInst); _gen.Emit(OpCodes.Ldfld, Field); } } /// <summary> /// Defines a local variable that has been captured by nested functions and is stored in a /// parent nest. This version loads the variable from parent nest types. /// </summary> sealed class CapturedParVarDef : IVarDefinition { readonly ILGenerator _gen; readonly FieldBuilder[] _fields; public CapturedParVarDef(ILGenerator gen, FieldBuilder[] fields) { _gen = gen; _fields = fields; } public void StartSet() { _gen.Emit(OpCodes.Ldarg_0); for (int i = 0; i < _fields.Length - 1; i++) { _gen.Emit(OpCodes.Ldfld, _fields[i]); } } public void EndSet() { _gen.Emit(OpCodes.Stfld, _fields[_fields.Length - 1]); } public void Get() { _gen.Emit(OpCodes.Ldarg_0); for (int i = 0; i < _fields.Length; i++) { _gen.Emit(OpCodes.Ldfld, _fields[i]); } } } #endregion } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using NUnit.Framework; namespace Google.ProtocolBuffers.ProtoGen { [TestFixture] [Category("Preprocessor")] public partial class TestPreprocessing { private static readonly string TempPath = Path.Combine(Path.GetTempPath(), "proto-gen-test"); private const string DefaultProto = @" package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; }"; #region TestFixture SetUp/TearDown private static readonly string OriginalWorkingDirectory = Environment.CurrentDirectory; [TestFixtureSetUp] public virtual void Setup() { Teardown(); Directory.CreateDirectory(TempPath); Environment.CurrentDirectory = TempPath; } [TestFixtureTearDown] public virtual void Teardown() { Environment.CurrentDirectory = OriginalWorkingDirectory; if (Directory.Exists(TempPath)) { Directory.Delete(TempPath, true); } } #endregion #region Helper Methods RunProtoGen / RunCsc private void RunProtoGen(int expect, params string[] args) { TextWriter tout = Console.Out, terr = Console.Error; StringWriter temp = new StringWriter(); Console.SetOut(temp); Console.SetError(temp); try { Assert.AreEqual(expect, ProgramPreprocess.Run(args), "ProtoGen Failed: {0}", temp); } finally { Console.SetOut(tout); Console.SetError(terr); } } private Assembly RunCsc(int expect, params string[] sources) { using (TempFile tempDll = new TempFile(String.Empty)) { tempDll.ChangeExtension(".dll"); List<string> args = new List<string>(); args.Add("/nologo"); args.Add("/target:library"); args.Add("/debug-"); args.Add(String.Format(@"""/out:{0}""", tempDll.TempPath)); args.Add("/r:System.dll"); args.Add(String.Format(@"""/r:{0}""", typeof(Google.ProtocolBuffers.DescriptorProtos.DescriptorProto).Assembly. Location)); args.AddRange(sources); string exe = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "csc.exe"); ProcessStartInfo psi = new ProcessStartInfo(exe); psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.Arguments = string.Join(" ", args.ToArray()); Process p = Process.Start(psi); p.WaitForExit(); string errorText = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd(); Assert.AreEqual(expect, p.ExitCode, "CSC.exe Failed: {0}", errorText); Assembly asm = null; if (p.ExitCode == 0) { byte[] allbytes = File.ReadAllBytes(tempDll.TempPath); asm = Assembly.Load(allbytes); foreach (Type t in asm.GetTypes()) { Debug.WriteLine(t.FullName, asm.FullName); } } return asm; } } #endregion // ******************************************************************* // The following tests excercise options for protogen.exe // ******************************************************************* [Test] public void TestProtoFile() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } [Test] public void TestProtoFileWithConflictingType() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" package nunit.simple; // Test a very simple message. message " + test + @" { optional string name = 1; } ")) { RunProtoGen(0, proto.TempPath); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple." + test, true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple.Proto." + test, true, true); } } [Test] public void TestProtoFileWithNamespace() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "-namespace:MyNewNamespace"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("MyNewNamespace." + test, true, true); } } [Test] public void TestProtoFileWithUmbrellaClassName() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach("MyUmbrellaClassname.cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "/umbrella_classname=MyUmbrellaClassname"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple.MyUmbrellaClassname", true, true); } } [Test] public void TestProtoFileWithNestedClass() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "-nest_classes:true"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } [Test] public void TestProtoFileWithExpandedNsDirectories() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(@"nunit\simple\" + test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "-expand_namespace_directories:true"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } [Test] public void TestProtoFileWithNewExtension() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".Generated.cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "-file_extension:.Generated.cs"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } [Test] public void TestProtoFileWithUmbrellaNamespace() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "-umbrella_namespace:MyUmbrella.Namespace"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple.MyUmbrella.Namespace." + test, true, true); } } [Test] public void TestProtoFileWithIgnoredUmbrellaNamespaceDueToNesting() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(0, proto.TempPath, "-nest_classes:true", "-umbrella_namespace:MyUmbrella.Namespace"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } [Test] public void TestProtoFileWithExplicitEmptyUmbrellaNamespace() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" package nunit.simple; // Test a very simple message. message " + test + @" { optional string name = 1; } ")) { //Forces the umbrella class to not use a namespace even if a collision with a type is detected. RunProtoGen(0, proto.TempPath, "-umbrella_namespace:"); //error CS0441: 'nunit.simple.TestProtoFileWithExplicitEmptyUmbrellaNamespace': a class cannot be both static and sealed RunCsc(1, source.TempPath); } } [Test] public void TestProtoFileWithNewOutputFolder() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(@"generated-code\" + test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { RunProtoGen(1, proto.TempPath, "-output_directory:generated-code"); Directory.CreateDirectory("generated-code"); RunProtoGen(0, proto.TempPath, "-output_directory:generated-code"); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } [Test] public void TestProtoFileAndIgnoreGoogleProtobuf() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" import ""google/protobuf/csharp_options.proto""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; " + DefaultProto)) { string google = Path.Combine(TempPath, "google\\protobuf"); Directory.CreateDirectory(google); foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) { File.Copy(file, Path.Combine(google, Path.GetFileName(file))); } Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length); RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true"); Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("MyNewNamespace." + test, true, true); } } [Test] public void TestProtoFileWithoutIgnoreGoogleProtobuf() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" import ""google/protobuf/csharp_options.proto""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; " + DefaultProto)) { string google = Path.Combine(TempPath, "google\\protobuf"); Directory.CreateDirectory(google); foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) { File.Copy(file, Path.Combine(google, Path.GetFileName(file))); } Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length); //Without the option this fails due to being unable to resolve google/protobuf descriptors RunProtoGen(1, proto.TempPath, "-ignore_google_protobuf:false"); } } // ******************************************************************* // The following tests excercise options for protoc.exe // ******************************************************************* [Test] public void TestProtoFileWithIncludeImports() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" import ""google/protobuf/csharp_options.proto""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; } ") ) { string google = Path.Combine(TempPath, "google\\protobuf"); Directory.CreateDirectory(google); foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) { File.Copy(file, Path.Combine(google, Path.GetFileName(file))); } Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length); //if you specify the protoc option --include_imports this should build three source files RunProtoGen(0, proto.TempPath, "--include_imports"); Assert.AreEqual(3, Directory.GetFiles(TempPath, "*.cs").Length); //you can (and should) simply omit the inclusion of the extra source files in your project Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("MyNewNamespace." + test, true, true); } } [Test] public void TestProtoFileWithIncludeImportsAndIgnoreGoogleProtobuf() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" import ""google/protobuf/csharp_options.proto""; option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace""; package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; } ") ) { string google = Path.Combine(TempPath, "google\\protobuf"); Directory.CreateDirectory(google); foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) File.Copy(file, Path.Combine(google, Path.GetFileName(file))); Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length); //Even with --include_imports, if you provide -ignore_google_protobuf:true you only get the one source file RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "--include_imports"); Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length); //you can (and should) simply omit the inclusion of the extra source files in your project Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("MyNewNamespace.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("MyNewNamespace." + test, true, true); } } [Test] public void TestProtoFileKeepingTheProtoBuffer() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile protobuf = TempFile.Attach(test + ".pb")) using (TempFile source = TempFile.Attach(test + ".cs")) using ( ProtoFile proto = new ProtoFile(test + ".proto", @" package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; } ") ) { RunProtoGen(0, proto.TempPath, "--descriptor_set_out=" + protobuf.TempPath); Assert.IsTrue(File.Exists(protobuf.TempPath), "Missing: " + protobuf.TempPath); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } //Seems the --proto_path or -I option is non-functional for me. Maybe others have luck? [Test] public void TestProtoFileInDifferentDirectory() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto)) { Environment.CurrentDirectory = OriginalWorkingDirectory; RunProtoGen(0, proto.TempPath, "--proto_path=" + TempPath); Assembly a = RunCsc(0, source.TempPath); //assert that the message type is in the expected namespace Type t = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple." + test, true, true); } } // ******************************************************************* // Handling of mutliple input files // ******************************************************************* [Test] public void TestMultipleProtoFiles() { Setup(); using (TempFile source1 = TempFile.Attach("MyMessage.cs")) using ( ProtoFile proto1 = new ProtoFile("MyMessage.proto", @" package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; }") ) using (TempFile source2 = TempFile.Attach("MyMessageList.cs")) using ( ProtoFile proto2 = new ProtoFile("MyMessageList.proto", @" package nunit.simple; import ""MyMessage.proto""; // Test a very simple message. message MyMessageList { repeated MyMessage messages = 1; }") ) { RunProtoGen(0, proto1.TempPath, proto2.TempPath); Assembly a = RunCsc(0, source1.TempPath, source2.TempPath); //assert that the message type is in the expected namespace Type t1 = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage"); //assert that the message type is in the expected namespace Type t2 = a.GetType("nunit.simple.MyMessageList", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple.Proto.MyMessage", true, true); a.GetType("nunit.simple.Proto.MyMessageList", true, true); } } [Test] public void TestOneProtoFileWithBufferFile() { Setup(); using (TempFile source1 = TempFile.Attach("MyMessage.cs")) using (TempFile protobuf = TempFile.Attach("MyMessage.pb")) using ( ProtoFile proto1 = new ProtoFile("MyMessage.proto", @" package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; }") ) using (TempFile source2 = TempFile.Attach("MyMessageList.cs")) using ( ProtoFile proto2 = new ProtoFile("MyMessageList.proto", @" package nunit.simple; import ""MyMessage.proto""; // Test a very simple message. message MyMessageList { repeated MyMessage messages = 1; }") ) { //build the proto buffer for MyMessage RunProtoGen(0, proto1.TempPath, "--descriptor_set_out=" + protobuf.TempPath); //build the MyMessageList proto-buffer and generate code by including MyMessage.pb RunProtoGen(0, proto2.TempPath, protobuf.TempPath); Assembly a = RunCsc(0, source1.TempPath, source2.TempPath); //assert that the message type is in the expected namespace Type t1 = a.GetType("nunit.simple.MyMessage", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage"); //assert that the message type is in the expected namespace Type t2 = a.GetType("nunit.simple.MyMessageList", true, true); Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage"); //assert that we can find the static descriptor type a.GetType("nunit.simple.Proto.MyMessage", true, true); a.GetType("nunit.simple.Proto.MyMessageList", true, true); } } [Test] public void TestProtoFileWithService() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", @" import ""google/protobuf/csharp_options.proto""; option (google.protobuf.csharp_file_options).service_generator_type = GENERIC; package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; } // test a very simple service. service TestService { rpc Execute (MyMessage) returns (MyMessage); }")) { CopyInGoogleProtoFiles(); RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "-nest_classes=false"); Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length); Assembly a = RunCsc(0, source.TempPath); //assert that the service type is in the expected namespace Type t1 = a.GetType("nunit.simple.TestService", true, true); Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService"); Assert.IsTrue(t1.IsAbstract, "Expect abstract class"); //assert that the Stub subclass type is in the expected namespace Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true); Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService"); Assert.IsFalse(t2.IsAbstract, "Expect concrete class"); } } [Test] public void TestProtoFileWithServiceInternal() { string test = new StackFrame(false).GetMethod().Name; Setup(); using (TempFile source = TempFile.Attach(test + ".cs")) using (ProtoFile proto = new ProtoFile(test + ".proto", @" import ""google/protobuf/csharp_options.proto""; option (google.protobuf.csharp_file_options).service_generator_type = GENERIC; package nunit.simple; // Test a very simple message. message MyMessage { optional string name = 1; } // test a very simple service. service TestService { rpc Execute (MyMessage) returns (MyMessage); }")) { CopyInGoogleProtoFiles(); RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "-nest_classes=false", "-public_classes=false"); Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length); Assembly a = RunCsc(0, source.TempPath); //assert that the service type is in the expected namespace Type t1 = a.GetType("nunit.simple.TestService", true, true); Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService"); Assert.IsTrue(t1.IsAbstract, "Expect abstract class"); //assert that the Stub subclass type is in the expected namespace Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true); Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService"); Assert.IsFalse(t2.IsAbstract, "Expect concrete class"); } } private static void CopyInGoogleProtoFiles() { string google = Path.Combine(TempPath, "google\\protobuf"); Directory.CreateDirectory(google); foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf"))) { File.Copy(file, Path.Combine(google, Path.GetFileName(file))); } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnDatosReportable class. /// </summary> [Serializable] public partial class PnDatosReportableCollection : ActiveList<PnDatosReportable, PnDatosReportableCollection> { public PnDatosReportableCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnDatosReportableCollection</returns> public PnDatosReportableCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnDatosReportable o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_datos_reportables table. /// </summary> [Serializable] public partial class PnDatosReportable : ActiveRecord<PnDatosReportable>, IActiveRecord { #region .ctors and Default Settings public PnDatosReportable() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnDatosReportable(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnDatosReportable(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnDatosReportable(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_datos_reportables", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdDatoReportable = new TableSchema.TableColumn(schema); colvarIdDatoReportable.ColumnName = "idDatoReportable"; colvarIdDatoReportable.DataType = DbType.Int32; colvarIdDatoReportable.MaxLength = 0; colvarIdDatoReportable.AutoIncrement = true; colvarIdDatoReportable.IsNullable = false; colvarIdDatoReportable.IsPrimaryKey = true; colvarIdDatoReportable.IsForeignKey = false; colvarIdDatoReportable.IsReadOnly = false; colvarIdDatoReportable.DefaultSetting = @""; colvarIdDatoReportable.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdDatoReportable); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarUnidadMedida = new TableSchema.TableColumn(schema); colvarUnidadMedida.ColumnName = "unidad_medida"; colvarUnidadMedida.DataType = DbType.AnsiString; colvarUnidadMedida.MaxLength = 20; colvarUnidadMedida.AutoIncrement = false; colvarUnidadMedida.IsNullable = true; colvarUnidadMedida.IsPrimaryKey = false; colvarUnidadMedida.IsForeignKey = false; colvarUnidadMedida.IsReadOnly = false; colvarUnidadMedida.DefaultSetting = @""; colvarUnidadMedida.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnidadMedida); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_datos_reportables",schema); } } #endregion #region Props [XmlAttribute("IdDatoReportable")] [Bindable(true)] public int IdDatoReportable { get { return GetColumnValue<int>(Columns.IdDatoReportable); } set { SetColumnValue(Columns.IdDatoReportable, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("UnidadMedida")] [Bindable(true)] public string UnidadMedida { get { return GetColumnValue<string>(Columns.UnidadMedida); } set { SetColumnValue(Columns.UnidadMedida, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.PnRelNomencladorXDatoReportableCollection colPnRelNomencladorXDatoReportableRecords; public DalSic.PnRelNomencladorXDatoReportableCollection PnRelNomencladorXDatoReportableRecords { get { if(colPnRelNomencladorXDatoReportableRecords == null) { colPnRelNomencladorXDatoReportableRecords = new DalSic.PnRelNomencladorXDatoReportableCollection().Where(PnRelNomencladorXDatoReportable.Columns.IdDatoReportable, IdDatoReportable).Load(); colPnRelNomencladorXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelNomencladorXDatoReportableRecords_ListChanged); } return colPnRelNomencladorXDatoReportableRecords; } set { colPnRelNomencladorXDatoReportableRecords = value; colPnRelNomencladorXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelNomencladorXDatoReportableRecords_ListChanged); } } void colPnRelNomencladorXDatoReportableRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnRelNomencladorXDatoReportableRecords[e.NewIndex].IdDatoReportable = IdDatoReportable; } } private DalSic.PnRelPrestacionXDatoReportableCollection colPnRelPrestacionXDatoReportableRecords; public DalSic.PnRelPrestacionXDatoReportableCollection PnRelPrestacionXDatoReportableRecords { get { if(colPnRelPrestacionXDatoReportableRecords == null) { colPnRelPrestacionXDatoReportableRecords = new DalSic.PnRelPrestacionXDatoReportableCollection().Where(PnRelPrestacionXDatoReportable.Columns.IdDatoReportable, IdDatoReportable).Load(); colPnRelPrestacionXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelPrestacionXDatoReportableRecords_ListChanged); } return colPnRelPrestacionXDatoReportableRecords; } set { colPnRelPrestacionXDatoReportableRecords = value; colPnRelPrestacionXDatoReportableRecords.ListChanged += new ListChangedEventHandler(colPnRelPrestacionXDatoReportableRecords_ListChanged); } } void colPnRelPrestacionXDatoReportableRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnRelPrestacionXDatoReportableRecords[e.NewIndex].IdDatoReportable = IdDatoReportable; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre,string varUnidadMedida) { PnDatosReportable item = new PnDatosReportable(); item.Nombre = varNombre; item.UnidadMedida = varUnidadMedida; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdDatoReportable,string varNombre,string varUnidadMedida) { PnDatosReportable item = new PnDatosReportable(); item.IdDatoReportable = varIdDatoReportable; item.Nombre = varNombre; item.UnidadMedida = varUnidadMedida; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdDatoReportableColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn UnidadMedidaColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdDatoReportable = @"idDatoReportable"; public static string Nombre = @"nombre"; public static string UnidadMedida = @"unidad_medida"; } #endregion #region Update PK Collections public void SetPKValues() { if (colPnRelNomencladorXDatoReportableRecords != null) { foreach (DalSic.PnRelNomencladorXDatoReportable item in colPnRelNomencladorXDatoReportableRecords) { if (item.IdDatoReportable != IdDatoReportable) { item.IdDatoReportable = IdDatoReportable; } } } if (colPnRelPrestacionXDatoReportableRecords != null) { foreach (DalSic.PnRelPrestacionXDatoReportable item in colPnRelPrestacionXDatoReportableRecords) { if (item.IdDatoReportable != IdDatoReportable) { item.IdDatoReportable = IdDatoReportable; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colPnRelNomencladorXDatoReportableRecords != null) { colPnRelNomencladorXDatoReportableRecords.SaveAll(); } if (colPnRelPrestacionXDatoReportableRecords != null) { colPnRelPrestacionXDatoReportableRecords.SaveAll(); } } #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AutoScaling.Model { /// <summary> /// Container for the parameters to the UpdateAutoScalingGroup operation. /// Updates the configuration for the specified Auto Scaling group. /// /// /// <para> /// To update an Auto Scaling group with a launch configuration with <code>InstanceMonitoring</code> /// set to <code>False</code>, you must first disable the collection of group metrics. /// Otherwise, you will get an error. If you have previously enabled the collection of /// group metrics, you can disable it using <a>DisableMetricsCollection</a>. /// </para> /// /// <para> /// The new settings are registered upon the completion of this call. Any launch configuration /// settings take effect on any triggers after this call returns. Scaling activities that /// are currently in progress aren't affected. /// </para> /// /// <para> /// Note the following: /// </para> /// <ul> <li> /// <para> /// If you specify a new value for <code>MinSize</code> without specifying a value for /// <code>DesiredCapacity</code>, and the new <code>MinSize</code> is larger than the /// current size of the group, we implicitly call <a>SetDesiredCapacity</a> to set the /// size of the group to the new value of <code>MinSize</code>. /// </para> /// </li> <li> /// <para> /// If you specify a new value for <code>MaxSize</code> without specifying a value for /// <code>DesiredCapacity</code>, and the new <code>MaxSize</code> is smaller than the /// current size of the group, we implicitly call <a>SetDesiredCapacity</a> to set the /// size of the group to the new value of <code>MaxSize</code>. /// </para> /// </li> <li> /// <para> /// All other optional parameters are left unchanged if not specified. /// </para> /// </li> </ul> /// </summary> public partial class UpdateAutoScalingGroupRequest : AmazonAutoScalingRequest { private string _autoScalingGroupName; private List<string> _availabilityZones = new List<string>(); private int? _defaultCooldown; private int? _desiredCapacity; private int? _healthCheckGracePeriod; private string _healthCheckType; private string _launchConfigurationName; private int? _maxSize; private int? _minSize; private string _placementGroup; private List<string> _terminationPolicies = new List<string>(); private string _vpcZoneIdentifier; /// <summary> /// Gets and sets the property AutoScalingGroupName. /// <para> /// The name of the Auto Scaling group. /// </para> /// </summary> public string AutoScalingGroupName { get { return this._autoScalingGroupName; } set { this._autoScalingGroupName = value; } } // Check to see if AutoScalingGroupName property is set internal bool IsSetAutoScalingGroupName() { return this._autoScalingGroupName != null; } /// <summary> /// Gets and sets the property AvailabilityZones. /// <para> /// One or more Availability Zones for the group. /// </para> /// </summary> public List<string> AvailabilityZones { get { return this._availabilityZones; } set { this._availabilityZones = value; } } // Check to see if AvailabilityZones property is set internal bool IsSetAvailabilityZones() { return this._availabilityZones != null && this._availabilityZones.Count > 0; } /// <summary> /// Gets and sets the property DefaultCooldown. /// <para> /// The amount of time, in seconds, after a scaling activity completes before another /// scaling activity can start. For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/Cooldown.html">Understanding /// Auto Scaling Cooldowns</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public int DefaultCooldown { get { return this._defaultCooldown.GetValueOrDefault(); } set { this._defaultCooldown = value; } } // Check to see if DefaultCooldown property is set internal bool IsSetDefaultCooldown() { return this._defaultCooldown.HasValue; } /// <summary> /// Gets and sets the property DesiredCapacity. /// <para> /// The number of EC2 instances that should be running in the Auto Scaling group. This /// number must be greater than or equal to the minimum size of the group and less than /// or equal to the maximum size of the group. /// </para> /// </summary> public int DesiredCapacity { get { return this._desiredCapacity.GetValueOrDefault(); } set { this._desiredCapacity = value; } } // Check to see if DesiredCapacity property is set internal bool IsSetDesiredCapacity() { return this._desiredCapacity.HasValue; } /// <summary> /// Gets and sets the property HealthCheckGracePeriod. /// <para> /// The amount of time, in seconds, that Auto Scaling waits before checking the health /// status of an instance. The grace period begins when the instance passes the system /// status and instance status checks from Amazon EC2. For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/healthcheck.html">Health /// Checks</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public int HealthCheckGracePeriod { get { return this._healthCheckGracePeriod.GetValueOrDefault(); } set { this._healthCheckGracePeriod = value; } } // Check to see if HealthCheckGracePeriod property is set internal bool IsSetHealthCheckGracePeriod() { return this._healthCheckGracePeriod.HasValue; } /// <summary> /// Gets and sets the property HealthCheckType. /// <para> /// The type of health check for the instances in the Auto Scaling group. The health check /// type can either be <code>EC2</code> for Amazon EC2 or <code>ELB</code> for Elastic /// Load Balancing. /// </para> /// </summary> public string HealthCheckType { get { return this._healthCheckType; } set { this._healthCheckType = value; } } // Check to see if HealthCheckType property is set internal bool IsSetHealthCheckType() { return this._healthCheckType != null; } /// <summary> /// Gets and sets the property LaunchConfigurationName. /// <para> /// The name of the launch configuration. /// </para> /// </summary> public string LaunchConfigurationName { get { return this._launchConfigurationName; } set { this._launchConfigurationName = value; } } // Check to see if LaunchConfigurationName property is set internal bool IsSetLaunchConfigurationName() { return this._launchConfigurationName != null; } /// <summary> /// Gets and sets the property MaxSize. /// <para> /// The maximum size of the Auto Scaling group. /// </para> /// </summary> public int MaxSize { get { return this._maxSize.GetValueOrDefault(); } set { this._maxSize = value; } } // Check to see if MaxSize property is set internal bool IsSetMaxSize() { return this._maxSize.HasValue; } /// <summary> /// Gets and sets the property MinSize. /// <para> /// The minimum size of the Auto Scaling group. /// </para> /// </summary> public int MinSize { get { return this._minSize.GetValueOrDefault(); } set { this._minSize = value; } } // Check to see if MinSize property is set internal bool IsSetMinSize() { return this._minSize.HasValue; } /// <summary> /// Gets and sets the property PlacementGroup. /// <para> /// The name of the placement group into which you'll launch your instances, if any. For /// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html">Placement /// Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public string PlacementGroup { get { return this._placementGroup; } set { this._placementGroup = value; } } // Check to see if PlacementGroup property is set internal bool IsSetPlacementGroup() { return this._placementGroup != null; } /// <summary> /// Gets and sets the property TerminationPolicies. /// <para> /// A standalone termination policy or a list of termination policies used to select /// the instance to terminate. The policies are executed in the order that they are listed. /// /// </para> /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-termination-policy.html">Choosing /// a Termination Policy for Your Auto Scaling Group</a> in the <i>Auto Scaling Developer /// Guide</i>. /// </para> /// </summary> public List<string> TerminationPolicies { get { return this._terminationPolicies; } set { this._terminationPolicies = value; } } // Check to see if TerminationPolicies property is set internal bool IsSetTerminationPolicies() { return this._terminationPolicies != null && this._terminationPolicies.Count > 0; } /// <summary> /// Gets and sets the property VPCZoneIdentifier. /// <para> /// The ID of the subnet, if you are launching into a VPC. You can specify several subnets /// in a comma-separated list. /// </para> /// /// <para> /// When you specify <code>VPCZoneIdentifier</code> with <code>AvailabilityZones</code>, /// ensure that the subnets' Availability Zones match the values you specify for <code>AvailabilityZones</code>. /// /// </para> /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto /// Scaling and Amazon Virtual Private Cloud</a> in the <i>Auto Scaling Developer Guide</i>. /// /// </para> /// </summary> public string VPCZoneIdentifier { get { return this._vpcZoneIdentifier; } set { this._vpcZoneIdentifier = value; } } // Check to see if VPCZoneIdentifier property is set internal bool IsSetVPCZoneIdentifier() { return this._vpcZoneIdentifier != null; } } }
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Collections.ObjectModel; using System.Collections; using System.Management.Automation.Runspaces; using System.Management.Automation.Host; using Pash.Implementation; namespace System.Management.Automation { internal class CmdletParameterBinder { private Dictionary<MemberInfo, object> _defaultValues; private Collection<MemberInfo> _boundParameters; private Dictionary<MemberInfo, object> _commandLineValuesBackup; private CmdletInfo _cmdletInfo; private Cmdlet _cmdlet; private CommandParameterSetInfo _activeSet; private CommandParameterSetInfo _defaultSet; private bool _hasDefaultSet; private List<CommandParameterSetInfo> _candidateParameterSets; private EngineIntrinsics _engineIntrinsics; private Dictionary<MemberInfo, object> _bindDestinationLookup; private CommandParameterSetInfo ActiveOrDefaultParameterSet { get { return _activeSet ?? DefaultParameterSet; } } private CommandParameterSetInfo DefaultParameterSet { get { if (_defaultSet == null && _hasDefaultSet) { _defaultSet = _cmdletInfo.GetDefaultParameterSet(); _hasDefaultSet = _defaultSet != null; } return _defaultSet; } } public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _bindDestinationLookup = new Dictionary<MemberInfo, object>(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); // make sure common parameters are set in the CommonParameter member object, not the cmdlet itself AddBindDestionations(CommonCmdletParameters.ParameterDiscovery, _cmdlet.CommonParameters); } /// <summary> /// Binds the parameters from the command line to the command. /// </summary> /// <remarks> /// All abount Cmdlet parameters: http://msdn2.microsoft.com/en-us/library/ms714433(VS.85).aspx /// About the lifecycle: http://msdn.microsoft.com/en-us/library/ms714429(v=vs.85).aspx /// </remarks> public void BindCommandLineParameters(CommandParameterCollection parameters) { // How command line parameters are bound: // In general: We will bind first named parameters, then positionals, and then maybe gather some. // While parameters are being bound, a list of _candidateParameterSets is maintained that keeps track // of those sets that are eligible for being taken. // As we might have an early choice that can be handled, an _activeSet is maintained in addition. // The _candidateSet will be restricted to the _activeSet if we found one early // Check if one obvious choice for a parameter set to be chosen (e.g. if there is only one) _activeSet = SelectObviousActiveParameterSet(); // Bind all named parameters, fail if some name is bound twice or if the selection is already ambiguos parameters = BindNamedParameters(parameters); // Bind positional parameters per parameter set // To do so, sort parameters of set by position, ignore bound parameters and set the first unbound position // Note: if we don't know the active parameter set, yet, we will bind it by Default, this is PS behavior // Binding will also restrict the candidate set and check for ambiguity parameters = BindPositionalParameters(parameters, ActiveOrDefaultParameterSet); // Bind dynamic parameters based on what's already bound. // TODO: this is also the place to support ShouldProcess parameters = BindDynamicParameters(parameters); // Make sure that there are no parameters that couldn't be bound ValidateAllParametersBound(parameters); // There might be parameter sets with parameters that are still unbound but will be set by pipeline. // If not, and if we have an (active or default) parameter set that is still a candidate, then get the // missing parameters. if (!HasParameterSetsWithUnboundMandatoryPipelineParameters() && _candidateParameterSets.Contains(ActiveOrDefaultParameterSet)) { HandleMissingMandatoryParameters(ActiveOrDefaultParameterSet, false, true); } // We finished binding parameters without pipeline. Therefore we can restrict the candidate set to those // sets that have all mandatory parameters set or are able to set them by pipeline RestrictCandidatesByBoundParameter(false); // Check if we have unbound parameters that can be set by pipeline. If not and we can already do // our final choice (and throw an error on problems) if (!HasUnboundPipelineParameters()) { DoFinalChoiceOfParameterSet(); } // Back up the bound parameters BackupCommandLineParameterValues(); // For the beginning phase: Tell the cmdlet which parameter set is likely to be used (if we know it) // If there is only one candidate, use it at least temporarily. Otherwise the active or default SetCmdletParameterSetName(_candidateParameterSets.Count == 1 ? _candidateParameterSets[0] : ActiveOrDefaultParameterSet); } /// <summary> /// Binds the parameter values provided by pipeline to be processed as a separate record /// </summary> /// <param name="curInput">Current input object from the pipeline</param> /// <param name="isFirstInPipeline">Whether the command is the first in pipeline</param> public void BindPipelineParameters(object pipelineInput, bool isFirstInPipeline) { // First reset to command line parameter values RestoreCommandLineParameterValues(); // How pipeline parameters are bound: // 1. If this command is the first in pipeline and there are no input objects: // Then get all left mandatory parameters for the (active or default) parameter set from UI if (pipelineInput == null && isFirstInPipeline) { if (ActiveOrDefaultParameterSet != null && _candidateParameterSets.Contains(ActiveOrDefaultParameterSet)) { HandleMissingMandatoryParameters(ActiveOrDefaultParameterSet, true, true); } } // 2. If there is an input object: else { // 1. Try to bind pipeline object properly in all candidate sets: with and without conversion bool success = BindPipelineParameters(AllParameters(_candidateParameterSets), pipelineInput); // 2. If we had no success, throw an error if (!success) { throw new ParameterBindingException("The pipeline input cannot be bound to any parameter"); } } // 3. This would be the place to process dynamic pipeline parameters // TODO: care about dynamic pipeline parameters // 4. If there is an active set, make sure all mandatory parameters are set if (_activeSet != null) { HandleMissingMandatoryParameters(_activeSet, true, false); } // 5. Check for candidate sets, *not* ignoring pipeline related parameters (as we might still have no active) // Note that this set automatically only contain the active set if there is one, so don't worry RestrictCandidatesByBoundParameter(true); // 6. Do the final choice of our parameter set DoFinalChoiceOfParameterSet(); } private void DoFinalChoiceOfParameterSet() { // If there is only one candidate: Choose that parameter set (This is also the case with an active set) if (_candidateParameterSets.Count == 1) { ChooseParameterSet(_candidateParameterSets[0]); return; } // If there is more than one candidate: else if (_candidateParameterSets.Count > 1) { // If the default set is among the candidates, choose it if (DefaultParameterSet != null && _candidateParameterSets.Contains(DefaultParameterSet)) { ChooseParameterSet(DefaultParameterSet); return; } // If the default set is the AllParameter set then choose it. else if (DefaultParameterSet != null && (DefaultParameterSet.IsAllParameterSets)) { ChooseParameterSet(DefaultParameterSet); return; } // Otherwise we could choose multiple sets, so throw an ambigiuous error else { ThrowAmbiguousParameterSetException(); } } // If the candidate set is empty: Throw an error and tell the user what's missing else { ThrowMissingParametersExcpetion(ActiveOrDefaultParameterSet); } } IEnumerable<CommandParameterInfo> AllParameters(IEnumerable<CommandParameterSetInfo> sources) { IEnumerable<CommandParameterInfo> allParams = Enumerable.Empty<CommandParameterInfo>(); foreach (var curParamSet in sources) { allParams = allParams.Union(curParamSet.Parameters); } return allParams; } private CommandParameterCollection BindDynamicParameters(CommandParameterCollection parameters) { var dynamicParamsCmdlet = _cmdlet as IDynamicParameters; if (dynamicParamsCmdlet == null) // no support for dynamic parameters { return parameters; } // get the object with dynamic parameters var parameterObject = dynamicParamsCmdlet.GetDynamicParameters(); if (parameterObject == null) { return parameters; } var discovery = new CommandParameterDiscovery(parameterObject.GetType()); // add the parameters to the cmdletInfo _cmdletInfo.AddParametersToAllSets(discovery); // as we updated parameter sets, we need to rebuild some cached values _activeSet = _activeSet == null ? null : GetParameterSet(_activeSet.Name); _defaultSet = _defaultSet == null ? null : GetParameterSet(_defaultSet.Name); _candidateParameterSets = (from p in _candidateParameterSets select GetParameterSet(p.Name)).ToList(); AddBindDestionations(discovery, parameterObject); // now try to rebind the parameters parameters = BindNamedParameters(parameters); return BindPositionalParameters(parameters, ActiveOrDefaultParameterSet); } private CommandParameterSetInfo GetParameterSet(string name) { return _cmdletInfo.ParameterSets.Where(p => p.Name.Equals(name)).First(); } private void ValidateAllParametersBound(CommandParameterCollection parameters) { if (parameters.Count < 1) { return; } var curParam = parameters[0]; if (!String.IsNullOrEmpty(curParam.Name)) { var msg = String.Format("No parameter was found that matches the name or alias '{0}'.", curParam.Name); throw new ParameterBindingException(msg, "ParameterNotFound"); } else { var msg = String.Format("Positional parameter not found for provided argument '{0}'", curParam.Value); throw new ParameterBindingException(msg, "PositionalParameterNotFound"); } } private void SetCmdletParameterSetName(CommandParameterSetInfo chosenSet) { if (_cmdlet is PSCmdlet) { ((PSCmdlet)_cmdlet).ParameterSetName = chosenSet != null ? chosenSet.Name : ParameterAttribute.AllParameterSets; } } private void ChooseParameterSet(CommandParameterSetInfo chosenSet) { _activeSet = chosenSet; _candidateParameterSets.Clear(); _candidateParameterSets.Add(chosenSet); SetCmdletParameterSetName(chosenSet); } private void ThrowMissingParametersExcpetion(CommandParameterSetInfo paramSet) { var missing = GetMandatoryUnboundParameters(paramSet, true); var msg = "Missing value for mandatory parameter(s): " + String.Join(", ", missing); throw new ParameterBindingException(msg, "MissingMandatoryParameter"); } private CommandParameterCollection BindNamedParameters(CommandParameterCollection parameters) { var namedParameters = from parameter in parameters where !String.IsNullOrEmpty(parameter.Name) select parameter; var parametersLeft = new CommandParameterCollection(parameters); foreach (var curParam in namedParameters) { string curName = curParam.Name; // try to get the parameter from any set. throws an error if the name is ambiguous or doesn't exist var paramInfo = _cmdletInfo.LookupParameter(curName); if (paramInfo != null) { BindParameter(paramInfo, curParam.Value, true); parametersLeft.Remove(curParam); } } return parametersLeft; } private void ThrowAmbiguousParameterSetException() { throw new ParameterBindingException("The parameter set to be used cannot be resolved.", "AmbiguousParameterSet"); } private CommandParameterCollection BindPositionalParameters(CommandParameterCollection parameters, CommandParameterSetInfo parameterSet) { var parametersWithoutName = from param in parameters where String.IsNullOrEmpty(param.Name) select param; if (parameterSet == null) { if (parametersWithoutName.Any()) { ThrowAmbiguousParameterSetException(); } return parameters; } var positionals = (from param in parameterSet.Parameters where param.Position >= 0 && !_boundParameters.Contains(param.MemberInfo) orderby param.Position ascending select param).ToList(); int i = 0; var parametersLeft = new CommandParameterCollection(parameters); foreach (var curParam in parametersWithoutName) { if (i >= positionals.Count) { break; // can't bind it } BindParameter(positionals[i], curParam.Value, true); parametersLeft.Remove(curParam); i++; } return parametersLeft; } private void HandleMissingMandatoryParameters(CommandParameterSetInfo parameterSet, bool considerPipeline, bool askUser) { // select mandatory parametes var unsetMandatories = GetMandatoryUnboundParameters(parameterSet, considerPipeline).ToList(); // check if we got something to do, otherwise we're fine if (unsetMandatories.Count == 0) { return; } Dictionary<CommandParameterInfo, PSObject> values = null; if (askUser) { // try to get this value from UI values = GatherParameterValues(unsetMandatories); } if (values == null) { var parameterNames = from cmdInfo in unsetMandatories select "'" + cmdInfo.Name + "'"; var missingNames = String.Join(", ", parameterNames); var msg = String.Format("Missing value for mandatory parameters {0}.", missingNames); throw new ParameterBindingException(msg, "MissingMandatoryParameters"); } foreach (var pair in values) { if (pair.Value == null) { // WORKAROUND: PS throws a MethodInvocationException when binding pipeline parameters // that is when a user shouldn't be asked anymore... let's do the same if (askUser) { var msg = String.Format("Missing value for mandatory parameter '{0}'.", pair.Key.Name); throw new ParameterBindingException(msg, "MissingMandatoryParameter"); } else { var msg = "The input object cannot be bound as it doesn't provide some mandatory information: " + pair.Key.Name; throw new MethodInvocationException(msg); } } BindParameter(pair.Key, pair.Value, true); } } private bool HasUnboundPipelineParameters() { foreach (var curParamSet in _candidateParameterSets) { var unboundByPipeline = from param in curParamSet.Parameters where !_boundParameters.Contains(param.MemberInfo) && (param.ValueFromPipeline || param.ValueFromPipelineByPropertyName) select param; if (unboundByPipeline.Any()) { return true; } } return false; } private bool HasParameterSetsWithUnboundMandatoryPipelineParameters() { foreach (var curParamSet in _candidateParameterSets) { var unboundMandatoriesByPipeline = from param in curParamSet.Parameters where param.IsMandatory && !_boundParameters.Contains(param.MemberInfo) && (param.ValueFromPipeline || param.ValueFromPipelineByPropertyName) select param; var unboundMandatoriesWithoutPipeline = from param in curParamSet.Parameters where param.IsMandatory && !_boundParameters.Contains(param.MemberInfo) && !(param.ValueFromPipeline || param.ValueFromPipelineByPropertyName) select param; if (unboundMandatoriesByPipeline.Any() && !unboundMandatoriesWithoutPipeline.Any()) { return true; } } return false; } // restricts the candidate parameter sets by the newly bound parameters private void RestrictCandidatesByBoundParameter(CommandParameterInfo info) { var setsContaining = from paramSet in _cmdletInfo.ParameterSets where paramSet.Contains(info) select paramSet; _candidateParameterSets = _candidateParameterSets.Intersect(setsContaining).ToList(); if (_candidateParameterSets.Count == 0) { ThrowAmbiguousParameterSetException(); } else if (_candidateParameterSets.Count == 1) { _activeSet = _candidateParameterSets[0]; } } // restricts candidates by s.t. it only considers those parameter sets that have enough bound parameters private void RestrictCandidatesByBoundParameter(bool pipelineProcessed) { // if we already found an active set, then this should be the only real candidate if (_activeSet != null) { _candidateParameterSets = new List<CommandParameterSetInfo>() { _activeSet }; return; } var newCandidates = new List<CommandParameterSetInfo>(); foreach (var curParamSet in _candidateParameterSets) { var unboundMandatories = GetMandatoryUnboundParameters(curParamSet, pipelineProcessed); if (!unboundMandatories.Any() && !curParamSet.IsAllParameterSets) { newCandidates.Add(curParamSet); } } _candidateParameterSets = newCandidates; } bool BindPipelineParameters(IEnumerable<CommandParameterInfo> parameterSet, object pipelineInput) { var valueByPipeParams = (from param in parameterSet where param.ValueFromPipeline select param); var valuesByNamedPipeParams = from param in parameterSet where param.ValueFromPipelineByPropertyName select param; // first try to bind the parameter without conversion, then with conversion foreach (var doConvert in new bool[] { false, true }) { // 1. Try to bind the object to the parameter *without* type conversion with "ValueFromPipeline" param foreach (var param in valueByPipeParams) { if (TryBindParameter(param, pipelineInput, doConvert)) { return true; } } // 2. If this is not sucessfull, try to bind the object to parameters with "ValueFromPipelineByPropertyName" // *without" conversion, if exists if (valuesByNamedPipeParams.Any() && TryBindObjectAsParameters(valuesByNamedPipeParams, pipelineInput, doConvert)) { return true; } } return false; } private Dictionary<CommandParameterInfo, PSObject> GatherParameterValues(IEnumerable<CommandParameterInfo> parameters) { // check first if we have a host to interact with if (_cmdlet.PSHostInternal == null) { return null; } var fieldDescs = new Collection<FieldDescription>( (from param in parameters select new FieldDescription(param.Name, param.Name, param.ParameterType, param.HelpMessage, null, param.IsMandatory, param.Attributes) ).ToList() ); //var caption = String.Format("Cmdlet {0} at position {1} in the pipeline", _cmdletInfo.Name, ???); // we don't know the position in the pipeline var caption = String.Format("Cmdlet {0} in the pipeline", _cmdletInfo.Name); var message = "Please enter values for the following parameters:"; try { var values = _cmdlet.PSHostInternal.UI.Prompt(caption, message, fieldDescs); var lookupDict = new Dictionary<string, CommandParameterInfo>(); foreach (var info in parameters) { lookupDict[info.Name] = info; } var returnDict = new Dictionary<CommandParameterInfo, PSObject>(); foreach (var pair in values) { returnDict[lookupDict[pair.Key]] = pair.Value; } return returnDict; } catch (HostException) { return null; } catch (NotImplementedException) { return null; } } private IEnumerable<CommandParameterInfo> GetMandatoryUnboundParameters(CommandParameterSetInfo parameterSet, bool considerPipeline) { if (parameterSet == null) { return Enumerable.Empty<CommandParameterInfo>(); } return from param in parameterSet.Parameters where param.IsMandatory && !_boundParameters.Contains(param.MemberInfo) && (considerPipeline || !(param.ValueFromPipeline || param.ValueFromPipelineByPropertyName) ) select param; } private CommandParameterSetInfo SelectObviousActiveParameterSet() { // if we only have one parameter set, this is always the active one (e.g. AllParametersSets) CommandParameterSetInfo active = null; var setCount = _cmdletInfo.ParameterSets.Count; if (setCount == 1) { active = _cmdletInfo.ParameterSets[0]; } // if we have two sets and one is AllParametersSets, then the other one is naturally the default else if (setCount == 2) { var firstSet = _cmdletInfo.ParameterSets[0]; var secondSet = _cmdletInfo.ParameterSets[1]; if (firstSet.IsAllParameterSets) { active = secondSet; } else if (secondSet.IsAllParameterSets) { active = firstSet; } } if (active != null) { _candidateParameterSets = new List<CommandParameterSetInfo>() { active }; } return active; } private bool TryBindParameter(CommandParameterInfo info, object value, bool doConvert) { try { BindParameter(info, value, doConvert); return true; } catch (Exception) { return false; } } private void BindParameter(CommandParameterInfo info, object value, bool doConvert) { var memberInfo = info.MemberInfo; if (_boundParameters.Contains(memberInfo)) { var msg = String.Format("Parameter '{0}' has already been bound!", info.Name); throw new ParameterBindingException(msg); } foreach (var attr in info.TransformationAttributes) { value = attr.Transform(_engineIntrinsics, value); } // ConvertTo throws an exception if conversion isn't possible. That's just fine. if (doConvert) { value = LanguagePrimitives.ConvertTo(value, info.ParameterType); } // TODO: validate value with Attributes (ValidateNotNullOrEmpty, etc) SetCommandValue(memberInfo, value); // make sure to update the candidate set to only consider parameter sets with the newly bound parameter RestrictCandidatesByBoundParameter(info); _boundParameters.Add(memberInfo); } private bool TryBindObjectAsParameters(IEnumerable<CommandParameterInfo> parameters, object valueObject, bool doConvert) { var values = PSObject.AsPSObject(valueObject); var success = false; foreach (var param in parameters) { var aliases = new List<string>(param.Aliases); aliases.Add(param.Name); foreach (var curAlias in aliases) { var propertyInfo = values.Properties[curAlias]; if (propertyInfo == null) { continue; } var curValue = propertyInfo.Value; bool hadSuccess = TryBindParameter(param, curValue, doConvert); if (hadSuccess) { success = true; break; } } } return success; } private void SetCommandValue(MemberInfo info, object value) { // make a backup of the default values first, if we don't have one if (!_defaultValues.ContainsKey(info)) { _defaultValues[info] = GetCommandValue(info); } // now set the field or property try { if (info.MemberType == MemberTypes.Field) { FieldInfo fieldInfo = info as FieldInfo; fieldInfo.SetValue(GetBindDestination(info), value); } else if (info.MemberType == MemberTypes.Property) { PropertyInfo propertyInfo = info as PropertyInfo; propertyInfo.SetValue(GetBindDestination(info), value, null); } else { throw new Exception("SetValue only implemented for fields and properties"); } } catch (ArgumentException) { var msg = String.Format("Can't bind value to parameter '{0}'", info.Name); throw new ParameterBindingException(msg, "BindingFailed"); } } private object GetCommandValue(MemberInfo info) { if (info.MemberType == MemberTypes.Field) { FieldInfo fieldInfo = info as FieldInfo; return fieldInfo.GetValue(GetBindDestination(info)); } else if (info.MemberType == MemberTypes.Property) { PropertyInfo propertyInfo = info as PropertyInfo; return propertyInfo.GetValue(GetBindDestination(info), null); } else { throw new Exception("SetValue only implemented for fields and properties"); } } private object GetBindDestination(MemberInfo info) { if (_bindDestinationLookup.ContainsKey(info)) { return _bindDestinationLookup[info]; } return _cmdlet; } void AddBindDestionations(CommandParameterDiscovery parameterDiscovery, object destination) { foreach (var parameter in parameterDiscovery.NamedParameters.Values) { _bindDestinationLookup[parameter.MemberInfo] = destination; } } /// <summary> /// Makes and internal backup of the command line parameter values, so they can be restored /// </summary> private void BackupCommandLineParameterValues() { _commandLineValuesBackup.Clear(); foreach (var info in _boundParameters) { _commandLineValuesBackup[info] = GetCommandValue(info); } } /// <summary> /// Restores parameters to those provided by command line, so multiple /// records can be processed without influencing each other /// </summary> public void RestoreCommandLineParameterValues() { foreach (var bound in _boundParameters) { object restoredVaue = _commandLineValuesBackup.ContainsKey(bound) ? _commandLineValuesBackup[bound] : _defaultValues[bound]; if (GetCommandValue(bound) != restoredVaue) { SetCommandValue(bound, restoredVaue); } } // reset the bound parameter list _boundParameters.Clear(); foreach (MemberInfo info in _commandLineValuesBackup.Keys) { _boundParameters.Add(info); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Collections.Generic; using System.Runtime.Serialization.Diagnostics.Application; using System.Runtime.Serialization.Formatters; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; #if USE_REFEMIT public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext #else internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext #endif { static Hashtable dataContractTypeCache = new Hashtable(); bool preserveObjectReferences; protected IDataContractSurrogate dataContractSurrogate; SerializationMode mode; SerializationBinder binder; ISurrogateSelector surrogateSelector; FormatterAssemblyStyle assemblyFormat; Hashtable surrogateDataContracts; internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.mode = SerializationMode.SharedContract; this.preserveObjectReferences = serializer.PreserveObjectReferences; this.dataContractSurrogate = serializer.DataContractSurrogate; } internal XmlObjectSerializerReadContextComplex(NetDataContractSerializer serializer) : base(serializer) { this.mode = SerializationMode.SharedType; this.preserveObjectReferences = true; this.binder = serializer.Binder; this.surrogateSelector = serializer.SurrogateSelector; this.assemblyFormat = serializer.AssemblyFormat; } internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override SerializationMode Mode { get { return mode; } } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, null /*type*/, ref surrogateDataContracts); } if (dataContract != null) { if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(id, typeHandle); } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, type, ref surrogateDataContracts); } if (dataContract != null) { if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(typeHandle, type); } public override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns) { if (mode == SerializationMode.SharedContract) { if (dataContractSurrogate == null) return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns); } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { if (mode == SerializationMode.SharedContract) { if (dataContractSurrogate == null) return base.InternalDeserialize(xmlReader, declaredType, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (mode == SerializationMode.SharedContract) { if (dataContractSurrogate == null) return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } } object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns) { object retObj = null; if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj)) return retObj; DataContract dataContract; string assemblyName = attributes.ClrAssembly; string typeName = attributes.ClrType; if (assemblyName != null && typeName != null) { Assembly assembly; Type type; dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type); if (dataContract == null) { if (assembly == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.AssemblyNotFound, assemblyName))); if (type == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ClrTypeNotFound, assembly.FullName, typeName))); } //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array if (declaredType != null && declaredType.IsArray) dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle); } else { if (assemblyName != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)))); else if (typeName != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)))); else if (declaredType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)))); dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle); } return ReadDataContractValue(dataContract, xmlReader); } object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns) { if (TD.DCDeserializeWithSurrogateStartIsEnabled()) { TD.DCDeserializeWithSurrogateStart(declaredType.FullName); } DataContract dataContract = surrogateDataContract ?? GetDataContract(DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, declaredType)); if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType)))); } ReadAttributes(xmlReader); string objectId = GetObjectId(); object oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); object obj = DataContractSurrogateCaller.GetDeserializedObject(dataContractSurrogate, oldObj, dataContract.UnderlyingType, declaredType); ReplaceDeserializedObject(objectId, oldObj, obj); if (TD.DCDeserializeWithSurrogateStopIsEnabled()) { TD.DCDeserializeWithSurrogateStop(); } return obj; } Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly) { assembly = null; Type type = null; if (binder != null) type = binder.BindToType(assemblyName, typeName); if (type == null) { XmlObjectDataContractTypeKey key = new XmlObjectDataContractTypeKey(assemblyName, typeName); XmlObjectDataContractTypeInfo dataContractTypeInfo = (XmlObjectDataContractTypeInfo)dataContractTypeCache[key]; if (dataContractTypeInfo == null) { if (assemblyFormat == FormatterAssemblyStyle.Full) { if (assemblyName == Globals.MscorlibAssemblyName) { assembly = Globals.TypeOfInt.Assembly; } else { assembly = Assembly.Load(assemblyName); } if (assembly != null) type = assembly.GetType(typeName); } else { assembly = XmlObjectSerializerReadContextComplex.ResolveSimpleAssemblyName(assemblyName); if (assembly != null) { // Catching any exceptions that could be thrown from a failure on assembly load // This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available try { type = assembly.GetType(typeName); } catch (TypeLoadException) { } catch (FileNotFoundException) { } catch (FileLoadException) { } catch (BadImageFormatException) { } if (type == null) { type = Type.GetType(typeName, XmlObjectSerializerReadContextComplex.ResolveSimpleAssemblyName, new TopLevelAssemblyTypeResolver(assembly).ResolveType, false /* throwOnError */); } } } if (type != null) { CheckTypeForwardedTo(assembly, type.Assembly, type); dataContractTypeInfo = new XmlObjectDataContractTypeInfo(assembly, type); lock (dataContractTypeCache) { if (!dataContractTypeCache.ContainsKey(key)) { dataContractTypeCache[key] = dataContractTypeInfo; } } } } else { assembly = dataContractTypeInfo.Assembly; type = dataContractTypeInfo.Type; } } return type; } DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type) { type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly); if (type != null) { return GetDataContract(type); } return null; } protected override DataContract ResolveDataContractFromTypeName() { if (mode == SerializationMode.SharedContract) { return base.ResolveDataContractFromTypeName(); } else { if (attributes.ClrAssembly != null && attributes.ClrType != null) { Assembly assembly; Type type; return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type); } } return null; } [Fx.Tag.SecurityNote(Critical = "Calls the critical methods of ISurrogateSelector", Safe = "Demands for FullTrust")] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] [MethodImpl(MethodImplOptions.NoInlining)] bool CheckIfTypeSerializableForSharedTypeMode(Type memberType) { Fx.Assert(surrogateSelector != null, "Method should not be called when surrogateSelector is null."); ISurrogateSelector surrogateSelectorNotUsed; return (surrogateSelector.GetSurrogate(memberType, GetStreamingContext(), out surrogateSelectorNotUsed) != null); } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (mode == SerializationMode.SharedType && surrogateSelector != null && CheckIfTypeSerializableForSharedTypeMode(memberType)) { return; } else { if (dataContractSurrogate != null) { while (memberType.IsArray) memberType = memberType.GetElementType(); memberType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, memberType); if (!DataContract.IsTypeSerializable(memberType)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TypeNotSerializable, memberType))); return; } } base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } internal override Type GetSurrogatedType(Type type) { if (dataContractSurrogate == null) { return base.GetSurrogatedType(type); } else { type = DataContract.UnwrapNullableType(type); Type surrogateType = DataContractSerializer.GetSurrogatedType(dataContractSurrogate, type); if (this.IsGetOnlyCollection && surrogateType != type) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(type)))); } else { return surrogateType; } } } #if USE_REFEMIT public override int GetArraySize() #else internal override int GetArraySize() #endif { return preserveObjectReferences ? attributes.ArraySZSize : -1; } static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName) { return ResolveSimpleAssemblyName(assemblyName.FullName); } static Assembly ResolveSimpleAssemblyName(string assemblyName) { Assembly assembly; if (assemblyName == Globals.MscorlibAssemblyName) { assembly = Globals.TypeOfInt.Assembly; } else { assembly = Assembly.LoadWithPartialName(assemblyName); if (assembly == null) { AssemblyName an = new AssemblyName(assemblyName); an.Version = null; assembly = Assembly.LoadWithPartialName(an.FullName); } } return assembly; } [Fx.Tag.SecurityNote(Critical = "Gets the SecurityCritical PermissionSet for sourceAssembly and destinationAssembly.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destinationAssembly, Type resolvedType) { if (sourceAssembly != destinationAssembly && !NetDataContractSerializer.UnsafeTypeForwardingEnabled && !sourceAssembly.IsFullyTrusted) { #if !NO_DESKTOP_SECURITY // We have a TypeForwardedTo attribute if (!destinationAssembly.PermissionSet.IsSubsetOf(sourceAssembly.PermissionSet)) { // We look for a matching TypeForwardedFrom attribute TypeInformation typeInfo = NetDataContractSerializer.GetTypeInformation(resolvedType); if (typeInfo.HasTypeForwardedFrom) { Assembly typeForwardedFromAssembly = null; try { // if this Assembly.Load fails, we still want to throw security exception typeForwardedFromAssembly = Assembly.Load(typeInfo.AssemblyString); } catch { } if (typeForwardedFromAssembly == sourceAssembly) { return; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.CannotDeserializeForwardedType, DataContract.GetClrTypeFullName(resolvedType)))); } #endif } } sealed class TopLevelAssemblyTypeResolver { Assembly topLevelAssembly; public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly) { this.topLevelAssembly = topLevelAssembly; } public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase) { if (assembly == null) assembly = topLevelAssembly; return assembly.GetType(simpleTypeName, false, ignoreCase); } } class XmlObjectDataContractTypeInfo { Assembly assembly; Type type; public XmlObjectDataContractTypeInfo(Assembly assembly, Type type) { this.assembly = assembly; this.type = type; } public Assembly Assembly { get { return this.assembly; } } public Type Type { get { return this.type; } } } class XmlObjectDataContractTypeKey { string assemblyName; string typeName; public XmlObjectDataContractTypeKey(string assemblyName, string typeName) { this.assemblyName = assemblyName; this.typeName = typeName; } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) return true; XmlObjectDataContractTypeKey other = obj as XmlObjectDataContractTypeKey; if (other == null) return false; if (this.assemblyName != other.assemblyName) return false; if (this.typeName != other.typeName) return false; return true; } public override int GetHashCode() { int hashCode = 0; if (this.assemblyName != null) hashCode = this.assemblyName.GetHashCode(); if (this.typeName != null) hashCode ^= this.typeName.GetHashCode(); return hashCode; } } } }
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFAB_STATIC_API using PlayFab.GroupsModels; using PlayFab.Internal; #pragma warning disable 0649 using System; // This is required for the Obsolete Attribute flag // which is not always present in all API's #pragma warning restore 0649 using System.Collections.Generic; using System.Threading.Tasks; namespace PlayFab { /// <summary> /// The Groups API is designed for any permanent or semi-permanent collections of Entities (players, or non-players). If you /// want to make Guilds/Clans/Corporations/etc., then you should use groups. Groups can also be used to make chatrooms, /// parties, or any other persistent collection of entities. /// </summary> public static class PlayFabGroupsAPI { /// <summary> /// Verify entity login. /// </summary> public static bool IsEntityLoggedIn() { return PlayFabSettings.staticPlayer.IsEntityLoggedIn(); } /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public static void ForgetAllCredentials() { PlayFabSettings.staticPlayer.ForgetAllCredentials(); } /// <summary> /// Accepts an outstanding invitation to to join a group /// </summary> public static async Task<PlayFabResult<EmptyResponse>> AcceptGroupApplicationAsync(AcceptGroupApplicationRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/AcceptGroupApplication", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Accepts an invitation to join a group /// </summary> public static async Task<PlayFabResult<EmptyResponse>> AcceptGroupInvitationAsync(AcceptGroupInvitationRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/AcceptGroupInvitation", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Adds members to a group or role. /// </summary> public static async Task<PlayFabResult<EmptyResponse>> AddMembersAsync(AddMembersRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/AddMembers", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Applies to join a group /// </summary> public static async Task<PlayFabResult<ApplyToGroupResponse>> ApplyToGroupAsync(ApplyToGroupRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ApplyToGroup", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ApplyToGroupResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ApplyToGroupResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ApplyToGroupResponse> { Result = result, CustomData = customData }; } /// <summary> /// Blocks a list of entities from joining a group. /// </summary> public static async Task<PlayFabResult<EmptyResponse>> BlockEntityAsync(BlockEntityRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/BlockEntity", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Changes the role membership of a list of entities from one role to another. /// </summary> public static async Task<PlayFabResult<EmptyResponse>> ChangeMemberRoleAsync(ChangeMemberRoleRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ChangeMemberRole", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Creates a new group. /// </summary> public static async Task<PlayFabResult<CreateGroupResponse>> CreateGroupAsync(CreateGroupRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/CreateGroup", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<CreateGroupResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<CreateGroupResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CreateGroupResponse> { Result = result, CustomData = customData }; } /// <summary> /// Creates a new group role. /// </summary> public static async Task<PlayFabResult<CreateGroupRoleResponse>> CreateRoleAsync(CreateGroupRoleRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/CreateRole", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<CreateGroupRoleResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<CreateGroupRoleResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CreateGroupRoleResponse> { Result = result, CustomData = customData }; } /// <summary> /// Deletes a group and all roles, invitations, join requests, and blocks associated with it. /// </summary> public static async Task<PlayFabResult<EmptyResponse>> DeleteGroupAsync(DeleteGroupRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/DeleteGroup", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Deletes an existing role in a group. /// </summary> public static async Task<PlayFabResult<EmptyResponse>> DeleteRoleAsync(DeleteRoleRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/DeleteRole", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets information about a group and its roles /// </summary> public static async Task<PlayFabResult<GetGroupResponse>> GetGroupAsync(GetGroupRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/GetGroup", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetGroupResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetGroupResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetGroupResponse> { Result = result, CustomData = customData }; } /// <summary> /// Invites a player to join a group /// </summary> public static async Task<PlayFabResult<InviteToGroupResponse>> InviteToGroupAsync(InviteToGroupRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/InviteToGroup", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<InviteToGroupResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InviteToGroupResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<InviteToGroupResponse> { Result = result, CustomData = customData }; } /// <summary> /// Checks to see if an entity is a member of a group or role within the group /// </summary> public static async Task<PlayFabResult<IsMemberResponse>> IsMemberAsync(IsMemberRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/IsMember", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<IsMemberResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<IsMemberResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<IsMemberResponse> { Result = result, CustomData = customData }; } /// <summary> /// Lists all outstanding requests to join a group /// </summary> public static async Task<PlayFabResult<ListGroupApplicationsResponse>> ListGroupApplicationsAsync(ListGroupApplicationsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ListGroupApplications", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ListGroupApplicationsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ListGroupApplicationsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListGroupApplicationsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Lists all entities blocked from joining a group /// </summary> public static async Task<PlayFabResult<ListGroupBlocksResponse>> ListGroupBlocksAsync(ListGroupBlocksRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ListGroupBlocks", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ListGroupBlocksResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ListGroupBlocksResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListGroupBlocksResponse> { Result = result, CustomData = customData }; } /// <summary> /// Lists all outstanding invitations for a group /// </summary> public static async Task<PlayFabResult<ListGroupInvitationsResponse>> ListGroupInvitationsAsync(ListGroupInvitationsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ListGroupInvitations", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ListGroupInvitationsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ListGroupInvitationsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListGroupInvitationsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Lists all members for a group /// </summary> public static async Task<PlayFabResult<ListGroupMembersResponse>> ListGroupMembersAsync(ListGroupMembersRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ListGroupMembers", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ListGroupMembersResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ListGroupMembersResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListGroupMembersResponse> { Result = result, CustomData = customData }; } /// <summary> /// Lists all groups and roles for an entity /// </summary> public static async Task<PlayFabResult<ListMembershipResponse>> ListMembershipAsync(ListMembershipRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ListMembership", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ListMembershipResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ListMembershipResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListMembershipResponse> { Result = result, CustomData = customData }; } /// <summary> /// Lists all outstanding invitations and group applications for an entity /// </summary> public static async Task<PlayFabResult<ListMembershipOpportunitiesResponse>> ListMembershipOpportunitiesAsync(ListMembershipOpportunitiesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/ListMembershipOpportunities", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ListMembershipOpportunitiesResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ListMembershipOpportunitiesResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListMembershipOpportunitiesResponse> { Result = result, CustomData = customData }; } /// <summary> /// Removes an application to join a group /// </summary> public static async Task<PlayFabResult<EmptyResponse>> RemoveGroupApplicationAsync(RemoveGroupApplicationRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/RemoveGroupApplication", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Removes an invitation join a group /// </summary> public static async Task<PlayFabResult<EmptyResponse>> RemoveGroupInvitationAsync(RemoveGroupInvitationRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/RemoveGroupInvitation", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Removes members from a group. /// </summary> public static async Task<PlayFabResult<EmptyResponse>> RemoveMembersAsync(RemoveMembersRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/RemoveMembers", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Unblocks a list of entities from joining a group /// </summary> public static async Task<PlayFabResult<EmptyResponse>> UnblockEntityAsync(UnblockEntityRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/UnblockEntity", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<EmptyResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<EmptyResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<EmptyResponse> { Result = result, CustomData = customData }; } /// <summary> /// Updates non-membership data about a group. /// </summary> public static async Task<PlayFabResult<UpdateGroupResponse>> UpdateGroupAsync(UpdateGroupRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/UpdateGroup", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<UpdateGroupResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<UpdateGroupResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateGroupResponse> { Result = result, CustomData = customData }; } /// <summary> /// Updates metadata about a role. /// </summary> public static async Task<PlayFabResult<UpdateGroupRoleResponse>> UpdateRoleAsync(UpdateGroupRoleRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Group/UpdateRole", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<UpdateGroupRoleResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<UpdateGroupRoleResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateGroupRoleResponse> { Result = result, CustomData = customData }; } } } #endif
//#define TRACE_SERIALIZATION using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using Orleans.CodeGeneration; using Orleans.GrainDirectory; using Orleans.Runtime; namespace Orleans.Serialization { /// <summary> /// Reader for Orleans binary token streams /// </summary> public class BinaryTokenStreamReader { private IList<ArraySegment<byte>> buffers; private int buffersCount; private int currentSegmentIndex; private ArraySegment<byte> currentSegment; private byte[] currentBuffer; private int currentOffset; private int currentSegmentOffset; private int currentSegmentCount; private int totalProcessedBytes; private int currentSegmentOffsetPlusCount; private int totalLength; private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]); private static readonly byte[] emptyByteArray = new byte[0]; /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input byte array. /// </summary> /// <param name="input">Input binary data to be tokenized.</param> public BinaryTokenStreamReader(byte[] input) : this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) }) { } /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input buffers. /// </summary> /// <param name="buffs">The list of ArraySegments to use for the data.</param> public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs) { this.Reset(buffs); Trace("Starting new stream reader"); } /// <summary> /// Resets this instance with the provided data. /// </summary> /// <param name="buffs">The underlying buffers.</param> public void Reset(IList<ArraySegment<byte>> buffs) { buffers = buffs; totalProcessedBytes = 0; currentSegmentIndex = 0; InitializeCurrentSegment(0); totalLength = buffs.Sum(b => b.Count); buffersCount = buffs.Count; } private void InitializeCurrentSegment(int segmentIndex) { currentSegment = buffers[segmentIndex]; currentBuffer = currentSegment.Array; currentOffset = currentSegment.Offset; currentSegmentOffset = currentOffset; currentSegmentCount = currentSegment.Count; currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount; } /// <summary> /// Create a new BinaryTokenStreamReader to read from the specified input buffer. /// </summary> /// <param name="buff">ArraySegment to use for the data.</param> public BinaryTokenStreamReader(ArraySegment<byte> buff) : this(new[] { buff }) { } /// <summary> Current read position in the stream. </summary> public int CurrentPosition => currentOffset + totalProcessedBytes - currentSegmentOffset; /// <summary> /// Gets the total length. /// </summary> public int Length => this.totalLength; /// <summary> /// Creates a copy of the current stream reader. /// </summary> /// <returns>The new copy</returns> public BinaryTokenStreamReader Copy() { return new BinaryTokenStreamReader(this.buffers); } private void StartNextSegment() { totalProcessedBytes += currentSegment.Count; currentSegmentIndex++; if (currentSegmentIndex < buffersCount) { InitializeCurrentSegment(currentSegmentIndex); } else { currentSegment = emptySegment; currentBuffer = null; currentOffset = 0; currentSegmentOffset = 0; currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount; } } private byte[] CheckLength(int n, out int offset) { bool ignore; byte[] res; if (TryCheckLengthFast(n, out res, out offset, out ignore)) { return res; } return CheckLength(n, out offset, out ignore); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryCheckLengthFast(int n, out byte[] res, out int offset, out bool safeToUse) { safeToUse = false; res = null; offset = 0; var nextOffset = currentOffset + n; if (nextOffset <= currentSegmentOffsetPlusCount) { offset = currentOffset; currentOffset = nextOffset; res = currentBuffer; return true; } return false; } private byte[] CheckLength(int n, out int offset, out bool safeToUse) { safeToUse = false; offset = 0; if (currentOffset == currentSegmentOffsetPlusCount) { StartNextSegment(); } byte[] res; if (TryCheckLengthFast(n, out res, out offset, out safeToUse)) { return res; } if ((CurrentPosition + n > totalLength)) { throw new SerializationException( String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}", CurrentPosition, n, totalLength)); } var temp = new byte[n]; var i = 0; while (i < n) { var segmentOffsetPlusCount = currentSegmentOffsetPlusCount; var bytesFromThisBuffer = Math.Min(segmentOffsetPlusCount - currentOffset, n - i); Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer); i += bytesFromThisBuffer; currentOffset += bytesFromThisBuffer; if (currentOffset >= segmentOffsetPlusCount) { if (currentSegmentIndex >= buffersCount) { throw new SerializationException( String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count)); } StartNextSegment(); } } safeToUse = true; offset = 0; return temp; } /// <summary> Read an <c>Int32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public int ReadInt() { int offset; var buff = CheckLength(sizeof(int), out offset); var val = BitConverter.ToInt32(buff, offset); Trace("--Read int {0}", val); return val; } /// <summary> Read an <c>UInt32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public uint ReadUInt() { int offset; var buff = CheckLength(sizeof(uint), out offset); var val = BitConverter.ToUInt32(buff, offset); Trace("--Read uint {0}", val); return val; } /// <summary> Read an <c>Int16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public short ReadShort() { int offset; var buff = CheckLength(sizeof(short), out offset); var val = BitConverter.ToInt16(buff, offset); Trace("--Read short {0}", val); return val; } /// <summary> Read an <c>UInt16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public ushort ReadUShort() { int offset; var buff = CheckLength(sizeof(ushort), out offset); var val = BitConverter.ToUInt16(buff, offset); Trace("--Read ushort {0}", val); return val; } /// <summary> Read an <c>Int64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public long ReadLong() { int offset; var buff = CheckLength(sizeof(long), out offset); var val = BitConverter.ToInt64(buff, offset); Trace("--Read long {0}", val); return val; } /// <summary> Read an <c>UInt64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public ulong ReadULong() { int offset; var buff = CheckLength(sizeof(ulong), out offset); var val = BitConverter.ToUInt64(buff, offset); Trace("--Read ulong {0}", val); return val; } /// <summary> Read an <c>float</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public float ReadFloat() { int offset; var buff = CheckLength(sizeof(float), out offset); var val = BitConverter.ToSingle(buff, offset); Trace("--Read float {0}", val); return val; } /// <summary> Read an <c>double</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public double ReadDouble() { int offset; var buff = CheckLength(sizeof(double), out offset); var val = BitConverter.ToDouble(buff, offset); Trace("--Read double {0}", val); return val; } /// <summary> Read an <c>decimal</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public decimal ReadDecimal() { int offset; var buff = CheckLength(4 * sizeof(int), out offset); var raw = new int[4]; Trace("--Read decimal"); var n = offset; for (var i = 0; i < 4; i++) { raw[i] = BitConverter.ToInt32(buff, n); n += sizeof(int); } return new decimal(raw); } public DateTime ReadDateTime() { var n = ReadLong(); return n == 0 ? default(DateTime) : DateTime.FromBinary(n); } /// <summary> Read an <c>string</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public string ReadString() { var n = ReadInt(); if (n == 0) { Trace("--Read empty string"); return String.Empty; } string s = null; // a length of -1 indicates that the string is null. if (-1 != n) { int offset; var buff = CheckLength(n, out offset); s = Encoding.UTF8.GetString(buff, offset, n); } Trace("--Read string '{0}'", s); return s; } /// <summary> Read the next bytes from the stream. </summary> /// <param name="count">Number of bytes to read.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public byte[] ReadBytes(int count) { if (count == 0) { return emptyByteArray; } bool safeToUse; int offset; byte[] buff; if (!TryCheckLengthFast(count, out buff, out offset, out safeToUse)) { buff = CheckLength(count, out offset, out safeToUse); } Trace("--Read byte array of length {0}", count); if (!safeToUse) { var result = new byte[count]; Array.Copy(buff, offset, result, 0, count); return result; } else { return buff; } } /// <summary> Read the next bytes from the stream. </summary> /// <param name="destination">Output array to store the returned data in.</param> /// <param name="offset">Offset into the destination array to write to.</param> /// <param name="count">Number of bytes to read.</param> public void ReadByteArray(byte[] destination, int offset, int count) { if (offset + count > destination.Length) { throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small"); } var buffOffset = 0; var buff = count == 0 ? emptyByteArray : CheckLength(count, out buffOffset); Buffer.BlockCopy(buff, buffOffset, destination, offset, count); } /// <summary> Read an <c>char</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public char ReadChar() { Trace("--Read char"); return Convert.ToChar(ReadShort()); } /// <summary> Read an <c>byte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public byte ReadByte() { int offset; var buff = CheckLength(1, out offset); Trace("--Read byte"); return buff[offset]; } /// <summary> Read an <c>sbyte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public sbyte ReadSByte() { int offset; var buff = CheckLength(1, out offset); Trace("--Read sbyte"); return unchecked((sbyte)(buff[offset])); } /// <summary> Read an <c>IPAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public IPAddress ReadIPAddress() { int offset; var buff = CheckLength(16, out offset); bool v4 = true; for (var i = 0; i < 12; i++) { if (buff[offset + i] != 0) { v4 = false; break; } } if (v4) { var v4Bytes = new byte[4]; for (var i = 0; i < 4; i++) { v4Bytes[i] = buff[offset + 12 + i]; } return new IPAddress(v4Bytes); } else { var v6Bytes = new byte[16]; for (var i = 0; i < 16; i++) { v6Bytes[i] = buff[offset + i]; } return new IPAddress(v6Bytes); } } /// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public IPEndPoint ReadIPEndPoint() { var addr = ReadIPAddress(); var port = ReadInt(); return new IPEndPoint(addr, port); } /// <summary> Read an <c>SiloAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> public SiloAddress ReadSiloAddress() { var ep = ReadIPEndPoint(); var gen = ReadInt(); return SiloAddress.New(ep, gen); } /// <summary> Read an <c>GrainId</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal GrainId ReadGrainId() { UniqueKey key = ReadUniqueKey(); return GrainId.GetGrainId(key); } /// <summary> Read an <c>ActivationId</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal ActivationId ReadActivationId() { UniqueKey key = ReadUniqueKey(); return ActivationId.GetActivationId(key); } internal UniqueKey ReadUniqueKey() { ulong n0 = ReadULong(); ulong n1 = ReadULong(); ulong typeCodeData = ReadULong(); string keyExt = ReadString(); return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt); } internal Guid ReadGuid() { byte[] bytes = ReadBytes(16); return new Guid(bytes); } public TimeSpan ReadTimeSpan() { return new TimeSpan(ReadLong()); } internal CorrelationId ReadCorrelationId() { return new CorrelationId(ReadBytes(CorrelationId.SIZE_BYTES)); } internal GrainDirectoryEntryStatus ReadMultiClusterStatus() { byte val = ReadByte(); return (GrainDirectoryEntryStatus)val; } /// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal ActivationAddress ReadActivationAddress() { var silo = ReadSiloAddress(); var grain = ReadGrainId(); var act = ReadActivationId(); if (silo.Equals(SiloAddress.Zero)) silo = null; if (act.Equals(ActivationId.Zero)) act = null; return ActivationAddress.GetAddress(silo, grain, act); } /// <summary> /// Read a block of data into the specified output <c>Array</c>. /// </summary> /// <param name="array">Array to output the data to.</param> /// <param name="n">Number of bytes to read.</param> public void ReadBlockInto(Array array, int n) { int offset; var buff = CheckLength(n, out offset); Buffer.BlockCopy(buff, offset, array, 0, n); Trace("--Read block of {0} bytes", n); } /// <summary> /// Peek at the next token in this input stream. /// </summary> /// <returns>Next token thatr will be read from the stream.</returns> internal SerializationTokenType PeekToken() { if (currentOffset == currentSegment.Count + currentSegment.Offset) StartNextSegment(); return (SerializationTokenType)currentBuffer[currentOffset]; } /// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> internal SerializationTokenType ReadToken() { int offset; var buff = CheckLength(1, out offset); Trace("--Read token {0}", (SerializationTokenType)buff[offset]); return (SerializationTokenType)buff[offset]; } internal bool TryReadSimpleType(out object result, out SerializationTokenType token) { token = ReadToken(); byte[] bytes; switch (token) { case SerializationTokenType.True: result = true; break; case SerializationTokenType.False: result = false; break; case SerializationTokenType.Null: result = null; break; case SerializationTokenType.Object: result = new object(); break; case SerializationTokenType.Int: result = ReadInt(); break; case SerializationTokenType.Uint: result = ReadUInt(); break; case SerializationTokenType.Short: result = ReadShort(); break; case SerializationTokenType.Ushort: result = ReadUShort(); break; case SerializationTokenType.Long: result = ReadLong(); break; case SerializationTokenType.Ulong: result = ReadULong(); break; case SerializationTokenType.Byte: result = ReadByte(); break; case SerializationTokenType.Sbyte: result = ReadSByte(); break; case SerializationTokenType.Float: result = ReadFloat(); break; case SerializationTokenType.Double: result = ReadDouble(); break; case SerializationTokenType.Decimal: result = ReadDecimal(); break; case SerializationTokenType.String: result = ReadString(); break; case SerializationTokenType.Character: result = ReadChar(); break; case SerializationTokenType.Guid: bytes = ReadBytes(16); result = new Guid(bytes); break; case SerializationTokenType.Date: result = DateTime.FromBinary(ReadLong()); break; case SerializationTokenType.TimeSpan: result = new TimeSpan(ReadLong()); break; case SerializationTokenType.GrainId: result = ReadGrainId(); break; case SerializationTokenType.ActivationId: result = ReadActivationId(); break; case SerializationTokenType.SiloAddress: result = ReadSiloAddress(); break; case SerializationTokenType.ActivationAddress: result = ReadActivationAddress(); break; case SerializationTokenType.IpAddress: result = ReadIPAddress(); break; case SerializationTokenType.IpEndPoint: result = ReadIPEndPoint(); break; case SerializationTokenType.CorrelationId: result = new CorrelationId(ReadBytes(CorrelationId.SIZE_BYTES)); break; default: result = null; return false; } return true; } /// <summary> Read a <c>Type</c> value from the stream. </summary> /// <param name="serializationManager">The serialization manager used to resolve type names.</param> /// <param name="expected">Expected Type, if known.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> private Type ReadFullTypeHeader(SerializationManager serializationManager, Type expected = null) { var token = ReadToken(); if (token == SerializationTokenType.ExpectedType) { return expected; } var t = CheckSpecialTypeCode(token); if (t != null) { return t; } if (token == SerializationTokenType.SpecifiedType) { #if TRACE_SERIALIZATION var tt = ReadSpecifiedTypeHeader(); Trace("--Read specified type header for type {0}", tt); return tt; #else return ReadSpecifiedTypeHeader(serializationManager); #endif } throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected"); } internal static Type CheckSpecialTypeCode(SerializationTokenType token) { switch (token) { case SerializationTokenType.Boolean: return typeof(bool); case SerializationTokenType.Int: return typeof(int); case SerializationTokenType.Short: return typeof(short); case SerializationTokenType.Long: return typeof(long); case SerializationTokenType.Sbyte: return typeof(sbyte); case SerializationTokenType.Uint: return typeof(uint); case SerializationTokenType.Ushort: return typeof(ushort); case SerializationTokenType.Ulong: return typeof(ulong); case SerializationTokenType.Byte: return typeof(byte); case SerializationTokenType.Float: return typeof(float); case SerializationTokenType.Double: return typeof(double); case SerializationTokenType.Decimal: return typeof(decimal); case SerializationTokenType.String: return typeof(string); case SerializationTokenType.Character: return typeof(char); case SerializationTokenType.Guid: return typeof(Guid); case SerializationTokenType.Date: return typeof(DateTime); case SerializationTokenType.TimeSpan: return typeof(TimeSpan); case SerializationTokenType.IpAddress: return typeof(IPAddress); case SerializationTokenType.IpEndPoint: return typeof(IPEndPoint); case SerializationTokenType.GrainId: return typeof(GrainId); case SerializationTokenType.ActivationId: return typeof(ActivationId); case SerializationTokenType.SiloAddress: return typeof(SiloAddress); case SerializationTokenType.ActivationAddress: return typeof(ActivationAddress); case SerializationTokenType.CorrelationId: return typeof(CorrelationId); #if false // Note: not yet implemented as simple types on the Writer side case SerializationTokenType.Object: return typeof(Object); case SerializationTokenType.ByteArray: return typeof(byte[]); case SerializationTokenType.ShortArray: return typeof(short[]); case SerializationTokenType.IntArray: return typeof(int[]); case SerializationTokenType.LongArray: return typeof(long[]); case SerializationTokenType.UShortArray: return typeof(ushort[]); case SerializationTokenType.UIntArray: return typeof(uint[]); case SerializationTokenType.ULongArray: return typeof(ulong[]); case SerializationTokenType.FloatArray: return typeof(float[]); case SerializationTokenType.DoubleArray: return typeof(double[]); case SerializationTokenType.CharArray: return typeof(char[]); case SerializationTokenType.BoolArray: return typeof(bool[]); #endif default: break; } return null; } /// <summary> Read a <c>Type</c> value from the stream. </summary> internal Type ReadSpecifiedTypeHeader(SerializationManager serializationManager) { // Assumes that the SpecifiedType token has already been read var token = ReadToken(); switch (token) { case SerializationTokenType.Boolean: return typeof(bool); case SerializationTokenType.Int: return typeof(int); case SerializationTokenType.Short: return typeof(short); case SerializationTokenType.Long: return typeof(long); case SerializationTokenType.Sbyte: return typeof(sbyte); case SerializationTokenType.Uint: return typeof(uint); case SerializationTokenType.Ushort: return typeof(ushort); case SerializationTokenType.Ulong: return typeof(ulong); case SerializationTokenType.Byte: return typeof(byte); case SerializationTokenType.Float: return typeof(float); case SerializationTokenType.Double: return typeof(double); case SerializationTokenType.Decimal: return typeof(decimal); case SerializationTokenType.String: return typeof(string); case SerializationTokenType.Character: return typeof(char); case SerializationTokenType.Guid: return typeof(Guid); case SerializationTokenType.Date: return typeof(DateTime); case SerializationTokenType.TimeSpan: return typeof(TimeSpan); case SerializationTokenType.IpAddress: return typeof(IPAddress); case SerializationTokenType.IpEndPoint: return typeof(IPEndPoint); case SerializationTokenType.GrainId: return typeof(GrainId); case SerializationTokenType.ActivationId: return typeof(ActivationId); case SerializationTokenType.SiloAddress: return typeof(SiloAddress); case SerializationTokenType.ActivationAddress: return typeof(ActivationAddress); case SerializationTokenType.CorrelationId: return typeof(CorrelationId); case SerializationTokenType.Request: return typeof(InvokeMethodRequest); case SerializationTokenType.Response: return typeof(Response); case SerializationTokenType.StringObjDict: return typeof(Dictionary<string, object>); case SerializationTokenType.Object: return typeof(Object); case SerializationTokenType.Tuple + 1: Trace("----Reading type info for a Tuple'1"); return typeof(Tuple<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Tuple + 2: Trace("----Reading type info for a Tuple'2"); return typeof(Tuple<,>).MakeGenericType(ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.Tuple + 3: Trace("----Reading type info for a Tuple'3"); return typeof(Tuple<,,>).MakeGenericType(ReadGenericArguments(serializationManager, 3)); case SerializationTokenType.Tuple + 4: Trace("----Reading type info for a Tuple'4"); return typeof(Tuple<,,,>).MakeGenericType(ReadGenericArguments(serializationManager, 4)); case SerializationTokenType.Tuple + 5: Trace("----Reading type info for a Tuple'5"); return typeof(Tuple<,,,,>).MakeGenericType(ReadGenericArguments(serializationManager, 5)); case SerializationTokenType.Tuple + 6: Trace("----Reading type info for a Tuple'6"); return typeof(Tuple<,,,,,>).MakeGenericType(ReadGenericArguments(serializationManager, 6)); case SerializationTokenType.Tuple + 7: Trace("----Reading type info for a Tuple'7"); return typeof(Tuple<,,,,,,>).MakeGenericType(ReadGenericArguments(serializationManager, 7)); case SerializationTokenType.Array + 1: var et1 = ReadFullTypeHeader(serializationManager); return et1.MakeArrayType(); case SerializationTokenType.Array + 2: var et2 = ReadFullTypeHeader(serializationManager); return et2.MakeArrayType(2); case SerializationTokenType.Array + 3: var et3 = ReadFullTypeHeader(serializationManager); return et3.MakeArrayType(3); case SerializationTokenType.Array + 4: var et4 = ReadFullTypeHeader(serializationManager); return et4.MakeArrayType(4); case SerializationTokenType.Array + 5: var et5 = ReadFullTypeHeader(serializationManager); return et5.MakeArrayType(5); case SerializationTokenType.Array + 6: var et6 = ReadFullTypeHeader(serializationManager); return et6.MakeArrayType(6); case SerializationTokenType.Array + 7: var et7 = ReadFullTypeHeader(serializationManager); return et7.MakeArrayType(7); case SerializationTokenType.Array + 8: var et8 = ReadFullTypeHeader(serializationManager); return et8.MakeArrayType(8); case SerializationTokenType.List: return typeof(List<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Dictionary: return typeof(Dictionary<,>).MakeGenericType(ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.KeyValuePair: return typeof(KeyValuePair<,>).MakeGenericType(ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.Set: return typeof(HashSet<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.SortedList: return typeof(SortedList<,>).MakeGenericType(ReadGenericArguments(serializationManager, 2)); case SerializationTokenType.SortedSet: return typeof(SortedSet<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Stack: return typeof(Stack<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Queue: return typeof(Queue<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.LinkedList: return typeof(LinkedList<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.Nullable: return typeof(Nullable<>).MakeGenericType(ReadGenericArguments(serializationManager, 1)); case SerializationTokenType.ByteArray: return typeof(byte[]); case SerializationTokenType.ShortArray: return typeof(short[]); case SerializationTokenType.IntArray: return typeof(int[]); case SerializationTokenType.LongArray: return typeof(long[]); case SerializationTokenType.UShortArray: return typeof(ushort[]); case SerializationTokenType.UIntArray: return typeof(uint[]); case SerializationTokenType.ULongArray: return typeof(ulong[]); case SerializationTokenType.FloatArray: return typeof(float[]); case SerializationTokenType.DoubleArray: return typeof(double[]); case SerializationTokenType.CharArray: return typeof(char[]); case SerializationTokenType.BoolArray: return typeof(bool[]); case SerializationTokenType.SByteArray: return typeof(sbyte[]); case SerializationTokenType.NamedType: var typeName = ReadString(); try { return serializationManager.ResolveTypeName(typeName); } catch (TypeAccessException ex) { throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message); } default: break; } throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference"); } private Type[] ReadGenericArguments(SerializationManager serializationManager, int n) { Trace("About to read {0} generic arguments", n); var args = new Type[n]; for (var i = 0; i < n; i++) { args[i] = ReadFullTypeHeader(serializationManager); } Trace("Finished reading {0} generic arguments", n); return args; } private StreamWriter trace; [Conditional("TRACE_SERIALIZATION")] private void Trace(string format, params object[] args) { if (trace == null) { var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks); Console.WriteLine("Opening trace file at '{0}'", path); trace = File.CreateText(path); } trace.Write(format, args); trace.WriteLine(" at offset {0}", CurrentPosition); trace.Flush(); } } }
// <copyright file="MetricReaderExt.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry 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. // </copyright> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.Metrics; using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { /// <summary> /// MetricReader base class. /// </summary> public abstract partial class MetricReader { private readonly HashSet<string> metricStreamNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary<InstrumentIdentity, Metric> instrumentIdentityToMetric = new ConcurrentDictionary<InstrumentIdentity, Metric>(); private readonly object instrumentCreationLock = new object(); private int maxMetricStreams; private int maxMetricPointsPerMetricStream; private Metric[] metrics; private Metric[] metricsCurrentBatch; private int metricIndex = -1; internal Metric AddMetricWithNoViews(Instrument instrument) { var meterName = instrument.Meter.Name; var meterVersion = instrument.Meter.Version; var metricName = instrument.Name; var metricStreamName = $"{meterName}.{meterVersion}.{metricName}"; var instrumentIdentity = new InstrumentIdentity(instrument.Meter, metricName, instrument.Unit, instrument.Description, instrument.GetType()); lock (this.instrumentCreationLock) { if (this.instrumentIdentityToMetric.TryGetValue(instrumentIdentity, out var existingMetric)) { return existingMetric; } if (this.metricStreamNames.Contains(metricStreamName)) { OpenTelemetrySdkEventSource.Log.DuplicateMetricInstrument( metricName, meterName, "Metric instrument has the same name as an existing one but differs by description, unit, or instrument type. Measurements from this instrument will still be exported but may result in conflicts.", "Either change the name of the instrument or use MeterProviderBuilder.AddView to resolve the conflict."); } var index = ++this.metricIndex; if (index >= this.maxMetricStreams) { OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(metricName, instrument.Meter.Name, "Maximum allowed Metric streams for the provider exceeded.", "Use MeterProviderBuilder.AddView to drop unused instruments. Or use MeterProviderBuilder.SetMaxMetricStreams to configure MeterProvider to allow higher limit."); return null; } else { var metric = new Metric(instrumentIdentity, this.Temporality, this.maxMetricPointsPerMetricStream); this.instrumentIdentityToMetric[instrumentIdentity] = metric; this.metrics[index] = metric; this.metricStreamNames.Add(metricStreamName); return metric; } } } internal void RecordSingleStreamLongMeasurement(Metric metric, long value, ReadOnlySpan<KeyValuePair<string, object>> tags) { metric.UpdateLong(value, tags); } internal void RecordSingleStreamDoubleMeasurement(Metric metric, double value, ReadOnlySpan<KeyValuePair<string, object>> tags) { metric.UpdateDouble(value, tags); } internal List<Metric> AddMetricsListWithViews(Instrument instrument, List<MetricStreamConfiguration> metricStreamConfigs) { var maxCountMetricsToBeCreated = metricStreamConfigs.Count; // Create list with initial capacity as the max metric count. // Due to duplicate/max limit, we may not end up using them // all, and that memory is wasted until Meter disposed. // TODO: Revisit to see if we need to do metrics.TrimExcess() var metrics = new List<Metric>(maxCountMetricsToBeCreated); lock (this.instrumentCreationLock) { for (int i = 0; i < maxCountMetricsToBeCreated; i++) { var metricStreamConfig = metricStreamConfigs[i]; var meterName = instrument.Meter.Name; var meterVersion = instrument.Meter.Version; var metricName = metricStreamConfig?.Name ?? instrument.Name; var metricStreamName = $"{meterName}.{meterVersion}.{metricName}"; var metricDescription = metricStreamConfig?.Description ?? instrument.Description; var instrumentIdentity = new InstrumentIdentity(instrument.Meter, metricName, instrument.Unit, metricDescription, instrument.GetType()); if (!MeterProviderBuilderSdk.IsValidInstrumentName(metricName)) { OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored( metricName, instrument.Meter.Name, "Metric name is invalid.", "The name must comply with the OpenTelemetry specification."); continue; } if (this.instrumentIdentityToMetric.TryGetValue(instrumentIdentity, out var existingMetric)) { metrics.Add(existingMetric); continue; } if (this.metricStreamNames.Contains(metricStreamName)) { OpenTelemetrySdkEventSource.Log.DuplicateMetricInstrument( metricName, meterName, "Metric instrument has the same name as an existing one but differs by description, unit, or instrument type. Measurements from this instrument will still be exported but may result in conflicts.", "Either change the name of the instrument or use MeterProviderBuilder.AddView to resolve the conflict."); } if (metricStreamConfig?.Aggregation == Aggregation.Drop) { OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(metricName, instrument.Meter.Name, "View configuration asks to drop this instrument.", "Modify view configuration to allow this instrument, if desired."); continue; } var index = ++this.metricIndex; if (index >= this.maxMetricStreams) { OpenTelemetrySdkEventSource.Log.MetricInstrumentIgnored(metricName, instrument.Meter.Name, "Maximum allowed Metric streams for the provider exceeded.", "Use MeterProviderBuilder.AddView to drop unused instruments. Or use MeterProviderBuilder.SetMaxMetricStreams to configure MeterProvider to allow higher limit."); } else { Metric metric; string[] tagKeysInteresting = metricStreamConfig?.TagKeys; double[] histogramBucketBounds = (metricStreamConfig is ExplicitBucketHistogramConfiguration histogramConfig && histogramConfig.Boundaries != null) ? histogramConfig.Boundaries : null; metric = new Metric(instrumentIdentity, this.Temporality, this.maxMetricPointsPerMetricStream, histogramBucketBounds, tagKeysInteresting); this.instrumentIdentityToMetric[instrumentIdentity] = metric; this.metrics[index] = metric; metrics.Add(metric); this.metricStreamNames.Add(metricStreamName); } } return metrics; } } internal void RecordLongMeasurement(List<Metric> metrics, long value, ReadOnlySpan<KeyValuePair<string, object>> tags) { if (metrics.Count == 1) { // special casing the common path // as this is faster than the // foreach, when count is 1. metrics[0].UpdateLong(value, tags); } else { foreach (var metric in metrics) { metric.UpdateLong(value, tags); } } } internal void RecordDoubleMeasurement(List<Metric> metrics, double value, ReadOnlySpan<KeyValuePair<string, object>> tags) { if (metrics.Count == 1) { // special casing the common path // as this is faster than the // foreach, when count is 1. metrics[0].UpdateDouble(value, tags); } else { foreach (var metric in metrics) { metric.UpdateDouble(value, tags); } } } internal void CompleteSingleStreamMeasurement(Metric metric) { metric.InstrumentDisposed = true; } internal void CompleteMeasurement(List<Metric> metrics) { foreach (var metric in metrics) { metric.InstrumentDisposed = true; } } internal void SetMaxMetricStreams(int maxMetricStreams) { this.maxMetricStreams = maxMetricStreams; this.metrics = new Metric[maxMetricStreams]; this.metricsCurrentBatch = new Metric[maxMetricStreams]; } internal void SetMaxMetricPointsPerMetricStream(int maxMetricPointsPerMetricStream) { this.maxMetricPointsPerMetricStream = maxMetricPointsPerMetricStream; } private Batch<Metric> GetMetricsBatch() { try { var indexSnapshot = Math.Min(this.metricIndex, this.maxMetricStreams - 1); var target = indexSnapshot + 1; int metricCountCurrentBatch = 0; for (int i = 0; i < target; i++) { var metric = this.metrics[i]; int metricPointSize = 0; if (metric != null) { if (metric.InstrumentDisposed) { metricPointSize = metric.Snapshot(); this.instrumentIdentityToMetric.TryRemove(metric.InstrumentIdentity, out var _); this.metrics[i] = null; } else { metricPointSize = metric.Snapshot(); } if (metricPointSize > 0) { this.metricsCurrentBatch[metricCountCurrentBatch++] = metric; } } } return (metricCountCurrentBatch > 0) ? new Batch<Metric>(this.metricsCurrentBatch, metricCountCurrentBatch) : default; } catch (Exception ex) { OpenTelemetrySdkEventSource.Log.MetricReaderException(nameof(this.GetMetricsBatch), ex); return default; } } } }
/* Copyright (c) 2012, Ooyala, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Threading; using System.Windows.Forms; using Microsoft.SharePoint.Administration; using System.Web.Configuration; using Microsoft.SharePoint; using System.IO; using SharePointInstaller.Resources; using System.Security; using System.Reflection; using System.Xml; namespace SharePointInstaller { public partial class InstallProcessControl : InstallerControl { private static readonly MessageCollector log = new MessageCollector(LogManager.GetLogger()); private static readonly TimeSpan JobTimeout = TimeSpan.FromMinutes(15); private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); private CommandList executeCommands; private CommandList rollbackCommands; private int nextCommand; private bool completed; private bool requestCancel; private int errors; private int rollbackErrors; public InstallProcessControl() { InitializeComponent(); errorPictureBox.Visible = false; errorDetailsTextBox.Visible = false; this.Load += new EventHandler(InstallProcessControl_Load); } #region Event Handlers private void InstallProcessControl_Load(object sender, EventArgs e) { switch (Form.Operation) { case InstallOperation.Install: Form.SetTitle(CommonUIStrings.installTitle); Form.SetSubTitle(InstallConfiguration.FormatString(CommonUIStrings.installSubTitle)); break; case InstallOperation.Upgrade: Form.SetTitle(CommonUIStrings.upgradeTitle); Form.SetSubTitle(InstallConfiguration.FormatString(CommonUIStrings.upgradeSubTitle)); break; case InstallOperation.Repair: Form.SetTitle(CommonUIStrings.repairTitle); Form.SetSubTitle(InstallConfiguration.FormatString(CommonUIStrings.repairSubTitle)); break; case InstallOperation.Uninstall: Form.SetTitle(CommonUIStrings.uninstallTitle); Form.SetSubTitle(InstallConfiguration.FormatString(CommonUIStrings.uninstallSubTitle)); removeTableEntries(); break; } Form.PrevButton.Enabled = false; Form.NextButton.Enabled = false; } private void removeTableEntries() { try { //Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApp.Name); string ConnectionString = GetConnetionString(); ; string queryString = "DELETE FROM tblUser"; SqlConnection con = new SqlConnection(ConnectionString); SqlCommand cmd = new SqlCommand(queryString, con); if (con != null) { con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } catch (SqlException ex) { MessageBox.Show(ex.Message); } } private void TimerEventInstall(Object myObject, EventArgs myEventArgs) { timer.Stop(); if (requestCancel) { descriptionLabel.Text = Resources.CommonUIStrings.descriptionLabelTextOperationCanceled; InitiateRollback(); } else if (nextCommand < executeCommands.Count) { try { Command command = executeCommands[nextCommand]; if (command.Execute()) { nextCommand++; progressBar.PerformStep(); if (nextCommand < executeCommands.Count) { descriptionLabel.Text = executeCommands[nextCommand].Description; } } timer.Start(); } catch (Exception ex) { log.Error(CommonUIStrings.logError); log.Error(ex.Message, ex); errors++; errorPictureBox.Visible = true; errorDetailsTextBox.Visible = true; errorDetailsTextBox.Text = ex.Message; descriptionLabel.Text = Resources.CommonUIStrings.descriptionLabelTextErrorsDetected; InitiateRollback(); } } else { descriptionLabel.Text = Resources.CommonUIStrings.descriptionLabelTextSuccess; HandleCompletion(); } } private void TimerEventRollback(Object myObject, EventArgs myEventArgs) { timer.Stop(); if (nextCommand < rollbackCommands.Count) { try { Command command = rollbackCommands[nextCommand]; if (command.Rollback()) { nextCommand++; progressBar.PerformStep(); } } catch (Exception ex) { log.Error(CommonUIStrings.logError); log.Error(ex.Message, ex); rollbackErrors++; nextCommand++; progressBar.PerformStep(); } timer.Start(); } else { if (rollbackErrors == 0) { descriptionLabel.Text = Resources.CommonUIStrings.descriptionLabelTextRollbackSuccess; } else { descriptionLabel.Text = string.Format(Resources.CommonUIStrings.descriptionLabelTextRollbackError, rollbackErrors); } HandleCompletion(); } } #endregion #region Protected Methods protected internal override void RequestCancel() { if (completed) { base.RequestCancel(); } else { requestCancel = true; Form.AbortButton.Enabled = false; } } protected internal override void Open(InstallOptions options) { executeCommands = new CommandList(); rollbackCommands = new CommandList(); nextCommand = 0; SPFeatureScope featureScope = InstallConfiguration.FeatureScope; DeactivateSiteCollectionFeatureCommand deactivateSiteCollectionFeatureCommand = null; switch (Form.Operation) { case InstallOperation.Install: executeCommands.Add(new ConfigureConnectionStringCommand(this, options.WebApplicationTargets)); executeCommands.Add(new AddSolutionCommand(this)); executeCommands.Add(new CreateDeploymentJobCommand(this, options.WebApplicationTargets)); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionDeployment)); if (featureScope == SPFeatureScope.Farm) { executeCommands.Add(new ActivateFarmFeatureCommand(this)); } else if (featureScope == SPFeatureScope.Site) { executeCommands.Add(new ActivateSiteCollectionFeatureCommand(this, options.SiteCollectionTargets)); } executeCommands.Add(new RegisterVersionNumberCommand(this)); for (int i = executeCommands.Count - 1; i <= 0; i--) { rollbackCommands.Add(executeCommands[i]); } break; case InstallOperation.Upgrade: if (featureScope == SPFeatureScope.Farm) { executeCommands.Add(new DeactivateFarmFeatureCommand(this)); } else if (featureScope == SPFeatureScope.Site) { deactivateSiteCollectionFeatureCommand = new DeactivateSiteCollectionFeatureCommand(this); executeCommands.Add(deactivateSiteCollectionFeatureCommand); } if (!IsSolutionRenamed()) { executeCommands.Add(new CreateUpgradeJobCommand(this)); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionUpgrade)); } else { executeCommands.Add(new CreateRetractionJobCommand(this)); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionRetraction)); executeCommands.Add(new RemoveSolutionCommand(this)); executeCommands.Add(new AddSolutionCommand(this)); executeCommands.Add(new CreateDeploymentJobCommand(this, GetDeployedApplications())); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionDeployment)); } if (featureScope == SPFeatureScope.Farm) { executeCommands.Add(new ActivateFarmFeatureCommand(this)); } if (featureScope == SPFeatureScope.Site) { executeCommands.Add(new ActivateSiteCollectionFeatureCommand(this, deactivateSiteCollectionFeatureCommand.DeactivatedSiteCollections)); } executeCommands.Add(new RegisterVersionNumberCommand(this)); break; case InstallOperation.Repair: if (featureScope == SPFeatureScope.Farm) { executeCommands.Add(new DeactivateFarmFeatureCommand(this)); } if (featureScope == SPFeatureScope.Site) { deactivateSiteCollectionFeatureCommand = new DeactivateSiteCollectionFeatureCommand(this); executeCommands.Add(deactivateSiteCollectionFeatureCommand); } executeCommands.Add(new CreateRetractionJobCommand(this)); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionRetraction)); executeCommands.Add(new RemoveSolutionCommand(this)); executeCommands.Add(new AddSolutionCommand(this)); executeCommands.Add(new CreateDeploymentJobCommand(this, GetDeployedApplications())); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionDeployment)); if (featureScope == SPFeatureScope.Farm) { executeCommands.Add(new ActivateFarmFeatureCommand(this)); } if (featureScope == SPFeatureScope.Site) { executeCommands.Add(new ActivateSiteCollectionFeatureCommand(this, deactivateSiteCollectionFeatureCommand.DeactivatedSiteCollections)); } executeCommands.Add(new RegisterVersionNumberCommand(this)); break; case InstallOperation.Uninstall: if (featureScope == SPFeatureScope.Farm) { executeCommands.Add(new DeactivateFarmFeatureCommand(this)); } if (featureScope == SPFeatureScope.Site) { executeCommands.Add(new DeactivateSiteCollectionFeatureCommand(this)); } executeCommands.Add(new CreateRetractionJobCommand(this)); executeCommands.Add(new WaitForJobCompletionCommand(this, CommonUIStrings.waitForSolutionRetraction)); executeCommands.Add(new RemoveSolutionCommand(this)); executeCommands.Add(new UnregisterVersionNumberCommand(this)); break; } progressBar.Maximum = executeCommands.Count; descriptionLabel.Text = executeCommands[0].Description; timer.Interval = 1000; timer.Tick += new EventHandler(TimerEventInstall); timer.Start(); } #endregion #region Private Methods private void HandleCompletion() { completed = true; Form.NextButton.Enabled = true; Form.AbortButton.Text = CommonUIStrings.abortButtonText; Form.AbortButton.Enabled = true; CompletionControl nextControl = new CompletionControl(); foreach (string message in log.Messages) { nextControl.Details += message + "\r\n"; } switch (Form.Operation) { case InstallOperation.Install: nextControl.Title = errors == 0 ? CommonUIStrings.installSuccess : CommonUIStrings.installError; break; case InstallOperation.Upgrade: nextControl.Title = errors == 0 ? CommonUIStrings.upgradeSuccess : CommonUIStrings.upgradeError; break; case InstallOperation.Repair: nextControl.Title = errors == 0 ? CommonUIStrings.repairSuccess : CommonUIStrings.repairError; break; case InstallOperation.Uninstall: nextControl.Title = errors == 0 ? CommonUIStrings.uninstallSuccess : CommonUIStrings.uninstallError; break; } Form.ContentControls.Add(nextControl); } private void InitiateRollback() { Form.AbortButton.Enabled = false; progressBar.Maximum = rollbackCommands.Count; progressBar.Value = rollbackCommands.Count; nextCommand = 0; rollbackErrors = 0; progressBar.Step = -1; // // Create and start new timer. // timer = new System.Windows.Forms.Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(TimerEventRollback); timer.Start(); } private bool IsSolutionRenamed() { SPFarm farm = SPFarm.Local; SPSolution solution = farm.Solutions[InstallConfiguration.SolutionId]; if (solution == null) return false; FileInfo solutionFileInfo = new FileInfo(InstallConfiguration.SolutionFile); return !solution.Name.Equals(solutionFileInfo.Name, StringComparison.OrdinalIgnoreCase); } private Collection<SPWebApplication> GetDeployedApplications() { SPFarm farm = SPFarm.Local; SPSolution solution = farm.Solutions[InstallConfiguration.SolutionId]; if (solution.ContainsWebApplicationResource) { return solution.DeployedWebApplications; } return null; } #endregion #region Command Classes /// <summary> /// The base class of all installation commands. /// </summary> private abstract class Command { private readonly InstallProcessControl parent; protected Command(InstallProcessControl parent) { this.parent = parent; } internal InstallProcessControl Parent { get { return parent; } } internal abstract string Description { get; } protected internal virtual bool Execute() { return true; } protected internal virtual bool Rollback() { return true; } } private class CommandList : List<Command> { } /// <summary> /// The base class of all SharePoint solution related commands. /// </summary> private abstract class SolutionCommand : Command { protected SolutionCommand(InstallProcessControl parent) : base(parent) { } protected void RemoveSolution() { try { SPFarm farm = SPFarm.Local; SPSolution solution = farm.Solutions[InstallConfiguration.SolutionId]; if (solution != null) { if (!solution.Deployed) { solution.Delete(); } } } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } } /// <summary> /// Command for adding the SharePoint solution. /// </summary> private class AddSolutionCommand : SolutionCommand { internal AddSolutionCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.addSolutionCommand; } } protected internal override bool Execute() { string filename = InstallConfiguration.SolutionFile; if (String.IsNullOrEmpty(filename)) { throw new InstallException(CommonUIStrings.installExceptionConfigurationNoWsp); } try { SPFarm farm = SPFarm.Local; SPSolution solution = farm.Solutions.Add(filename); return true; } catch (SecurityException ex) { string message = CommonUIStrings.addSolutionAccessError; if (Environment.OSVersion.Version >= new Version("6.0")) message += " " + CommonUIStrings.addSolutionAccessErrorWinServer2008Solution; else message += " " + CommonUIStrings.addSolutionAccessErrorWinServer2003Solution; throw new InstallException(message, ex); } catch (IOException ex) { throw new InstallException(ex.Message, ex); } catch (ArgumentException ex) { throw new InstallException(ex.Message, ex); } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } protected internal override bool Rollback() { RemoveSolution(); return true; } } /// <summary> /// Command for removing the SharePoint solution. /// </summary> private class RemoveSolutionCommand : SolutionCommand { internal RemoveSolutionCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.removeSolutionCommand; } } protected internal override bool Execute() { RemoveSolution(); return true; } } private abstract class JobCommand : Command { protected JobCommand(InstallProcessControl parent) : base(parent) { } protected static void RemoveExistingJob(SPSolution solution) { if (solution.JobStatus == SPRunningJobStatus.Initialized) { throw new InstallException(CommonUIStrings.installExceptionDuplicateJob); } SPJobDefinition jobDefinition = GetSolutionJob(solution); if (jobDefinition != null) { jobDefinition.Delete(); Thread.Sleep(500); } } private static SPJobDefinition GetSolutionJob(SPSolution solution) { SPFarm localFarm = SPFarm.Local; SPTimerService service = localFarm.TimerService; foreach (SPJobDefinition definition in service.JobDefinitions) { if (definition.Title != null && definition.Title.Contains(solution.Name)) { return definition; } } return null; } protected static DateTime GetImmediateJobTime() { return DateTime.Now - TimeSpan.FromDays(1); } } /// <summary> /// Command for creating a deployment job. /// </summary> private class CreateDeploymentJobCommand : JobCommand { private readonly Collection<SPWebApplication> applications; internal CreateDeploymentJobCommand(InstallProcessControl parent, IList<SPWebApplication> applications) : base(parent) { if (applications != null) { this.applications = new Collection<SPWebApplication>(); foreach (SPWebApplication application in applications) { this.applications.Add(application); } } else { this.applications = null; } } internal override string Description { get { return CommonUIStrings.createDeploymentJobCommand; } } protected internal override bool Execute() { try { SPSolution installedSolution = SPFarm.Local.Solutions[InstallConfiguration.SolutionId]; // // Remove existing job, if any. // if (installedSolution.JobExists) { RemoveExistingJob(installedSolution); } log.Info("***** SOLUTION DEPLOYMENT *****"); if (installedSolution.ContainsWebApplicationResource && applications != null && applications.Count > 0) { installedSolution.Deploy(GetImmediateJobTime(), true, applications, true); } else { installedSolution.Deploy(GetImmediateJobTime(), true, true); } return true; } catch (SPException ex) { throw new InstallException(ex.Message, ex); } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } protected internal override bool Rollback() { SPSolution installedSolution = SPFarm.Local.Solutions[InstallConfiguration.SolutionId]; if (installedSolution != null) { // // Remove existing job, if any. // if (installedSolution.JobExists) { RemoveExistingJob(installedSolution); } log.Info("***** SOLUTION RETRACTION *****"); if (installedSolution.ContainsWebApplicationResource) { installedSolution.Retract(GetImmediateJobTime(), applications); } else { installedSolution.Retract(GetImmediateJobTime()); } } return true; } } /// <summary> /// Command for creating an upgrade job. /// </summary> private class CreateUpgradeJobCommand : JobCommand { internal CreateUpgradeJobCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.createUpgradeJobCommand; } } protected internal override bool Execute() { try { string filename = InstallConfiguration.SolutionFile; if (String.IsNullOrEmpty(filename)) { throw new InstallException(CommonUIStrings.installExceptionConfigurationNoWsp); } SPSolution installedSolution = SPFarm.Local.Solutions[InstallConfiguration.SolutionId]; // // Remove existing job, if any. // if (installedSolution.JobExists) { RemoveExistingJob(installedSolution); } log.Info(CommonUIStrings.logUpgrade); installedSolution.Upgrade(filename, GetImmediateJobTime()); return true; } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } } /// <summary> /// Command for creating a retraction job. /// </summary> private class CreateRetractionJobCommand : JobCommand { internal CreateRetractionJobCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.createRetractionJobCommand; } } protected internal override bool Execute() { try { SPSolution installedSolution = SPFarm.Local.Solutions[InstallConfiguration.SolutionId]; // // Remove existing job, if any. // if (installedSolution.JobExists) { RemoveExistingJob(installedSolution); } if (installedSolution.Deployed) { log.Info(CommonUIStrings.logRetract); if (installedSolution.ContainsWebApplicationResource) { Collection<SPWebApplication> applications = installedSolution.DeployedWebApplications; installedSolution.Retract(GetImmediateJobTime(), applications); } else { installedSolution.Retract(GetImmediateJobTime()); } } return true; } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } } private class WaitForJobCompletionCommand : Command { private readonly string description; private DateTime startTime; private bool first = true; internal WaitForJobCompletionCommand(InstallProcessControl parent, string description) : base(parent) { this.description = description; } internal override string Description { get { return description; } } protected internal override bool Execute() { try { SPSolution installedSolution = SPFarm.Local.Solutions[InstallConfiguration.SolutionId]; if (first) { if (!installedSolution.JobExists) return true; startTime = DateTime.Now; first = false; } // // Wait for job to end // if (installedSolution.JobExists) { if (DateTime.Now > startTime.Add(JobTimeout)) { throw new InstallException(CommonUIStrings.installExceptionTimeout); } return false; } else { log.Info(installedSolution.LastOperationDetails); SPSolutionOperationResult result = installedSolution.LastOperationResult; if (result != SPSolutionOperationResult.DeploymentSucceeded && result != SPSolutionOperationResult.RetractionSucceeded) { throw new InstallException(installedSolution.LastOperationDetails); } return true; } } catch (Exception ex) { throw new InstallException(ex.Message, ex); } } protected internal override bool Rollback() { SPSolution installedSolution = SPFarm.Local.Solutions[InstallConfiguration.SolutionId]; // // Wait for job to end // if (installedSolution != null) { if (installedSolution.JobExists) { if (DateTime.Now > startTime.Add(JobTimeout)) { throw new InstallException(CommonUIStrings.installExceptionTimeout); } return false; } else { log.Info(installedSolution.LastOperationDetails); } } return true; } } private abstract class FeatureCommand : Command { protected FeatureCommand(InstallProcessControl parent) : base(parent) { } protected static void DeactivateFeature(List<Guid?> featureIds) { try { if (featureIds != null && featureIds.Count > 0) { foreach (Guid? featureId in featureIds) { if (featureId != null) { SPFeature feature = SPWebService.AdministrationService.Features[featureId.Value]; if (feature != null) { SPWebService.AdministrationService.Features.Remove(featureId.Value); } } } } } catch (ArgumentException ex) // Missing assembly in GAC { log.Warn(ex.Message, ex); } catch (InvalidOperationException ex) // Missing receiver class { log.Warn(ex.Message, ex); } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } } private class ActivateFarmFeatureCommand : FeatureCommand { internal ActivateFarmFeatureCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.activateFarmFeatureCommand; } } protected internal override bool Execute() { try { List<Guid?> featureIds = InstallConfiguration.FeatureId; if (featureIds != null && featureIds.Count > 0) { foreach (Guid? featureId in featureIds) { if (featureId != null) { SPFeature feature = SPWebService.AdministrationService.Features.Add(featureId.Value, true); } } } return true; } catch (Exception ex) { throw new InstallException(ex.Message, ex); } } protected internal override bool Rollback() { DeactivateFeature(InstallConfiguration.FeatureId); return true; } } private class DeactivateFarmFeatureCommand : FeatureCommand { internal DeactivateFarmFeatureCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.deactivateFarmFeatureCommand; } } protected internal override bool Execute() { try { List<Guid?> featureIds = InstallConfiguration.FeatureId; if (featureIds != null && featureIds.Count > 0) { foreach (Guid? featureId in featureIds) { if (featureId != null && SPWebService.AdministrationService.Features[featureId.Value] != null) { SPWebService.AdministrationService.Features.Remove(featureId.Value); } } } return true; } catch (Exception ex) { log.Error(ex.Message, ex); } return true; } } private abstract class SiteCollectionFeatureCommand : Command { internal SiteCollectionFeatureCommand(InstallProcessControl parent) : base(parent) { } protected static void DeactivateFeature(IList<SPSite> siteCollections, List<Guid?> featureIds) { try { if (siteCollections != null && featureIds != null && featureIds.Count > 0) { log.Info(CommonUIStrings.logFeatureDeactivate); foreach (SPSite siteCollection in siteCollections) { foreach (Guid? featureId in featureIds) { if (featureId == null) continue; SPFeature feature = siteCollection.Features[featureId.Value]; if (feature == null) continue; siteCollection.Features.Remove(featureId.Value); log.Info(siteCollection.Url + " : " + featureId.Value.ToString()); } } } } catch (ArgumentException ex) { log.Warn(ex.Message, ex); } catch (InvalidOperationException ex) { log.Warn(ex.Message, ex); } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } } private class ActivateSiteCollectionFeatureCommand : SiteCollectionFeatureCommand { private readonly IList<SPSite> siteCollections; internal ActivateSiteCollectionFeatureCommand(InstallProcessControl parent, IList<SPSite> siteCollections) : base(parent) { this.siteCollections = siteCollections; } internal override string Description { get { return String.Format(CommonUIStrings.activateSiteCollectionFeatureCommand, siteCollections.Count, siteCollections.Count == 1 ? String.Empty : "s"); } } protected internal override bool Execute() { try { List<Guid?> featureIds = InstallConfiguration.FeatureId; if (siteCollections != null && featureIds != null && featureIds.Count > 0) { log.Info(CommonUIStrings.logFeatureActivate); foreach (SPSite siteCollection in siteCollections) { foreach (Guid? featureId in featureIds) { if (featureId == null) continue; SPFeature feature = siteCollection.Features.Add(featureId.Value, true); log.Info(siteCollection.Url + " : " + featureId.Value.ToString()); } } } return true; } catch (Exception ex) { throw new InstallException(ex.Message, ex); } } protected internal override bool Rollback() { DeactivateFeature(siteCollections, InstallConfiguration.FeatureId); return true; } } private class DeactivateSiteCollectionFeatureCommand : SiteCollectionFeatureCommand { private List<SPSite> deactivatedSiteCollections; internal DeactivateSiteCollectionFeatureCommand(InstallProcessControl parent) : base(parent) { deactivatedSiteCollections = new List<SPSite>(); } public List<SPSite> DeactivatedSiteCollections { get { return deactivatedSiteCollections; } } internal override string Description { get { return CommonUIStrings.deactivateSiteCollectionFeatureCommand; } } protected internal override bool Execute() { try { List<Guid?> featureIds = InstallConfiguration.FeatureId; SPFarm farm = SPFarm.Local; SPSolution solution = farm.Solutions[InstallConfiguration.SolutionId]; if (solution != null && solution.Deployed && featureIds != null && featureIds.Count > 0) { log.Info(CommonUIStrings.logFeatureDeactivate); foreach (SPWebApplication webApp in SPWebService.AdministrationService.WebApplications) { DeactivateFeatures(webApp); } foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications) { DeactivateFeatures(webApp); } } } catch (Exception ex) { log.Error(ex.Message, ex); } return true; } private void DeactivateFeatures(SPWebApplication webApp) { List<Guid?> featureIds = InstallConfiguration.FeatureId; foreach (SPSite siteCollection in webApp.Sites) { foreach (Guid? featureId in featureIds) { if (featureId == null) continue; if (siteCollection.Features[featureId.Value] == null) continue; log.Info(siteCollection.Url + " : " + featureId.Value.ToString()); siteCollection.Features.Remove(featureId.Value); } siteCollection.Dispose(); } } } /// <summary> /// Command that registers the version number of a solution. /// </summary> private class RegisterVersionNumberCommand : Command { private Version oldVersion; internal RegisterVersionNumberCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.registerVersionNumberCommand; } } protected internal override bool Execute() { oldVersion = InstallConfiguration.InstalledVersion; InstallConfiguration.InstalledVersion = InstallConfiguration.SolutionVersion; return true; } protected internal override bool Rollback() { InstallConfiguration.InstalledVersion = oldVersion; return true; } } /// <summary> /// Command that unregisters the version number of a solution. /// </summary> private class UnregisterVersionNumberCommand : Command { internal UnregisterVersionNumberCommand(InstallProcessControl parent) : base(parent) { } internal override string Description { get { return CommonUIStrings.unregisterVersionNumberCommand; } } protected internal override bool Execute() { InstallConfiguration.InstalledVersion = null; return true; } } /// <summary> /// Command that configuring Connection String in Web Application Config File. /// </summary> private class ConfigureConnectionStringCommand : Command { private Collection<SPWebApplication> applications; internal ConfigureConnectionStringCommand(InstallProcessControl parent, IList<SPWebApplication> applications) : base(parent) { if (applications != null) { this.applications = new Collection<SPWebApplication>(); foreach (SPWebApplication application in applications) { this.applications.Add(application); } } else { this.applications = null; } } internal override string Description { get { return CommonUIStrings.configureConnectionStringCommand; } } protected internal override bool Execute() { try { foreach (SPWebApplication application in applications) { if (!application.IsAdministrationWebApplication) { WebConfigModifier.EnsureChildNode(application); } } return true; } catch (SPException ex) { throw new InstallException(ex.Message, ex); } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } } protected string GetConnetionString() { try { string conString = string.Empty; foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications) { if (!webApp.IsAdministrationWebApplication) { conString=WebConfigModifier.getConnectionString(webApp); } } return conString; } catch (SPException ex) { throw new InstallException(ex.Message, ex); } catch (SqlException ex) { throw new InstallException(ex.Message, ex); } } #endregion #region ILog Wrapper private class MessageList : List<string> { } private class MessageCollector : ILog { private readonly ILog wrappee; private readonly MessageList messages = new MessageList(); internal MessageCollector(ILog wrappee) { this.wrappee = wrappee; } public MessageList Messages { get { return messages; } } public void Info(object message) { messages.Add(message.ToString()); wrappee.Info(message); } public void Info(object message, Exception t) { messages.Add(message.ToString()); messages.Add(t.ToString()); wrappee.Info(message, t); } public void Warn(object message) { wrappee.Warn(message); } public void Warn(object message, Exception t) { wrappee.Warn(message, t); } public void Error(object message) { messages.Add(message.ToString()); wrappee.Error(message); } public void Error(object message, Exception t) { messages.Add(message.ToString()); messages.Add(t.ToString()); wrappee.Error(message, t); } public void Fatal(object message) { wrappee.Fatal(message); } public void Fatal(object message, Exception t) { wrappee.Fatal(message, t); } } #endregion } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using NSubstitute; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoriesClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null)); } } public class TheCreateMethodForUser { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null)); } [Fact] public void UsesTheUserReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Create(new NewRepository("aName")); connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>()); } [Fact] public void TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); client.Create(newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create(newRepository)); Assert.False(exception.OwnerIsOrganization); Assert.Null(exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Null(exception.ExistingRepositoryWebUrl); } [Fact] public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository("aName") { Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>( () => client.Create(newRepository)); Assert.NotNull(exception); } } public class TheCreateMethodForOrganization { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null, new NewRepository("aName"))); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create("aLogin", null)); } [Fact] public async Task UsesTheOrganizatinosReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Create("theLogin", new NewRepository("aName")); connection.Received().Post<Repository>( Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"), Args.NewRepository); } [Fact] public async Task TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); await client.Create("aLogin", newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.True(exception.OwnerIsOrganization); Assert.Equal("illuminati", exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.", exception.Message); } [Fact] public async Task ThrowsValidationException() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<ApiValidationException>( () => client.Create("illuminati", newRepository)); Assert.Null(exception as RepositoryExistsException); } [Fact] public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(new Uri("https://example.com")); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); } } public class TheDeleteMethod { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete(null, "aRepoName")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete("anOwner", null)); } [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete("theOwner", "theRepoName"); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/theOwner/theRepoName")); } } public class TheGetMethod { [Fact] public void RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Get("fake", "repo"); connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null)); } } public class TheGetAllPublicMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllPublic(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories")); } } public class TheGetAllPublicSinceMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllPublic(new PublicRepositoryRequest(364)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories?since=364")); } [Fact] public void SendsTheCorrectParameter() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllPublic(new PublicRepositoryRequest(364)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "/repositories?since=364")); } } public class TheGetAllForCurrentMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForCurrent(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos")); } [Fact] public void CanFilterByType() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.All }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "all")); } [Fact] public void CanFilterBySort() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Private, Sort = RepositorySort.FullName }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "private" && d["sort"] == "full_name")); } [Fact] public void CanFilterBySortDirection() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Member, Sort = RepositorySort.Updated, Direction = SortDirection.Ascending }; client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "member" && d["sort"] == "updated" && d["direction"] == "asc")); } } public class TheGetAllForUserMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForUser("username"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos")); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null)); } } public class TheGetAllForOrgMethod { [Fact] public void RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllForOrg("orgname"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos")); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null)); } } public class TheGetAllBranchesMethod { [Fact] public void ReturnsBranches() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllBranches("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", "")); } } public class TheGetAllContributorsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllContributors("owner", "name"); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>()); } [Fact] public async Task EnsuresArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "")); } } public class TheGetAllLanguagesMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages("owner", "name"); connection.Received() .Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("owner", "")); } } public class TheGetAllTeamsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTeams("owner", "name"); connection.Received() .GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", "")); } } public class TheGetAllTagsMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllTags("owner", "name"); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", "")); } } public class TheGetBranchMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetBranch("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void PatchesCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate(); client.Edit("owner", "repo", update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>()); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new RepositoryUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", update)); } } public class TheCompareMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("", "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", null, "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "base", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "head"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head")); } [Fact] public void EncodesUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch")); } } public class TheGetCommitMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", "")); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Get("owner", "name", "reference"); connection.Received() .Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference")); } } public class TheGetAllCommitsMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "repo", null)); } [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetAll("owner", "name"); connection.Received() .GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"), Arg.Any<Dictionary<string, string>>()); } } public class TheEditBranchMethod { [Fact] public void GetsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.EditBranch("owner", "repo", "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new BranchUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "repo", "", update)); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; using System.Xml; using DocumentFormat.OpenXml.Packaging; namespace DocumentFormat.OpenXml { /// <summary> /// OpenXmlLoadMode - load mode, default is Lazy /// Full - load all the OpenXmlElements recursively /// Lazy (default) - load N layer descendant elements from the current element, lazy load (cache OuterXml) for others /// default is populate 3 layers /// </summary> internal enum OpenXmlLoadMode { /// <summary> /// Load all the OpenXmlElements recursively /// </summary> Full, /// <summary> /// Load only one layer element, cache OuterXml /// </summary> Lazy, ///// <summary> ///// Full populate the top N layers, and then lazy load others. ///// </summary> //TopLayers } /// <summary> /// Represents the OpenXml loading context. /// </summary> public class OpenXmlElementContext { #region const data internal const string xmlnsUri = @"http://www.w3.org/2000/xmlns/"; internal const string xmlnsPrefix = "xmlns"; #endregion #region data member private OpenXmlPart _ownerPart; // TODO: XmlNameTable, XmlParserContext, NamespaceManager private XmlNameTable _xmlNameTable; // private XmlNamespaceManager _xmlNamespaceManager; // private XmlParserContext _xmlParserContext; private XmlReaderSettings _xmlReaderSettings; private OpenXmlLoadMode _loadMode = OpenXmlLoadMode.Full; private int _lazySteps = 3; private EventHandler<ElementEventArgs> _onElementInserting; private EventHandler<ElementEventArgs> _onElementInserted; private EventHandler<ElementEventArgs> _onElementRemoving; private EventHandler<ElementEventArgs> _onElementRemoved; private MarkupCompatibilityProcessSettings _mcSettings; internal MarkupCompatibilityProcessSettings MCSettings { get { if (_mcSettings == null) { _mcSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.NoProcess, FileFormatVersions.Office2007 | FileFormatVersions.Office2010 | FileFormatVersions.Office2013); } return _mcSettings; } set { _mcSettings = value; } } #endregion internal OpenXmlPart OwnerPart { get { return _ownerPart; } set { _ownerPart = value; } } /// <summary> /// The XmlNameTable to be used by internal XmlReader /// </summary> private XmlNameTable XmlNameTable { get { return _xmlNameTable; } // set { _xmlNameTable = value; } } /// <summary> /// The XmlReaderSettings to be used by internal XmlReader /// </summary> internal XmlReaderSettings XmlReaderSettings { get { return _xmlReaderSettings; } set { _xmlReaderSettings = value; } } /// <summary> /// Load mode /// </summary> internal OpenXmlLoadMode LoadMode { get { return _loadMode; } set { _loadMode = value; } } /// <summary> /// Layers to be full populated, only effective when LoadMode==Lazy. /// Start from 0 (populate only the children layer). /// </summary> internal int LazySteps { get { return this._lazySteps; } set { if (value < 0) { this._lazySteps = 0; } else { this._lazySteps = value; } } } //public XmlNamespaceManager XmlNamespaceManager //{ // get { return _xmlNamespaceManager; } // // set { _xmlNamespaceManager = value; } //} //public XmlParserContext XmlParserContext //{ // get { return _xmlParserContext; } // //set { _xmlParserContext = value; } //} /// <summary> /// Initializes a new instance of the OpenXmlElementContext class. /// </summary> public OpenXmlElementContext() { // this._xmlParserContext = new XmlParserContext( this._xmlNameTable = new NameTable(); MCContext = new MCContext(); Init(); } ///// <summary> ///// OpenXmlElementContext constructor ///// </summary> //public OpenXmlElementContext(OpenXmlPart ownerPart) //{ // this._ownerPart = ownerPart; // // this._xmlParserContext = new XmlParserContext( // this._xmlNameTable = new NameTable(); // Init(); //} internal static XmlReaderSettings CreateDefaultXmlReaderSettings() { XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); xmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit; // set true explicitly for security fix // init XmlReaderSettings xmlReaderSettings.NameTable = new NameTable(); // O15:#3024890, Set IgnoreWhitespace to false for the SDK to handle the whitespace node type. We have to do this because // PPT does not use the preserve attribute (xml:space="preserve") for non-ignorable whitespaces. (See the bug for details.) xmlReaderSettings.IgnoreWhitespace = false; // load predifined namespace to nametable for (int i = 1; i < NamespaceIdMap.Count; i++) { xmlReaderSettings.NameTable.Add(NamespaceIdMap.GetNamespaceUri((byte)i)); } xmlReaderSettings.NameTable.Add(xmlnsUri); return xmlReaderSettings; } /// <summary> /// Determines whether the namespace uri equals @"http://www.w3.org/2000/xmlns/". /// </summary> /// <param name="nsUri">The namespace uri.</param> /// <returns>Returns true if nsUri equals @"http://www.w3.org/2000/xmlns/".</returns> internal bool IsXmlnsUri(string nsUri) { return this._xmlNameTable.Get(nsUri) == xmlnsUri; } private void Init() { // load predifined namespace to nametable for (int i = 1; i < NamespaceIdMap.Count; i++) { this._xmlNameTable.Add(NamespaceIdMap.GetNamespaceUri( (byte)i )); } this._xmlNameTable.Add(xmlnsUri); // init XmlReaderSettings this.XmlReaderSettings = new XmlReaderSettings(); this.XmlReaderSettings.NameTable = this.XmlNameTable; // O15:#3024890, Set IgnoreWhitespace to false for the SDK to handle the whitespace node type. We have to do this because // PPT does not use the preserve attribute (xml:space="preserve") for non-ignorable whitespaces. (See the bug for details.) this.XmlReaderSettings.IgnoreWhitespace = false; } #region Event mechanism /// <summary> /// Fires the ElementInserting event. /// </summary> /// <param name="element">The OpenXmlElement element to insert.</param> /// <param name="parent">The parent element.</param> internal void ElementInsertingEvent(OpenXmlElement element, OpenXmlElement parent) { if (this._onElementInserting != null) { this._onElementInserting(this, new ElementEventArgs(element, parent)); } } /// <summary> /// Fires the ElementInserted event. /// </summary> /// <param name="element">The inserted OpenXmlElement element.</param> /// <param name="parent">The parent element.</param> internal void ElementInsertedEvent(OpenXmlElement element, OpenXmlElement parent) { if (this._onElementInserted != null) { this._onElementInserted(this, new ElementEventArgs(element, parent)); } } /// <summary> /// Fires the ElementRemoving event. /// </summary> /// <param name="element">The OpenXmlElement element to remove.</param> /// <param name="parent">The parent element.</param> internal void ElementRemovingEvent(OpenXmlElement element, OpenXmlElement parent) { if (this._onElementRemoving != null) { this._onElementRemoving(this, new ElementEventArgs(element, parent)); } } /// <summary> /// Fires the ElementRemoved event. /// </summary> /// <param name="element">The removed OpenXmlElement element.</param> /// <param name="parent">The parent element.</param> internal void ElementRemovedEvent(OpenXmlElement element, OpenXmlElement parent) { if (this._onElementRemoved != null) { this._onElementRemoved(this, new ElementEventArgs(element, parent)); } } /// <summary> /// Occurs when an element is about to be inserted into the element hierarchy. /// </summary> public event EventHandler<ElementEventArgs> ElementInserting { add { this._onElementInserting = (EventHandler<ElementEventArgs>)Delegate.Combine(this._onElementInserting, value); } remove { this._onElementInserting = (EventHandler<ElementEventArgs>)Delegate.Remove(this._onElementInserting, value); } } /// <summary> /// Occurs when an element has been inserted into the element hierarchy. /// </summary> public event EventHandler<ElementEventArgs> ElementInserted { add { this._onElementInserted = (EventHandler<ElementEventArgs>)Delegate.Combine(this._onElementInserted, value); } remove { this._onElementInserted = (EventHandler<ElementEventArgs>)Delegate.Remove(this._onElementInserted, value); } } /// <summary> /// Occurs when an element is being removed from the element hierarchy. /// </summary> public event EventHandler<ElementEventArgs> ElementRemoving { add { this._onElementRemoving = (EventHandler<ElementEventArgs>)Delegate.Combine(this._onElementRemoving, value); } remove { this._onElementRemoving = (EventHandler<ElementEventArgs>)Delegate.Remove(this._onElementRemoving, value); } } /// <summary> /// Occurs when an element has been removed from the element hierarchy. /// </summary> public event EventHandler<ElementEventArgs> ElementRemoved { add { this._onElementRemoved = (EventHandler<ElementEventArgs>)Delegate.Combine(this._onElementRemoved, value); } remove { this._onElementRemoved = (EventHandler<ElementEventArgs>)Delegate.Remove(this._onElementRemoved, value); } } #endregion internal MCContext MCContext { get; set; } internal uint ACBlockLevel { get; set; } } /// <summary> /// Represents arguments for element events. /// </summary> public class ElementEventArgs : EventArgs { private OpenXmlElement _element; private OpenXmlElement _parentElement; /// <summary> /// Initializes a new instance of the ElementEventArgs class using the /// supplied elements. /// </summary> /// <param name="element"> /// The element that caused the event. /// </param> /// <param name="parentElement"> /// The parent element of the element that caused the event. /// </param> public ElementEventArgs(OpenXmlElement element, OpenXmlElement parentElement) { this._element = element; this._parentElement = parentElement; } /// <summary> /// Gets the element that caused the event. /// </summary> public OpenXmlElement Element { get { return this._element; } } /// <summary> /// Gets the parent element of the element that caused the event. /// </summary> public OpenXmlElement ParentElement { get { return this._parentElement; } } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Text; namespace Irony.Parsing { public partial class Grammar { #region properties /// <summary> /// Gets case sensitivity of the grammar. Read-only, true by default. /// Can be set to false only through a parameter to grammar constructor. /// </summary> public readonly bool CaseSensitive = true; public readonly StringComparer LanguageStringComparer; public readonly StringComparison StringComparisonMode; //List of chars that unambigously identify the start of new token. //used in scanner error recovery, and in quick parse path in NumberLiterals, Identifiers public string Delimiters = null; public string WhitespaceChars = " \t\r\n\v"; //Used for line counting in source file public string LineTerminators = "\n\r\v"; #region Language Flags public LanguageFlags LanguageFlags = LanguageFlags.Default; #endregion public TermReportGroupList TermReportGroups = new TermReportGroupList(); //Terminals not present in grammar expressions and not reachable from the Root // (Comment terminal is usually one of them) // Tokens produced by these terminals will be ignored by parser input. public readonly TerminalSet NonGrammarTerminals = new TerminalSet(); //Terminals that either don't have explicitly declared Firsts symbols, or can start with chars not covered by these Firsts // For ex., identifier in c# can start with a Unicode char in one of several Unicode classes, not necessarily latin letter. // Whenever terminals with explicit Firsts() cannot produce a token, the Scanner would call terminals from this fallback // collection to see if they can produce it. // Note that IdentifierTerminal automatically add itself to this collection if its StartCharCategories list is not empty, // so programmer does not need to do this explicitly public readonly TerminalSet FallbackTerminals = new TerminalSet(); public Type DefaultNodeType; public Type DefaultLiteralNodeType; //default node type for literals public Type DefaultIdentifierNodeType; //default node type for identifiers /// <summary> /// The main root entry for the grammar. /// </summary> public NonTerminal Root; /// <summary> /// Alternative roots for parsing code snippets. /// </summary> public NonTerminalSet SnippetRoots = new NonTerminalSet(); public string GrammarComments; //shown in Grammar info tab public CultureInfo DefaultCulture = CultureInfo.InvariantCulture; //Console-related properties, initialized in grammar constructor public string ConsoleTitle; public string ConsoleGreeting; public string ConsolePrompt; //default prompt public string ConsolePromptMoreInput; //prompt to show when more input is expected public readonly OperatorInfoDictionary OperatorMappings; #endregion #region constructors public Grammar() : this(true) { } //case sensitive by default public Grammar(bool caseSensitive) { _currentGrammar = this; this.CaseSensitive = caseSensitive; bool ignoreCase = !this.CaseSensitive; LanguageStringComparer = StringComparer.Create(System.Globalization.CultureInfo.InvariantCulture, ignoreCase); StringComparisonMode = CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; KeyTerms = new KeyTermTable(LanguageStringComparer); //Initialize console attributes ConsoleTitle = Resources.MsgDefaultConsoleTitle; ConsoleGreeting = string.Format(Resources.MsgDefaultConsoleGreeting, this.GetType().Name); ConsolePrompt = ">"; ConsolePromptMoreInput = "."; OperatorMappings = OperatorUtility.GetDefaultOperatorMappings(caseSensitive); } #endregion #region Reserved words handling //Reserved words handling public void MarkReservedWords(params string[] reservedWords) { foreach (var word in reservedWords) { var wdTerm = ToTerm(word); wdTerm.SetFlag(TermFlags.IsReservedWord); } } #endregion #region Register/Mark methods public void RegisterOperators(int precedence, params string[] opSymbols) { RegisterOperators(precedence, Associativity.Left, opSymbols); } public void RegisterOperators(int precedence, Associativity associativity, params string[] opSymbols) { foreach (string op in opSymbols) { KeyTerm opSymbol = ToTerm(op); opSymbol.SetFlag(TermFlags.IsOperator); opSymbol.Precedence = precedence; opSymbol.Associativity = associativity; } }//method public void RegisterOperators(int precedence, params BnfTerm[] opTerms) { RegisterOperators(precedence, Associativity.Left, opTerms); } public void RegisterOperators(int precedence, Associativity associativity, params BnfTerm[] opTerms) { foreach (var term in opTerms) { term.SetFlag(TermFlags.IsOperator); term.Precedence = precedence; term.Associativity = associativity; } } public void RegisterBracePair(string openBrace, string closeBrace) { KeyTerm openS = ToTerm(openBrace); KeyTerm closeS = ToTerm(closeBrace); openS.SetFlag(TermFlags.IsOpenBrace); openS.IsPairFor = closeS; closeS.SetFlag(TermFlags.IsCloseBrace); closeS.IsPairFor = openS; } [Obsolete("RegisterPunctuation is renamed to MarkPunctuation.")] public void RegisterPunctuation(params string[] symbols) { MarkPunctuation(symbols); } [Obsolete("RegisterPunctuation is renamed to MarkPunctuation.")] public void RegisterPunctuation(params BnfTerm[] terms) { MarkPunctuation(terms); } public void MarkPunctuation(params string[] symbols) { foreach (string symbol in symbols) { KeyTerm term = ToTerm(symbol); term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode); } } public void MarkPunctuation(params BnfTerm[] terms) { foreach (BnfTerm term in terms) term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode); } public void MarkTransient(params NonTerminal[] nonTerminals) { foreach (NonTerminal nt in nonTerminals) nt.Flags |= TermFlags.IsTransient | TermFlags.NoAstNode; } //MemberSelect are symbols invoking member list dropdowns in editor; for ex: . (dot), :: public void MarkMemberSelect(params string[] symbols) { foreach (var symbol in symbols) ToTerm(symbol).SetFlag(TermFlags.IsMemberSelect); } //Sets IsNotReported flag on terminals. As a result the terminal wouldn't appear in expected terminal list // in syntax error messages public void MarkNotReported(params BnfTerm[] terms) { foreach (var term in terms) term.SetFlag(TermFlags.IsNotReported); } public void MarkNotReported(params string[] symbols) { foreach (var symbol in symbols) ToTerm(symbol).SetFlag(TermFlags.IsNotReported); } #endregion #region virtual methods: TryMatch, CreateNode, CreateRuntime, RunSample public virtual void CreateTokenFilters(LanguageData language, TokenFilterList filters) { } //This method is called if Scanner fails to produce a token; it offers custom method a chance to produce the token public virtual Token TryMatch(ParsingContext context, ISourceStream source) { return null; } //Gives a way to customize parse tree nodes captions in the tree view. public virtual string GetParseNodeCaption(ParseTreeNode node) { if (node.IsError) return node.Term.Name + " (Syntax error)"; if (node.Token != null) return node.Token.ToString(); if(node.Term == null) //special case for initial node pushed into the stack at parser start return (node.State != null ? string.Empty : "(State " + node.State.Name + ")"); // Resources.LabelInitialState; var ntTerm = node.Term as NonTerminal; if(ntTerm != null && !string.IsNullOrEmpty(ntTerm.NodeCaptionTemplate)) return ntTerm.GetNodeCaption(node); return node.Term.Name; } //Gives a chance of custom AST node creation at Grammar level // by default calls Term's method public virtual void CreateAstNode(ParsingContext context, ParseTreeNode parseTreeNode) { parseTreeNode.Term.CreateAstNode(context, parseTreeNode); } /// <summary> /// Override this method to help scanner select a terminal to create token when there are more than one candidates /// for an input char. context.CurrentTerminals contains candidate terminals; leave a single terminal in this list /// as the one to use. /// </summary> public virtual void OnScannerSelectTerminal(ParsingContext context) { } /// <summary> /// Override this method to provide custom conflict resolution; for example, custom code may decide proper shift or reduce /// action based on preview of tokens ahead. /// </summary> public virtual void OnResolvingConflict(ConflictResolutionArgs args) { //args.Result is Shift by default } //The method is called after GrammarData is constructed public virtual void OnGrammarDataConstructed(LanguageData language) { } public virtual void OnLanguageDataConstructed(LanguageData language) { } //Constructs the error message in situation when parser has no available action for current input. // override this method if you want to change this message public virtual string ConstructParserErrorMessage(ParsingContext context, StringSet expectedTerms) { return string.Format(Resources.ErrParserUnexpInput, expectedTerms.ToString(", ")); } // Override this method to perform custom error processing public virtual void ReportParseError(ParsingContext context) { string error = null; if (context.CurrentParserInput.Term == this.SyntaxError) error = context.CurrentParserInput.Token.Value as string; //scanner error else if (context.CurrentParserInput.Term == this.Indent) error = Resources.ErrUnexpIndent; else if (context.CurrentParserInput.Term == this.Eof && context.OpenBraces.Count > 0) { //report unclosed braces/parenthesis var openBrace = context.OpenBraces.Peek(); error = string.Format(Resources.ErrNoClosingBrace, openBrace.Text); } else { var expectedTerms = context.GetExpectedTermSet(); if (expectedTerms.Count > 0) error = ConstructParserErrorMessage(context, expectedTerms); //error = string.Format(Resources.ErrParserUnexpInput, expectedTerms.ToString(" ") else error = Resources.ErrUnexpEof; } context.AddParserError(error); }//method #endregion #region MakePlusRule, MakeStarRule methods public static BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm listMember) { return MakePlusRule(listNonTerminal, null, listMember); } public static BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember, TermListOptions options) { bool allowTrailingDelimiter = (options & TermListOptions.AllowTrailingDelimiter) != 0; if (delimiter == null || !allowTrailingDelimiter) return MakePlusRule(listNonTerminal, delimiter, listMember); //create plus list var plusList = new NonTerminal(listMember.Name + "+"); plusList.Rule = MakePlusRule(listNonTerminal, delimiter, listMember); listNonTerminal.Rule = plusList | plusList + delimiter; listNonTerminal.SetFlag(TermFlags.IsListContainer); return listNonTerminal.Rule; } public static BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) { if (delimiter == null) listNonTerminal.Rule = listMember | listNonTerminal + listMember; else listNonTerminal.Rule = listMember | listNonTerminal + delimiter + listMember; listNonTerminal.SetFlag(TermFlags.IsList); return listNonTerminal.Rule; } public static BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm listMember) { return MakeStarRule(listNonTerminal, null, listMember, TermListOptions.None); } public static BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) { return MakeStarRule(listNonTerminal, delimiter, listMember, TermListOptions.None); } public static BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember, TermListOptions options) { bool allowTrailingDelimiter = (options & TermListOptions.AllowTrailingDelimiter) != 0; if (delimiter == null) { //it is much simpler case listNonTerminal.SetFlag(TermFlags.IsList); listNonTerminal.Rule = _currentGrammar.Empty | listNonTerminal + listMember; return listNonTerminal.Rule; } //Note that deceptively simple version of the star-rule // Elem* -> Empty | Elem | Elem* + delim + Elem // does not work when you have delimiters. This simple version allows lists starting with delimiters - // which is wrong. The correct formula is to first define "Elem+"-list, and then define "Elem*" list // as "Elem* -> Empty|Elem+" NonTerminal plusList = new NonTerminal(listMember.Name + "+"); plusList.Rule = MakePlusRule(plusList, delimiter, listMember); plusList.SetFlag(TermFlags.NoAstNode); //to allow it to have AstNodeType not assigned if (allowTrailingDelimiter) listNonTerminal.Rule = _currentGrammar.Empty | plusList | plusList + delimiter; else listNonTerminal.Rule = _currentGrammar.Empty | plusList; listNonTerminal.SetFlag(TermFlags.IsListContainer); return listNonTerminal.Rule; } #endregion #region Hint utilities protected GrammarHint PreferShiftHere() { return new GrammarHint(HintType.ResolveToShift, null); } protected GrammarHint ReduceHere() { return new GrammarHint(HintType.ResolveToReduce, null); } protected GrammarHint ResolveInCode() { return new GrammarHint(HintType.ResolveInCode, null); } protected TokenPreviewHint ReduceIf(string symbol) { return new TokenPreviewHint(ParserActionType.Reduce, symbol); } protected TokenPreviewHint ShiftIf(string symbol) { return new TokenPreviewHint(ParserActionType.Shift, symbol); } protected GrammarHint ImplyPrecedenceHere(int precedence) { return ImplyPrecedenceHere(precedence, Associativity.Left); } protected GrammarHint ImplyPrecedenceHere(int precedence, Associativity associativity) { var hint = new GrammarHint(HintType.Precedence, null); hint.Precedence = precedence; hint.Associativity = associativity; return hint; } #endregion #region Term report group methods /// <summary> /// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like /// "Syntax error, expected: [list of terms]" /// </summary> /// <param name="alias">An alias for all terminals in the group.</param> /// <param name="symbols">Symbols to be included into the group.</param> protected void AddTermsReportGroup(string alias, params string[] symbols) { TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, SymbolsToTerms(symbols))); } /// <summary> /// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like /// "Syntax error, expected: [list of terms]" /// </summary> /// <param name="alias">An alias for all terminals in the group.</param> /// <param name="terminals">Terminals to be included into the group.</param> protected void AddTermsReportGroup(string alias, params Terminal[] terminals) { TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, terminals)); } /// <summary> /// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages. /// </summary> /// <param name="symbols">Symbols to exclude.</param> protected void AddToNoReportGroup(params string[] symbols) { TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, SymbolsToTerms(symbols))); } /// <summary> /// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages. /// </summary> /// <param name="symbols">Symbols to exclude.</param> protected void AddToNoReportGroup(params Terminal[] terminals) { TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, terminals)); } /// <summary> /// Adds a group and an alias for all operator symbols used in the grammar. /// </summary> /// <param name="alias">An alias for operator symbols.</param> protected void AddOperatorReportGroup(string alias) { TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Operator, null)); //operators will be filled later } private IEnumerable<Terminal> SymbolsToTerms(IEnumerable<string> symbols) { var termList = new TerminalList(); foreach(var symbol in symbols) termList.Add(ToTerm(symbol)); return termList; } #endregion #region Standard terminals: EOF, Empty, NewLine, Indent, Dedent // Empty object is used to identify optional element: // term.Rule = term1 | Empty; public readonly Terminal Empty = new Terminal("EMPTY"); // The following terminals are used in indent-sensitive languages like Python; // they are not produced by scanner but are produced by CodeOutlineFilter after scanning public readonly NewLineTerminal NewLine = new NewLineTerminal("LF"); public readonly Terminal Indent = new Terminal("INDENT", TokenCategory.Outline, TermFlags.IsNonScanner); public readonly Terminal Dedent = new Terminal("DEDENT", TokenCategory.Outline, TermFlags.IsNonScanner); //End-of-Statement terminal - used in indentation-sensitive language to signal end-of-statement; // it is not always synced with CRLF chars, and CodeOutlineFilter carefully produces Eos tokens // (as well as Indent and Dedent) based on line/col information in incoming content tokens. public readonly Terminal Eos = new Terminal("EOS", Resources.LabelEosLabel, TokenCategory.Outline, TermFlags.IsNonScanner); // Identifies end of file // Note: using Eof in grammar rules is optional. Parser automatically adds this symbol // as a lookahead to Root non-terminal public readonly Terminal Eof = new Terminal("EOF", TokenCategory.Outline); //Used for error tokens public readonly Terminal LineStartTerminal = new Terminal("LINE_START", TokenCategory.Outline); //Used for error tokens public readonly Terminal SyntaxError = new Terminal("SYNTAX_ERROR", TokenCategory.Error, TermFlags.IsNonScanner); public NonTerminal NewLinePlus { get { if(_newLinePlus == null) { _newLinePlus = new NonTerminal("LF+"); MarkPunctuation(_newLinePlus); _newLinePlus.Rule = MakePlusRule(_newLinePlus, NewLine); } return _newLinePlus; } } NonTerminal _newLinePlus; public NonTerminal NewLineStar { get { if(_newLineStar == null) { _newLineStar = new NonTerminal("LF*"); MarkPunctuation(_newLineStar); _newLineStar.Rule = MakeStarRule(_newLineStar, NewLine); } return _newLineStar; } } NonTerminal _newLineStar; #endregion #region KeyTerms (keywords + special symbols) public KeyTermTable KeyTerms; public KeyTerm ToTerm(string text) { return ToTerm(text, text); } public KeyTerm ToTerm(string text, string name) { KeyTerm term; if (KeyTerms.TryGetValue(text, out term)) { //update name if it was specified now and not before if (string.IsNullOrEmpty(term.Name) && !string.IsNullOrEmpty(name)) term.Name = name; return term; } //create new term if (!CaseSensitive) text = text.ToLower(CultureInfo.InvariantCulture); string.Intern(text); term = new KeyTerm(text, name); KeyTerms[text] = term; return term; } #endregion #region CurrentGrammar static field //Static per-thread instance; Grammar constructor sets it to self (this). // This field/property is used by operator overloads (which are static) to access Grammar's predefined terminals like Empty, // and SymbolTerms dictionary to convert string literals to symbol terminals and add them to the SymbolTerms dictionary [ThreadStatic] private static Grammar _currentGrammar; public static Grammar CurrentGrammar { get { return _currentGrammar; } } internal static void ClearCurrentGrammar() { _currentGrammar = null; } #endregion }//class }//namespace
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Reflection; using System.Web.Http; using System.Web.Http.Controllers; using SocialEventPlannerWeb.Areas.RouteDebugger.Models; namespace SocialEventPlannerWeb.Areas.RouteDebugger.Components { /// <summary> /// Simulate the action selection and record the decision making process. /// /// This class is basically a copy of default IHttpActionSelector implementation (DefaultActionSelector) private members, /// and methods where we have included logging. /// The private members of the DefaultActionSelector are copied here, so we can access them. /// /// Some help internal help classes are also copied to assist the process, /// </summary> public class ActionSelectSimulator { private ReflectedHttpActionDescriptor[] _actionDescriptors; private IDictionary<ReflectedHttpActionDescriptor, string[]> _actionParameterNames = new Dictionary<ReflectedHttpActionDescriptor, string[]>(); private ILookup<string, ReflectedHttpActionDescriptor> _actionNameMapping; private void Initialize(HttpControllerDescriptor controllerDesc) { MethodInfo[] allMethods = controllerDesc.ControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public); MethodInfo[] validMethods = Array.FindAll(allMethods, IsValidActionMethod); _actionDescriptors = new ReflectedHttpActionDescriptor[validMethods.Length]; for (int i = 0; i < validMethods.Length; i++) { MethodInfo method = validMethods[i]; ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDesc, method); _actionDescriptors[i] = actionDescriptor; HttpActionBinding actionBinding = actionDescriptor.ActionBinding; // Building an action parameter name mapping to compare against the URI parameters coming from the request. // Here we only take into account required parameters that are simple types and come from the URI. _actionParameterNames.Add( actionDescriptor, actionBinding.ParameterBindings .Where(binding => !binding.Descriptor.IsOptional && TypeHelper.IsSimpleUnderlyingType(binding.Descriptor.ParameterType) && binding.WillReadUri()) .Select(binding => binding.Descriptor.Prefix ?? binding.Descriptor.ParameterName).ToArray()); } _actionNameMapping = _actionDescriptors.ToLookup(actionDesc => actionDesc.ActionName, StringComparer.OrdinalIgnoreCase); } /// <summary> /// Simulating the action selecting process. It mimics the ASP.NET Web API internal logic /// </summary> /// <param name="controllerContext">The controller context.</param> /// <returns>A structure contains the log of selecting process</returns> public ActionSelectionLog Simulate(HttpControllerContext controllerContext) { Initialize(controllerContext.ControllerDescriptor); ActionSelectionLog log = new ActionSelectionLog(_actionDescriptors); // If the action name exists in route data, filter the action descriptors based on action name. ReflectedHttpActionDescriptor[] actionsFoundByMethod = null; var routeData = controllerContext.Request.GetRouteData(); string actionName; if (routeData.Values.TryGetValue("action", out actionName)) { var actionsFound = _actionNameMapping[actionName].OfType<ReflectedHttpActionDescriptor>().ToArray(); // Filter actions based on verb. actionsFoundByMethod = actionsFound .Where(actionDescriptor => actionDescriptor.SupportedHttpMethods.Contains(controllerContext.Request.Method)) .ToArray(); log.ActionName = actionName; log.MarkSelected(actionsFound, info => info.FoundByActionName = true); log.MarkOthersSelected(actionsFound, info => info.FoundByActionName = false); log.MarkSelected(actionsFound, info => info.FoundByActionNameWithRightVerb = false); log.MarkSelected(actionsFoundByMethod, info => info.FoundByActionNameWithRightVerb = true); } else { log.ActionName = string.Empty; // If action name doesn't exist, find actions based on HTTP verb. log.HttpMethod = controllerContext.Request.Method; if (string.IsNullOrEmpty(actionName)) { actionsFoundByMethod = FindActionsForVerb(log.HttpMethod); log.MarkSelected(actionsFoundByMethod, info => info.FoundByVerb = true); } } // If no action is found at this stage a failure must happen. if (actionsFoundByMethod != null && actionsFoundByMethod.Length != 0) { // filter the actions by parameters matching var actionsFilterByParam = FindActionUsingRouteAndQueryParameters( controllerContext, actionsFoundByMethod, !string.IsNullOrEmpty(actionName)).ToArray(); log.MarkSelected(actionsFoundByMethod, info => info.FoundWithRightParam = false); log.MarkSelected(actionsFilterByParam, info => info.FoundWithRightParam = true); // filter the actions by selection filters var actionsFilterBySelectors = RunSelectionFilters(controllerContext, actionsFilterByParam).ToArray(); log.MarkSelected(actionsFilterByParam, info => info.FoundWithSelectorsRun = false); log.MarkSelected(actionsFilterBySelectors, info => info.FoundWithSelectorsRun = true); } return log; } /// <summary> /// This is a copy of the private ApiControllerActionSelector.FindActionsForVerb. It doesn't use the cache /// but copies the contents of the FindActionsForVerbWorker method. /// </summary> private ReflectedHttpActionDescriptor[] FindActionsForVerb(HttpMethod verb) { List<ReflectedHttpActionDescriptor> listMethods = new List<ReflectedHttpActionDescriptor>(); foreach (ReflectedHttpActionDescriptor descriptor in _actionDescriptors) { if (descriptor.SupportedHttpMethods.Contains(verb)) { listMethods.Add(descriptor); } } return listMethods.ToArray(); } /// <summary> /// This is an exact copy from ApiControllerActionSelector. /// </summary> private IEnumerable<ReflectedHttpActionDescriptor> FindActionUsingRouteAndQueryParameters( HttpControllerContext controllerContext, IEnumerable<ReflectedHttpActionDescriptor> actionsFound, bool hasActionRouteKey) { IDictionary<string, object> routeValues = controllerContext.RouteData.Values; HashSet<string> routeParameterNames = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase); routeParameterNames.Remove("controller"); if (hasActionRouteKey) { routeParameterNames.Remove("action"); } HttpRequestMessage request = controllerContext.Request; Uri requestUri = request.RequestUri; bool hasQueryParameters = requestUri != null && !String.IsNullOrEmpty(requestUri.Query); bool hasRouteParameters = routeParameterNames.Count != 0; if (hasRouteParameters || hasQueryParameters) { var combinedParameterNames = new HashSet<string>(routeParameterNames, StringComparer.OrdinalIgnoreCase); if (hasQueryParameters) { foreach (var queryNameValuePair in request.GetQueryNameValuePairs()) { combinedParameterNames.Add(queryNameValuePair.Key); } } // action parameters is a subset of route parameters and query parameters actionsFound = actionsFound.Where(descriptor => IsSubset(_actionParameterNames[descriptor], combinedParameterNames)); if (actionsFound.Count() > 1) { // select the results that match the most number of required parameters actionsFound = actionsFound .GroupBy(descriptor => _actionParameterNames[descriptor].Length) .OrderByDescending(g => g.Key) .First(); } } else { // return actions with no parameters actionsFound = actionsFound.Where(descriptor => _actionParameterNames[descriptor].Length == 0); } return actionsFound; } /// <summary> /// This is an exact copy from ApiControllerActionSelector. /// </summary> private static bool IsValidActionMethod(MethodInfo methodInfo) { if (methodInfo.IsSpecialName) { // not a normal method, e.g. a constructor or an event return false; } if (methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(TypeHelper.ApiControllerType)) { // is a method on Object, IHttpController, ApiController return false; } return true; } /// <summary> /// This is an exact copy from ApiControllerActionSelector. /// </summary> private static bool IsSubset(string[] actionParameters, HashSet<string> routeAndQueryParameters) { foreach (string actionParameter in actionParameters) { if (!routeAndQueryParameters.Contains(actionParameter)) { return false; } } return true; } /// <summary> /// Replace the private method from ApiControllerActionSelector. /// /// The IActionMethodSelector interface used in the method is internal so we must make a copy. /// CacheAttrsIActionMethodSelector is also internal. /// The default implementation of IActionMethodSelector finds methods marked with the NonActionAttribute, so the /// code below is converted to directly filter out methods with that attribute. /// </summary> private static List<ReflectedHttpActionDescriptor> RunSelectionFilters( HttpControllerContext controllerContext, IEnumerable<HttpActionDescriptor> descriptorsFound) { // remove all methods which are opting out of this request // to opt out, at least one attribute defined on the method must return false List<ReflectedHttpActionDescriptor> matchesWithSelectionAttributes = null; List<ReflectedHttpActionDescriptor> matchesWithoutSelectionAttributes = new List<ReflectedHttpActionDescriptor>(); foreach (ReflectedHttpActionDescriptor actionDescriptor in descriptorsFound) { var attrs = actionDescriptor.GetCustomAttributes<NonActionAttribute>().ToArray(); if (attrs.Length == 0) { matchesWithoutSelectionAttributes.Add(actionDescriptor); } else { // The following code will never run (it's always false) System.Diagnostics.Debug.Assert(false, "This control flow is not expected to be accessed"); } } // if a matching action method had a selection attribute, consider it more specific than a matching action method // without a selection attribute if ((matchesWithSelectionAttributes != null) && (matchesWithSelectionAttributes.Count > 0)) { return matchesWithSelectionAttributes; } else { return matchesWithoutSelectionAttributes; } } } }
using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace MongoDB.Messaging.Storage { /// <summary> /// The queue storage repository /// </summary> public class QueueRepository : IQueueRepository { private readonly IMongoCollection<Message> _collection; /// <summary> /// Initializes a new instance of the <see cref="QueueRepository"/> class. /// </summary> /// <param name="collection">The underlying storage collection.</param> public QueueRepository(IMongoCollection<Message> collection) { _collection = collection; } /// <summary> /// Gets the underlying storage collection. /// </summary> /// <value> /// The underlying storage collection. /// </value> public IMongoCollection<Message> Collection { get { return _collection; } } /// <summary> /// Start an <see cref="IQueryable" /> of all messages. /// </summary> /// <returns> /// An <see cref="IQueryable" /> of all messages. /// </returns> public IQueryable<Message> All() { return _collection.AsQueryable(); } /// <summary> /// Finds message with the specified <paramref name="id" /> as an asynchronous operation. /// </summary> /// <param name="id">The identifier of the message.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<Message> Find(string id) { return _collection .Find(m => m.Id == id) .FirstOrDefaultAsync(); } /// <summary> /// Finds one message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<Message> FindOne(Expression<Func<Message, bool>> criteria) { return _collection .Find(criteria) .FirstOrDefaultAsync(); } /// <summary> /// Finds all message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<List<Message>> FindAll(Expression<Func<Message, bool>> criteria) { return _collection .Find(criteria) .ToListAsync(); } /// <summary> /// Gets the number of message as an asynchronous operation. /// </summary> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> Count() { // empty document to get all var filter = new BsonDocument(); return _collection .CountAsync(filter); } /// <summary> /// Gets the number of message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria"></param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> Count(Expression<Func<Message, bool>> criteria) { return _collection .Find(criteria) .CountAsync(); } /// <summary> /// Save the specified <paramref name="message" /> as an asynchronous operation. /// </summary> /// <param name="message">The message to save.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> public Task<Message> Save(Message message) { if (message == null) throw new ArgumentNullException("message"); // generate id if null, upsert requires id if (string.IsNullOrEmpty(message.Id)) { message.Id = ObjectId.GenerateNewId().ToString(); message.Created = DateTime.UtcNow; } message.Updated = DateTime.UtcNow; var updateOptions = new UpdateOptions { IsUpsert = true }; return _collection .ReplaceOneAsync(m => m.Id == message.Id, message, updateOptions) .ContinueWith(t => message); } /// <summary> /// Delete the message with the specified <paramref name="id" /> as an asynchronous operation. /// </summary> /// <param name="id">The identifier of the message.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<long> Delete(string id) { if (id == null) throw new ArgumentNullException("id"); return _collection .DeleteOneAsync(m => m.Id == id) .ContinueWith(t => t.Result.DeletedCount); } /// <summary> /// Delete one message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> DeleteOne(Expression<Func<Message, bool>> criteria) { return _collection .DeleteOneAsync(criteria) .ContinueWith(t => t.Result.DeletedCount); } /// <summary> /// Delete all message with the specified <paramref name="criteria" /> as an asynchronous operation. /// </summary> /// <param name="criteria">The criteria expression.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<long> DeleteAll(Expression<Func<Message, bool>> criteria) { return _collection .DeleteManyAsync(criteria) .ContinueWith(t => t.Result.DeletedCount); } /// <summary> /// Enqueue the specified <paramref name="message" /> for processing as an asynchronous operation. /// </summary> /// <param name="message">The message to queue.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> public Task<Message> Enqueue(Message message) { if (message == null) throw new ArgumentNullException("message"); // mark state as queued message.State = MessageState.Queued; return Save(message); } /// <summary> /// Dequeues the next queued message for processing as an asynchronous operation. /// </summary> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task<Message> Dequeue(FilterDefinition<Message> queueFilter = null) { var filter = Builders<Message>.Filter.And( queueFilter ?? Builders<Message>.Filter.Empty, Builders<Message>.Filter.Eq(m => m.State, MessageState.Queued) ); var update = Builders<Message>.Update .Set(m => m.State, MessageState.Processing) .Set(p => p.Status, "Begin processing ...") .Set(p => p.StartTime, DateTime.UtcNow) .Set(p => p.Updated, DateTime.UtcNow); // sort by priority then by insert order var sort = Builders<Message>.Sort .Ascending(m => m.Priority) .Ascending(m => m.Id); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; options.Sort = sort; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Requeue the message with the specified <paramref name="id"/> as an asynchronous operation. /// </summary> /// <param name="id">The identifier of the message.</param> /// <returns> /// The <see cref="Task"/> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> Requeue(string id) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.State, MessageState.Queued) .Set(p => p.Updated, DateTime.UtcNow); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Schedules the message with specified identifier for processing on the <paramref name="scheduled"/> date and time. /// </summary> /// <param name="id">The message identifier to schedule.</param> /// <param name="scheduled">The date and time of the scheduled processing.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> Schedule(string id, DateTime scheduled) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.State, MessageState.Scheduled) .Set(p => p.Scheduled, scheduled.ToUniversalTime()) .Set(p => p.Updated, DateTime.UtcNow) .Unset(p => p.Expire); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Schedules the specified <paramref name="message" /> for future processing as an asynchronous operation. /// </summary> /// <param name="message">The message to queue.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">The Scheduled property can't be null when scheduling a message.</exception> public Task<Message> Schedule(Message message) { if (message == null) throw new ArgumentNullException("message"); if (message.Scheduled == null) throw new ArgumentException("The Scheduled property can't be null when scheduling a message.", "message"); // mark state as queued message.State = MessageState.Scheduled; return Save(message); } /// <summary> /// Updates the status of the message with specified <paramref name="id" /> as an asynchronous operation.. /// </summary> /// <param name="id">The identifier of the message.</param> /// <param name="status">The status display mesage.</param> /// <param name="step">The current processing step.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> UpdateStatus(string id, string status, int? step = null) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.Updated, DateTime.UtcNow); if (!string.IsNullOrEmpty(status)) update.Set(p => p.Status, status); if (step.HasValue) update.Set(p => p.Step, step.Value); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } /// <summary> /// Marks the processing complete for the message with specified <paramref name="id" /> as an asynchronous operation.. /// </summary> /// <param name="id">The identifier of the message.</param> /// <param name="messageResult">The result of the processing.</param> /// <param name="status">The status display mesage.</param> /// <param name="expireDate">The expire date.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="id"/> is <see langword="null" />.</exception> public Task<Message> MarkComplete(string id, MessageResult messageResult, string status = null, DateTime? expireDate = null) { if (id == null) throw new ArgumentNullException("id"); var filter = Builders<Message>.Filter .Eq(p => p.Id, id); var update = Builders<Message>.Update .Set(p => p.State, MessageState.Complete) .Set(p => p.Result, messageResult) .Set(p => p.EndTime, DateTime.UtcNow) .Set(p => p.Updated, DateTime.UtcNow); update = expireDate.HasValue ? update.Set(p => p.Expire, expireDate.Value) : update.Unset(p => p.Expire); if (!string.IsNullOrEmpty(status)) update = update.Set(p => p.Status, status); if (messageResult == MessageResult.Error) update = update.Inc(p => p.ErrorCount, 1); var options = new FindOneAndUpdateOptions<Message, Message>(); options.IsUpsert = false; options.ReturnDocument = ReturnDocument.After; return _collection.FindOneAndUpdateAsync(filter, update, options); } } }
// 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.ComponentModel; using System.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { public sealed class SqlDataAdapter : DbDataAdapter, IDbDataAdapter, ICloneable { private static readonly object EventRowUpdated = new object(); private static readonly object EventRowUpdating = new object(); private SqlCommand _deleteCommand, _insertCommand, _selectCommand, _updateCommand; private SqlCommandSet _commandSet; private int _updateBatchSize = 1; public SqlDataAdapter() : base() { GC.SuppressFinalize(this); } public SqlDataAdapter(SqlCommand selectCommand) : this() { SelectCommand = selectCommand; } public SqlDataAdapter(string selectCommandText, string selectConnectionString) : this() { SqlConnection connection = new SqlConnection(selectConnectionString); SelectCommand = new SqlCommand(selectCommandText, connection); } public SqlDataAdapter(string selectCommandText, SqlConnection selectConnection) : this() { SelectCommand = new SqlCommand(selectCommandText, selectConnection); } private SqlDataAdapter(SqlDataAdapter from) : base(from) { // Clone GC.SuppressFinalize(this); } public new SqlCommand DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = value; } } IDbCommand IDbDataAdapter.DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = (SqlCommand)value; } } public new SqlCommand InsertCommand { get { return _insertCommand; } set { _insertCommand = value; } } IDbCommand IDbDataAdapter.InsertCommand { get { return _insertCommand; } set { _insertCommand = (SqlCommand)value; } } public new SqlCommand SelectCommand { get { return _selectCommand; } set { _selectCommand = value; } } IDbCommand IDbDataAdapter.SelectCommand { get { return _selectCommand; } set { _selectCommand = (SqlCommand)value; } } public new SqlCommand UpdateCommand { get { return _updateCommand; } set { _updateCommand = value; } } IDbCommand IDbDataAdapter.UpdateCommand { get { return _updateCommand; } set { _updateCommand = (SqlCommand)value; } } public override int UpdateBatchSize { get { return _updateBatchSize; } set { if (0 > value) { throw ADP.ArgumentOutOfRange(nameof(UpdateBatchSize)); } _updateBatchSize = value; } } protected override int AddToBatch(IDbCommand command) { int commandIdentifier = _commandSet.CommandCount; _commandSet.Append((SqlCommand)command); return commandIdentifier; } protected override void ClearBatch() { _commandSet.Clear(); } protected override int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); return _commandSet.ExecuteNonQuery(); } protected override IDataParameter GetBatchedParameter(int commandIdentifier, int parameterIndex) { Debug.Assert(commandIdentifier < _commandSet.CommandCount, "commandIdentifier out of range"); Debug.Assert(parameterIndex < _commandSet.GetParameterCount(commandIdentifier), "parameter out of range"); IDataParameter parameter = _commandSet.GetParameter(commandIdentifier, parameterIndex); return parameter; } protected override bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out Exception error) { Debug.Assert(commandIdentifier < _commandSet.CommandCount, "commandIdentifier out of range"); return _commandSet.GetBatchedAffected(commandIdentifier, out recordsAffected, out error); } protected override void InitializeBatching() { _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) { command = InsertCommand; if (null == command) { command = UpdateCommand; if (null == command) { command = DeleteCommand; } } } if (null != command) { _commandSet.Connection = command.Connection; _commandSet.Transaction = command.Transaction; _commandSet.CommandTimeout = command.CommandTimeout; } } protected override void TerminateBatching() { if (null != _commandSet) { _commandSet.Dispose(); _commandSet = null; } } object ICloneable.Clone() { return new SqlDataAdapter(this); } protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new SqlRowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new SqlRowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } public event SqlRowUpdatedEventHandler RowUpdated { add { Events.AddHandler(EventRowUpdated, value); } remove { Events.RemoveHandler(EventRowUpdated, value); } } public event SqlRowUpdatingEventHandler RowUpdating { add { SqlRowUpdatingEventHandler handler = (SqlRowUpdatingEventHandler)Events[EventRowUpdating]; // Prevent someone from registering two different command builders on the adapter by // silently removing the old one. if ((null != handler) && (value.Target is DbCommandBuilder)) { SqlRowUpdatingEventHandler d = (SqlRowUpdatingEventHandler)ADP.FindBuilder(handler); if (null != d) { Events.RemoveHandler(EventRowUpdating, d); } } Events.AddHandler(EventRowUpdating, value); } remove { Events.RemoveHandler(EventRowUpdating, value); } } protected override void OnRowUpdated(RowUpdatedEventArgs value) { SqlRowUpdatedEventHandler handler = (SqlRowUpdatedEventHandler)Events[EventRowUpdated]; if ((null != handler) && (value is SqlRowUpdatedEventArgs)) { handler(this, (SqlRowUpdatedEventArgs)value); } base.OnRowUpdated(value); } protected override void OnRowUpdating(RowUpdatingEventArgs value) { SqlRowUpdatingEventHandler handler = (SqlRowUpdatingEventHandler)Events[EventRowUpdating]; if ((null != handler) && (value is SqlRowUpdatingEventArgs)) { handler(this, (SqlRowUpdatingEventArgs)value); } base.OnRowUpdating(value); } } }
// 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: Create a Memorystream over an UnmanagedMemoryStream ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace System.IO { // Needed for backwards compatibility with V1.x usages of the // ResourceManager, where a MemoryStream is now returned as an // UnmanagedMemoryStream from ResourceReader. internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream { private UnmanagedMemoryStream _unmanagedStream; internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) { _unmanagedStream = stream; } public override bool CanRead { get { return _unmanagedStream.CanRead; } } public override bool CanSeek { get { return _unmanagedStream.CanSeek; } } public override bool CanWrite { get { return _unmanagedStream.CanWrite; } } protected override void Dispose(bool disposing) { try { if (disposing) _unmanagedStream.Dispose(); } finally { base.Dispose(disposing); } } public override void Flush() { _unmanagedStream.Flush(); } public override byte[] GetBuffer() { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); } public override bool TryGetBuffer(out ArraySegment<byte> buffer) { buffer = default(ArraySegment<byte>); return false; } public override int Capacity { get { return (int)_unmanagedStream.Capacity; } set { throw new IOException(SR.IO_FixedCapacity); } } public override long Length { get { return _unmanagedStream.Length; } } public override long Position { get { return _unmanagedStream.Position; } set { _unmanagedStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return _unmanagedStream.Read(buffer, offset, count); } public override int Read(Span<byte> destination) { return _unmanagedStream.Read(destination); } public override int ReadByte() { return _unmanagedStream.ReadByte(); } public override long Seek(long offset, SeekOrigin loc) { return _unmanagedStream.Seek(offset, loc); } public unsafe override byte[] ToArray() { byte[] buffer = new byte[_unmanagedStream.Length]; _unmanagedStream.Read(buffer, 0, (int)_unmanagedStream.Length); return buffer; } public override void Write(byte[] buffer, int offset, int count) { _unmanagedStream.Write(buffer, offset, count); } public override void Write(ReadOnlySpan<byte> source) { _unmanagedStream.Write(source); } public override void WriteByte(byte value) { _unmanagedStream.WriteByte(value); } // Writes this MemoryStream to another stream. public unsafe override void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); byte[] buffer = ToArray(); stream.Write(buffer, 0, buffer.Length); } public override void SetLength(Int64 value) { // This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0. // Now this results in a call to the base which touches the underlying array which is never actually used. // We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity. base.SetLength(value); } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // The parameter checks must be in sync with the base version: if (destination == null) throw new ArgumentNullException(nameof(destination)); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!destination.CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { return _unmanagedStream.FlushAsync(cancellationToken); } public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { return _unmanagedStream.ReadAsync(destination, cancellationToken); } public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken); } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { return _unmanagedStream.WriteAsync(source, cancellationToken); } } // class UnmanagedMemoryStreamWrapper } // namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System.Security.Permissions; using System.Runtime.Serialization; using System.Text; using System; using System.Diagnostics.Contracts; // // Property Default Description // PositiveSign '+' Character used to indicate positive values. // NegativeSign '-' Character used to indicate negative values. // NumberDecimalSeparator '.' The character used as the decimal separator. // NumberGroupSeparator ',' The character used to separate groups of // digits to the left of the decimal point. // NumberDecimalDigits 2 The default number of decimal places. // NumberGroupSizes 3 The number of digits in each group to the // left of the decimal point. // NaNSymbol "NaN" The string used to represent NaN values. // PositiveInfinitySymbol"Infinity" The string used to represent positive // infinities. // NegativeInfinitySymbol"-Infinity" The string used to represent negative // infinities. // // // // Property Default Description // CurrencyDecimalSeparator '.' The character used as the decimal // separator. // CurrencyGroupSeparator ',' The character used to separate groups // of digits to the left of the decimal // point. // CurrencyDecimalDigits 2 The default number of decimal places. // CurrencyGroupSizes 3 The number of digits in each group to // the left of the decimal point. // CurrencyPositivePattern 0 The format of positive values. // CurrencyNegativePattern 0 The format of negative values. // CurrencySymbol "$" String used as local monetary symbol. // [Serializable] [System.Runtime.InteropServices.ComVisible(true)] sealed public partial class NumberFormatInfo : ICloneable, IFormatProvider { // invariantInfo is constant irrespective of your current culture. private static volatile NumberFormatInfo invariantInfo; // READTHIS READTHIS READTHIS // This class has an exact mapping onto a native structure defined in COMNumber.cpp // DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END. // ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets. // READTHIS READTHIS READTHIS internal int[] numberGroupSizes = new int[] {3}; internal int[] currencyGroupSizes = new int[] {3}; internal int[] percentGroupSizes = new int[] {3}; internal String positiveSign = "+"; internal String negativeSign = "-"; internal String numberDecimalSeparator = "."; internal String numberGroupSeparator = ","; internal String currencyGroupSeparator = ","; internal String currencyDecimalSeparator = "."; internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. // The alternative currency symbol used in Win9x ANSI codepage, that can not roundtrip between ANSI and Unicode. // Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash) // NOTE: The only legal values for this string are null and "\x005c" internal String ansiCurrencySymbol = null; internal String nanSymbol = "NaN"; internal String positiveInfinitySymbol = "Infinity"; internal String negativeInfinitySymbol = "-Infinity"; internal String percentDecimalSeparator = "."; internal String percentGroupSeparator = ","; internal String percentSymbol = "%"; internal String perMilleSymbol = "\u2030"; [OptionalField(VersionAdded = 2)] internal String[] nativeDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; // an index which points to a record in Culture Data Table. // We shouldn't be persisting dataItem (since its useless & we weren't using it), // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now. [OptionalField(VersionAdded = 1)] internal int m_dataItem = 0; // NEVER USED, DO NOT USE THIS! (Serialized in Everett) internal int numberDecimalDigits = 2; internal int currencyDecimalDigits = 2; internal int currencyPositivePattern = 0; internal int currencyNegativePattern = 0; internal int numberNegativePattern = 1; internal int percentPositivePattern = 0; internal int percentNegativePattern = 0; internal int percentDecimalDigits = 2; [OptionalField(VersionAdded = 2)] internal int digitSubstitution = 1; // DigitShapes.None internal bool isReadOnly=false; // We shouldn't be persisting m_useUserOverride (since its useless & we weren't using it), // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now. [OptionalField(VersionAdded = 1)] internal bool m_useUserOverride=false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett) // Is this NumberFormatInfo for invariant culture? [OptionalField(VersionAdded = 2)] internal bool m_isInvariant=false; public NumberFormatInfo() : this(null) { } #region Serialization // Check if NumberFormatInfo was not set up ambiguously for parsing as number and currency // eg. if the NumberDecimalSeparator and the NumberGroupSeparator were the same. This check // is solely for backwards compatibility / version tolerant serialization [OptionalField(VersionAdded = 1)] internal bool validForParseAsNumber = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett) [OptionalField(VersionAdded = 1)] internal bool validForParseAsCurrency = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett) [OnSerializing] private void OnSerializing(StreamingContext ctx) { #if !FEATURE_CORECLR // Update these legacy flags, so that 1.1/2.0 versions of the framework // can still throw while parsing; even when using a de-serialized // NumberFormatInfo from a 4.0+ version of the framework if (numberDecimalSeparator != numberGroupSeparator) { validForParseAsNumber = true; } else { validForParseAsNumber = false; } if ((numberDecimalSeparator != numberGroupSeparator) && (numberDecimalSeparator != currencyGroupSeparator) && (currencyDecimalSeparator != numberGroupSeparator) && (currencyDecimalSeparator != currencyGroupSeparator)) { validForParseAsCurrency = true; } else { validForParseAsCurrency = false; } #endif // !FEATURE_CORECLR } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { } #endregion Serialization static private void VerifyDecimalSeparator(String decSep, String propertyName) { if (decSep==null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_String")); } if (decSep.Length==0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyDecString")); } Contract.EndContractBlock(); } static private void VerifyGroupSeparator(String groupSep, String propertyName) { if (groupSep==null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); } static private void VerifyNativeDigits(String [] nativeDig, String propertyName) { if (nativeDig==null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_Array")); } if (nativeDig.Length != 10) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitCount"), propertyName); } Contract.EndContractBlock(); for(int i = 0; i < nativeDig.Length; i++) { if (nativeDig[i] == null) { throw new ArgumentNullException(propertyName, Environment.GetResourceString("ArgumentNull_ArrayValue")); } if (nativeDig[i].Length != 1) { if(nativeDig[i].Length != 2) { // Not 1 or 2 UTF-16 code points throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName); } else if(!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) { // 2 UTF-6 code points, but not a surrogate pair throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName); } } if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i && CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) { // Not the appropriate digit according to the Unicode data properties // (Digit 0 must be a 0, etc.). throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName); } } } static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName) { switch(digitSub) { case DigitShapes.Context: case DigitShapes.None: case DigitShapes.NativeNational: // Success. break; default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDigitSubstitution"), propertyName); } } // We aren't persisting dataItem any more (since its useless & we weren't using it), // Ditto with m_useUserOverride. Don't use them, we use a local copy of everything. [System.Security.SecuritySafeCritical] // auto-generated internal NumberFormatInfo(CultureData cultureData) { if (cultureData != null) { // We directly use fields here since these data is coming from data table or Win32, so we // don't need to verify their values (except for invalid parsing situations). cultureData.GetNFIValues(this); if (cultureData.IsInvariantCulture) { // For invariant culture this.m_isInvariant = true; } } } [Pure] private void VerifyWritable() { if (isReadOnly) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); } Contract.EndContractBlock(); } // Returns a default NumberFormatInfo that will be universally // supported and constant irrespective of the current culture. // Used by FromString methods. // public static NumberFormatInfo InvariantInfo { get { if (invariantInfo == null) { // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. NumberFormatInfo nfi = new NumberFormatInfo(); nfi.m_isInvariant = true; invariantInfo = ReadOnly(nfi); } return invariantInfo; } } public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) { // Fast case for a regular CultureInfo NumberFormatInfo info; CultureInfo cultureProvider = formatProvider as CultureInfo; if (cultureProvider != null && !cultureProvider.m_isInherited) { info = cultureProvider.numInfo; if (info != null) { return info; } else { return cultureProvider.NumberFormat; } } // Fast case for an NFI; info = formatProvider as NumberFormatInfo; if (info != null) { return info; } if (formatProvider != null) { info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo; if (info != null) { return info; } } return CurrentInfo; } public Object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; return n; } public int CurrencyDecimalDigits { get { return currencyDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "CurrencyDecimalDigits", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); currencyDecimalDigits = value; } } public String CurrencyDecimalSeparator { get { return currencyDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "CurrencyDecimalSeparator"); currencyDecimalSeparator = value; } } public bool IsReadOnly { get { return isReadOnly; } } // // Check the values of the groupSize array. // // Every element in the groupSize array should be between 1 and 9 // excpet the last element could be zero. // static internal void CheckGroupSize(String propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { if (groupSize[i] < 1) { if (i == groupSize.Length - 1 && groupSize[i] == 0) return; throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName); } else if (groupSize[i] > 9) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName); } } } public int[] CurrencyGroupSizes { get { return ((int[])currencyGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("CurrencyGroupSizes", Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("CurrencyGroupSizes", inputSizes); currencyGroupSizes = inputSizes; } } public int[] NumberGroupSizes { get { return ((int[])numberGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("NumberGroupSizes", Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("NumberGroupSizes", inputSizes); numberGroupSizes = inputSizes; } } public int[] PercentGroupSizes { get { return ((int[])percentGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("PercentGroupSizes", Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("PercentGroupSizes", inputSizes); percentGroupSizes = inputSizes; } } public String CurrencyGroupSeparator { get { return currencyGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "CurrencyGroupSeparator"); currencyGroupSeparator = value; } } public String CurrencySymbol { get { return currencySymbol; } set { if (value == null) { throw new ArgumentNullException("CurrencySymbol", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); currencySymbol = value; } } // Returns the current culture's NumberFormatInfo. Used by Parse methods. // public static NumberFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture; if (!culture.m_isInherited) { NumberFormatInfo info = culture.numInfo; if (info != null) { return info; } } return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo))); } } public String NaNSymbol { get { return nanSymbol; } set { if (value == null) { throw new ArgumentNullException("NaNSymbol", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); nanSymbol = value; } } public int CurrencyNegativePattern { get { return currencyNegativePattern; } set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException( "CurrencyNegativePattern", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 15)); } Contract.EndContractBlock(); VerifyWritable(); currencyNegativePattern = value; } } public int NumberNegativePattern { get { return numberNegativePattern; } set { // // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException( "NumberNegativePattern", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 4)); } Contract.EndContractBlock(); VerifyWritable(); numberNegativePattern = value; } } public int PercentPositivePattern { get { return percentPositivePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( "PercentPositivePattern", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); percentPositivePattern = value; } } public int PercentNegativePattern { get { return percentNegativePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException( "PercentNegativePattern", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 11)); } Contract.EndContractBlock(); VerifyWritable(); percentNegativePattern = value; } } public String NegativeInfinitySymbol { get { return negativeInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("NegativeInfinitySymbol", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); negativeInfinitySymbol = value; } } public String NegativeSign { get { return negativeSign; } set { if (value == null) { throw new ArgumentNullException("NegativeSign", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); negativeSign = value; } } public int NumberDecimalDigits { get { return numberDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "NumberDecimalDigits", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); numberDecimalDigits = value; } } public String NumberDecimalSeparator { get { return numberDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "NumberDecimalSeparator"); numberDecimalSeparator = value; } } public String NumberGroupSeparator { get { return numberGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "NumberGroupSeparator"); numberGroupSeparator = value; } } public int CurrencyPositivePattern { get { return currencyPositivePattern; } set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( "CurrencyPositivePattern", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); currencyPositivePattern = value; } } public String PositiveInfinitySymbol { get { return positiveInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("PositiveInfinitySymbol", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); positiveInfinitySymbol = value; } } public String PositiveSign { get { return positiveSign; } set { if (value == null) { throw new ArgumentNullException("PositiveSign", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); positiveSign = value; } } public int PercentDecimalDigits { get { return percentDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "PercentDecimalDigits", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); percentDecimalDigits = value; } } public String PercentDecimalSeparator { get { return percentDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "PercentDecimalSeparator"); percentDecimalSeparator = value; } } public String PercentGroupSeparator { get { return percentGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "PercentGroupSeparator"); percentGroupSeparator = value; } } public String PercentSymbol { get { return percentSymbol; } set { if (value == null) { throw new ArgumentNullException("PercentSymbol", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); percentSymbol = value; } } public String PerMilleSymbol { get { return perMilleSymbol; } set { if (value == null) { throw new ArgumentNullException("PerMilleSymbol", Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); perMilleSymbol = value; } } [System.Runtime.InteropServices.ComVisible(false)] public String[] NativeDigits { get { return (String[])nativeDigits.Clone(); } set { VerifyWritable(); VerifyNativeDigits(value, "NativeDigits"); nativeDigits = value; } } [System.Runtime.InteropServices.ComVisible(false)] public DigitShapes DigitSubstitution { get { return (DigitShapes)digitSubstitution; } set { VerifyWritable(); VerifyDigitSubstitution(value, "DigitSubstitution"); digitSubstitution = (int)value; } } public Object GetFormat(Type formatType) { return formatType == typeof(NumberFormatInfo)? this: null; } public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { throw new ArgumentNullException("nfi"); } Contract.EndContractBlock(); if (nfi.IsReadOnly) { return (nfi); } NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone()); info.isReadOnly = true; return info; } // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00); private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style"); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHexStyle")); } } } internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style"); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number throw new ArgumentException(Environment.GetResourceString("Arg_HexStyleNotSupported")); } } } // NumberFormatInfo }
// 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.Globalization; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Threading; namespace System.Net.Mail { internal partial class SmtpConnection { private static readonly ContextCallback s_AuthenticateCallback = new ContextCallback(AuthenticateCallback); private BufferBuilder _bufferBuilder = new BufferBuilder(); private bool _isConnected; private bool _isClosed; private bool _isStreamOpen; private EventHandler _onCloseHandler; internal SmtpTransport _parent; private SmtpClient _client; private NetworkStream _networkStream; internal TcpClient _tcpClient; internal string _host = null; internal int _port = 0; private SmtpReplyReaderFactory _responseReader; private ICredentialsByHost _credentials; private int _timeout = 100000; private string[] _extensions; private ChannelBinding _channelBindingToken = null; private bool _enableSsl; private X509CertificateCollection _clientCertificates; internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost credentials, ISmtpAuthenticationModule[] authenticationModules) { _client = client; _credentials = credentials; _authenticationModules = authenticationModules; _parent = parent; _tcpClient = new TcpClient(); _onCloseHandler = new EventHandler(OnClose); } internal BufferBuilder BufferBuilder => _bufferBuilder; internal bool IsConnected => _isConnected; internal bool IsStreamOpen => _isStreamOpen; internal SmtpReplyReaderFactory Reader => _responseReader; internal bool EnableSsl { get { return _enableSsl; } set { _enableSsl = value; } } internal int Timeout { get { return _timeout; } set { _timeout = value; } } internal X509CertificateCollection ClientCertificates { get { return _clientCertificates; } set { _clientCertificates = value; } } internal void InitializeConnection(string host, int port) { _tcpClient.Connect(host, port); _networkStream = _tcpClient.GetStream(); } internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback callback, object state) { return _tcpClient.BeginConnect(host, port, callback, state); } internal void EndInitializeConnection(IAsyncResult result) { _tcpClient.EndConnect(result); _networkStream = _tcpClient.GetStream(); } internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port) { ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state); result.GetConnection(); return result; } internal IAsyncResult BeginFlush(AsyncCallback callback, object state) { return _networkStream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state); } internal void EndFlush(IAsyncResult result) { _networkStream.EndWrite(result); _bufferBuilder.Reset(); } internal void Flush() { _networkStream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length); _bufferBuilder.Reset(); } internal void ReleaseConnection() { if (!_isClosed) { lock (this) { if (!_isClosed && _tcpClient != null) { //free cbt buffer if (_channelBindingToken != null) { _channelBindingToken.Close(); } _networkStream.Close(); _tcpClient.Dispose(); } _isClosed = true; } } _isConnected = false; } internal void Abort() { if (!_isClosed) { lock (this) { if (!_isClosed && _tcpClient != null) { //free CBT buffer if (_channelBindingToken != null) { _channelBindingToken.Close(); } // must destroy manually since sending a QUIT here might not be // interpreted correctly by the server if it's in the middle of a // DATA command or some similar situation. This may send a RST // but this is ok in this situation. Do not reuse this connection _tcpClient.LingerState = new LingerOption(true, 0); _networkStream.Close(); _tcpClient.Dispose(); } _isClosed = true; } } _isConnected = false; } internal void GetConnection(string host, int port) { if (_isConnected) { throw new InvalidOperationException(SR.SmtpAlreadyConnected); } InitializeConnection(host, port); _responseReader = new SmtpReplyReaderFactory(_networkStream); LineInfo info = _responseReader.GetNextReplyReader().ReadLine(); switch (info.StatusCode) { case SmtpStatusCode.ServiceReady: break; default: throw new SmtpException(info.StatusCode, info.Line, true); } try { _extensions = EHelloCommand.Send(this, _client.clientDomain); ParseExtensions(_extensions); } catch (SmtpException e) { if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized) && (e.StatusCode != SmtpStatusCode.CommandNotImplemented)) { throw e; } HelloCommand.Send(this, _client.clientDomain); //if ehello isn't supported, assume basic login _supportedAuth = SupportedAuth.Login; } if (_enableSsl) { if (!_serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(_networkStream is TlsStream)) { throw new SmtpException(SR.MailServerDoesNotSupportStartTls); } } StartTlsCommand.Send(this); TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates); tlsStream.AuthenticateAsClient(); _networkStream = tlsStream; _responseReader = new SmtpReplyReaderFactory(_networkStream); // According to RFC 3207: The client SHOULD send an EHLO command // as the first command after a successful TLS negotiation. _extensions = EHelloCommand.Send(this, _client.clientDomain); ParseExtensions(_extensions); } // if no credentials were supplied, try anonymous // servers don't appear to anounce that they support anonymous login. if (_credentials != null) { for (int i = 0; i < _authenticationModules.Length; i++) { //only authenticate if the auth protocol is supported - chadmu if (!AuthSupported(_authenticationModules[i])) { continue; } NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType); if (credential == null) continue; Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null); if (auth != null && auth.Message != null) { info = AuthCommand.Send(this, _authenticationModules[i].AuthenticationType, auth.Message); if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented) { continue; } while ((int)info.StatusCode == 334) { auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken); if (auth == null) { throw new SmtpException(SR.SmtpAuthenticationFailed); } info = AuthCommand.Send(this, auth.Message); if ((int)info.StatusCode == 235) { _authenticationModules[i].CloseContext(this); _isConnected = true; return; } } } } } _isConnected = true; } [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)] private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context) { // We may need to restore user thread token here if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials)) { #if DEBUG if (context != null && !context.IdentityRequested) { NetEventSource.Fail(this, "Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)"); } #endif try { ExecutionContext x = context == null ? null : context.ContextCopy; if (x != null) { AuthenticateCallbackContext authenticationContext = new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken); ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext); return authenticationContext._result; } else { return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken); } } catch { // Prevent the impersonation from leaking to upstack exception filters. throw; } } return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken); } private static void AuthenticateCallback(object state) { AuthenticateCallbackContext context = (AuthenticateCallbackContext)state; context._result = context._module.Authenticate(null, context._credential, context._thisPtr, context._spn, context._token); } private class AuthenticateCallbackContext { internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string spn, ChannelBinding Token) { _thisPtr = thisPtr; _module = module; _credential = credential; _spn = spn; _token = Token; _result = null; } internal readonly SmtpConnection _thisPtr; internal readonly ISmtpAuthenticationModule _module; internal readonly NetworkCredential _credential; internal readonly string _spn; internal readonly ChannelBinding _token; internal Authorization _result; } internal void EndGetConnection(IAsyncResult result) { ConnectAndHandshakeAsyncResult.End(result); } internal Stream GetClosableStream() { ClosableStream cs = new ClosableStream(_networkStream, _onCloseHandler); _isStreamOpen = true; return cs; } private void OnClose(object sender, EventArgs args) { _isStreamOpen = false; DataStopCommand.Send(this); } private class ConnectAndHandshakeAsyncResult : LazyAsyncResult { private string _authResponse; private SmtpConnection _connection; private int _currentModule = -1; private int _port; private static AsyncCallback s_handshakeCallback = new AsyncCallback(HandshakeCallback); private static AsyncCallback s_sendEHelloCallback = new AsyncCallback(SendEHelloCallback); private static AsyncCallback s_sendHelloCallback = new AsyncCallback(SendHelloCallback); private static AsyncCallback s_authenticateCallback = new AsyncCallback(AuthenticateCallback); private static AsyncCallback s_authenticateContinueCallback = new AsyncCallback(AuthenticateContinueCallback); private string _host; private readonly ContextAwareResult _outerResult; internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) : base(null, state, callback) { _connection = connection; _host = host; _port = port; _outerResult = outerResult; } private static void ConnectionCreatedCallback(object request, object state) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, request); ConnectAndHandshakeAsyncResult ConnectAndHandshakeAsyncResult = (ConnectAndHandshakeAsyncResult)request; if (state is Exception) { ConnectAndHandshakeAsyncResult.InvokeCallback((Exception)state); return; } try { lock (ConnectAndHandshakeAsyncResult._connection) { //if we were cancelled while getting the connection, we should close and return if (ConnectAndHandshakeAsyncResult._connection._isClosed) { ConnectAndHandshakeAsyncResult._connection.ReleaseConnection(); if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect was aborted: {request}"); ConnectAndHandshakeAsyncResult.InvokeCallback(null); return; } } ConnectAndHandshakeAsyncResult.Handshake(); } catch (Exception e) { ConnectAndHandshakeAsyncResult.InvokeCallback(e); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, request); } internal static void End(IAsyncResult result) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result; object connectResult = thisPtr.InternalWaitForCompletion(); if (connectResult is Exception) { throw (Exception)connectResult; } } internal void GetConnection() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (_connection._isConnected) { throw new InvalidOperationException(SR.SmtpAlreadyConnected); } InitializeConnection(); } private void InitializeConnection() { IAsyncResult result = _connection.BeginInitializeConnection(_host, _port, InitializeConnectionCallback, this); if (result.CompletedSynchronously) { _connection.EndInitializeConnection(result); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Connect returned"); try { Handshake(); } catch (Exception e) { InvokeCallback(e); } } } private static void InitializeConnectionCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; thisPtr._connection.EndInitializeConnection(result); if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Connect returned {thisPtr}"); try { thisPtr.Handshake(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private void Handshake() { _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream); SmtpReplyReader reader = _connection.Reader.GetNextReplyReader(); IAsyncResult result = reader.BeginReadLine(s_handshakeCallback, this); if (!result.CompletedSynchronously) { return; } LineInfo info = reader.EndReadLine(result); if (info.StatusCode != SmtpStatusCode.ServiceReady) { throw new SmtpException(info.StatusCode, info.Line, true); } try { if (!SendEHello()) { return; } } catch { if (!SendHello()) { return; } } } private static void HandshakeCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { try { LineInfo info = thisPtr._connection.Reader.CurrentReader.EndReadLine(result); if (info.StatusCode != SmtpStatusCode.ServiceReady) { thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true)); return; } if (!thisPtr.SendEHello()) { return; } } catch (SmtpException) { if (!thisPtr.SendHello()) { return; } } } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool SendEHello() { IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendEHelloCallback, this); if (result.CompletedSynchronously) { _connection._extensions = EHelloCommand.EndSend(result); _connection.ParseExtensions(_connection._extensions); // If we already have a TlsStream, this is the second EHLO cmd // that we sent after TLS handshake compelted. So skip TLS and // continue with Authenticate. if (_connection._networkStream is TlsStream) { Authenticate(); return true; } if (_connection.EnableSsl) { if (!_connection._serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(_connection._networkStream is TlsStream)) { throw new SmtpException(SR.Format(SR.MailServerDoesNotSupportStartTls)); } } SendStartTls(); } else { Authenticate(); } return true; } return false; } private static void SendEHelloCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { try { thisPtr._connection._extensions = EHelloCommand.EndSend(result); thisPtr._connection.ParseExtensions(thisPtr._connection._extensions); // If we already have a SSlStream, this is the second EHLO cmd // that we sent after TLS handshake compelted. So skip TLS and // continue with Authenticate. if (thisPtr._connection._networkStream is TlsStream) { thisPtr.Authenticate(); return; } } catch (SmtpException e) { if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized) && (e.StatusCode != SmtpStatusCode.CommandNotImplemented)) { throw e; } if (!thisPtr.SendHello()) { return; } } if (thisPtr._connection.EnableSsl) { if (!thisPtr._connection._serverSupportsStartTls) { // Either TLS is already established or server does not support TLS if (!(thisPtr._connection._networkStream is TlsStream)) { throw new SmtpException(SR.MailServerDoesNotSupportStartTls); } } thisPtr.SendStartTls(); } else { thisPtr.Authenticate(); } } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool SendHello() { IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendHelloCallback, this); //if ehello isn't supported, assume basic auth if (result.CompletedSynchronously) { _connection._supportedAuth = SupportedAuth.Login; HelloCommand.EndSend(result); Authenticate(); return true; } return false; } private static void SendHelloCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { HelloCommand.EndSend(result); thisPtr.Authenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool SendStartTls() { IAsyncResult result = StartTlsCommand.BeginSend(_connection, SendStartTlsCallback, this); if (result.CompletedSynchronously) { StartTlsCommand.EndSend(result); TlsStreamAuthenticate(); return true; } return false; } private static void SendStartTlsCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { StartTlsCommand.EndSend(result); thisPtr.TlsStreamAuthenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool TlsStreamAuthenticate() { _connection._networkStream = new TlsStream(_connection._networkStream, _connection._tcpClient.Client, _host, _connection._clientCertificates); IAsyncResult result = (_connection._networkStream as TlsStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this); if (result.CompletedSynchronously) { (_connection._networkStream as TlsStream).EndAuthenticateAsClient(result); _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream); SendEHello(); return true; } return false; } private static void TlsStreamAuthenticateCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { (thisPtr._connection._networkStream as TlsStream).EndAuthenticateAsClient(result); thisPtr._connection._responseReader = new SmtpReplyReaderFactory(thisPtr._connection._networkStream); thisPtr.SendEHello(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private void Authenticate() { //if no credentials were supplied, try anonymous //servers don't appear to anounce that they support anonymous login. if (_connection._credentials != null) { while (++_currentModule < _connection._authenticationModules.Length) { //only authenticate if the auth protocol is supported ISmtpAuthenticationModule module = _connection._authenticationModules[_currentModule]; if (!_connection.AuthSupported(module)) { continue; } NetworkCredential credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType); if (credential == null) continue; Authorization auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult); if (auth != null && auth.Message != null) { IAsyncResult result = AuthCommand.BeginSend(_connection, _connection._authenticationModules[_currentModule].AuthenticationType, auth.Message, s_authenticateCallback, this); if (!result.CompletedSynchronously) { return; } LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 334) { _authResponse = info.Line; if (!AuthenticateContinue()) { return; } } else if ((int)info.StatusCode == 235) { module.CloseContext(_connection); _connection._isConnected = true; break; } } } } _connection._isConnected = true; InvokeCallback(); } private static void AuthenticateCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 334) { thisPtr._authResponse = info.Line; if (!thisPtr.AuthenticateContinue()) { return; } } else if ((int)info.StatusCode == 235) { thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection); thisPtr._connection._isConnected = true; thisPtr.InvokeCallback(); return; } thisPtr.Authenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } private bool AuthenticateContinue() { for (;;) { // We don't need credential on the continued auth assuming they were captured on the first call. // That should always work, otherwise what if a new credential has been returned? Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken); if (auth == null) { throw new SmtpException(SR.Format(SR.SmtpAuthenticationFailed)); } IAsyncResult result = AuthCommand.BeginSend(_connection, auth.Message, s_authenticateContinueCallback, this); if (!result.CompletedSynchronously) { return false; } LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 235) { _connection._authenticationModules[_currentModule].CloseContext(_connection); _connection._isConnected = true; InvokeCallback(); return false; } else if ((int)info.StatusCode != 334) { return true; } _authResponse = info.Line; } } private static void AuthenticateContinueCallback(IAsyncResult result) { if (!result.CompletedSynchronously) { ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState; try { LineInfo info = AuthCommand.EndSend(result); if ((int)info.StatusCode == 235) { thisPtr._connection._authenticationModules[thisPtr._currentModule].CloseContext(thisPtr._connection); thisPtr._connection._isConnected = true; thisPtr.InvokeCallback(); return; } else if ((int)info.StatusCode == 334) { thisPtr._authResponse = info.Line; if (!thisPtr.AuthenticateContinue()) { return; } } thisPtr.Authenticate(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Votter.Services.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xrm.Sdk.Query; using Microsoft.Xrm.Sdk; using System.Collections; using System.Linq.Expressions; #if DLAB_UNROOT_NAMESPACE || DLAB_XRM namespace DLaB.Xrm #else namespace Source.DLaB.Xrm #endif { public static partial class Extensions { #region FilterExpression /// <summary> /// Adds an In Condition to the FilterExpression /// </summary> /// <param name="filterExpression">The FilterExpression to apply the In Constraints to.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">An IEnumerable of values to search for being in the column name.</param> public static FilterExpression WhereIn(this FilterExpression filterExpression, string columnName, IEnumerable values) { // Since value type arrays are not covariant in C#, they will not be converted to an object[] if passed // into this method, but instead a single object of type array. Manually convert this to an object array AddWhereInCondition(filterExpression, columnName, values.Cast<object>().ToArray()); return filterExpression; } /// <summary> /// Adds an In Condition to the FilterExpression /// </summary> /// <param name="filterExpression">The FilterExpression to apply the In Constraints to.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> public static FilterExpression WhereIn(this FilterExpression filterExpression, string columnName, params object[] values) { if (values.Length == 1){ var type = values[0].GetType(); var eNum = values[0] as IEnumerable; if (type.Name != "String" && eNum != null) { return filterExpression.WhereIn(columnName, eNum); } } AddWhereInCondition(filterExpression, columnName, values); return filterExpression; } /// <summary> /// Adds an In Condition to the FilterExpression. Since a string is also IEnumerable, this method is required /// to wrap the string in to an object array for the correct method overloading resolution /// </summary> /// <param name="filterExpression">The FilterExpression to apply the In Constraints to.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="value">The single value to search for being in the column name.</param> public static FilterExpression WhereIn(this FilterExpression filterExpression, string columnName, string value) { AddWhereInCondition(filterExpression, columnName, new object[] {value}); return filterExpression; } /// <summary> /// /// </summary> /// <param name="filterExpression">The FilterExpression to apply the In Constraints to.</param> /// <param name="columnName"></param> /// <param name="values"></param> private static void AddWhereInCondition(FilterExpression filterExpression, string columnName, object[] values) { if(values.Length == 0){ // If no values are in our values array, create a constraint which causing nothing to get returned // ReSharper disable once InconsistentNaming var ANDing = new FilterExpression(LogicalOperator.And); ANDing.AddCondition(columnName, ConditionOperator.Null); ANDing.AddCondition(columnName, ConditionOperator.NotNull); filterExpression.AddFilter(ANDing); } else if (values.Any(v => v == null)) { if (values.Any(v => v != null)) { // ReSharper disable once InconsistentNaming var ORing = new FilterExpression(LogicalOperator.Or); ORing.AddCondition(columnName, ConditionOperator.Null); ORing.AddCondition(columnName, ConditionOperator.In, values.Where(v => v != null)); filterExpression.AddFilter(ORing); } else { filterExpression.AddCondition(columnName, ConditionOperator.Null); } } else { filterExpression.AddCondition(columnName, ConditionOperator.In, values); } } #endregion FilterExpression #region IOrganizationService #region GetAllEntitiesIn /// <summary> /// Gets all Active Entities where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static IEnumerable<T> GetAllEntitiesIn<T>(this IOrganizationService service, string columnName, IEnumerable values) where T : Entity { return RetrieveAllEntities<T>.GetAllEntities(service, QueryExpressionFactory.CreateIn<T>(columnName, values)); } /// <summary> /// Gets all Active Entities where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static IEnumerable<T> GetAllEntitiesIn<T>(this IOrganizationService service, string columnName, params object[] values) where T : Entity { return RetrieveAllEntities<T>.GetAllEntities(service, QueryExpressionFactory.CreateIn<T>(columnName, values)); } /// <summary> /// Gets all Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous /// type are the column names to add.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static IEnumerable<T> GetAllEntitiesIn<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer, string columnName, IEnumerable values) where T : Entity { var columnSet = AddColumns(new ColumnSet(), anonymousTypeInitializer); return service.GetAllEntitiesIn<T>(columnSet, columnName, values); } /// <summary> /// Gets all Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static IEnumerable<T> GetAllEntitiesIn<T>(this IOrganizationService service, ColumnSet columnSet, string columnName, IEnumerable values) where T : Entity { return RetrieveAllEntities<T>.GetAllEntities(service, QueryExpressionFactory.CreateIn<T>(columnSet, columnName, values)); } /// <summary> /// Gets all Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous /// type are the column names to add.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static IEnumerable<T> GetAllEntitiesIn<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer, string columnName, params object[] values) where T : Entity { var columnSet = AddColumns(new ColumnSet(), anonymousTypeInitializer); return service.GetAllEntitiesIn<T>(columnSet, columnName, values); } /// <summary> /// Gets all Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static IEnumerable<T> GetAllEntitiesIn<T>(this IOrganizationService service, ColumnSet columnSet, string columnName, params object[] values) where T : Entity { return RetrieveAllEntities<T>.GetAllEntities(service, QueryExpressionFactory.CreateIn<T>(columnSet, columnName, values)); } #endregion GetAllEntitiesIn #region GetEntitiesIn /// <summary> /// Gets first 5000 Active Entities where the values are in the columnName /// </summary> /// <param name="service"></param> /// <param name="logicalName">The LogicalName of the Entity to query.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<Entity> GetEntitiesIn(this IOrganizationService service, string logicalName, string columnName, IEnumerable values) { var settings = new LateBoundQuerySettings(logicalName); return service.RetrieveMultiple(settings.CreateInExpression(columnName, values)).Entities.ToList(); } /// <summary> /// Gets first 5000 Active Entities where the values are in the columnName /// </summary> /// <param name="service"></param> /// <param name="logicalName">The LogicalName of the Entity to query.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<Entity> GetEntitiesIn(this IOrganizationService service, string logicalName, string columnName, params object[] values) { var settings = new LateBoundQuerySettings(logicalName); return service.RetrieveMultiple(settings.CreateInExpression(columnName, values)).Entities.ToList(); } /// <summary> /// Gets first 5000 Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <param name="service"></param> /// <param name="logicalName">The LogicalName of the Entity to query.</param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<Entity> GetEntitiesIn(this IOrganizationService service, string logicalName, ColumnSet columnSet, string columnName, IEnumerable values) { var settings = new LateBoundQuerySettings(logicalName) { Columns = columnSet, }; return service.RetrieveMultiple(settings.CreateInExpression(columnName, values)).Entities.ToList(); } /// <summary> /// Gets first 5000 Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <param name="service"></param> /// <param name="logicalName">The LogicalName of the Entity to query.</param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<Entity> GetEntitiesIn(this IOrganizationService service, string logicalName, ColumnSet columnSet, string columnName, params object[] values) { var settings = new LateBoundQuerySettings(logicalName) { Columns = columnSet, }; return service.RetrieveMultiple(settings.CreateInExpression(columnName, values)).Entities.ToList(); } #endregion GetEntitiesIn #region GetEntitiesIn<T> /// <summary> /// Gets first 5000 Active Entities where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<T> GetEntitiesIn<T>(this IOrganizationService service, string columnName, IEnumerable values) where T : Entity { return service.GetEntities(QueryExpressionFactory.CreateIn<T>(columnName, values)); } /// <summary> /// Gets first 5000 Active Entities where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<T> GetEntitiesIn<T>(this IOrganizationService service, string columnName, params object[] values) where T : Entity { return service.GetEntities(QueryExpressionFactory.CreateIn<T>(columnName, values)); } /// <summary> /// Gets first 5000 Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous /// type are the column names to add.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<T> GetEntitiesIn<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer, string columnName, IEnumerable values) where T : Entity { var columnSet = AddColumns(new ColumnSet(), anonymousTypeInitializer); return service.GetEntitiesIn<T>(columnSet, columnName, values); } /// <summary> /// Gets first 5000 Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<T> GetEntitiesIn<T>(this IOrganizationService service, ColumnSet columnSet, string columnName, IEnumerable values) where T : Entity { return service.GetEntities(QueryExpressionFactory.CreateIn<T>(columnSet, columnName, values)); } /// <summary> /// Gets first 5000 Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous /// type are the column names to add.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<T> GetEntitiesIn<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer, string columnName, params object[] values) where T : Entity { var columnSet = AddColumns(new ColumnSet(), anonymousTypeInitializer); return service.GetEntitiesIn<T>(columnSet, columnName, values); } /// <summary> /// Gets first 5000 Active Entities (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">Type of Entity List to return.</typeparam> /// <param name="service"></param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static List<T> GetEntitiesIn<T>(this IOrganizationService service, ColumnSet columnSet, string columnName, params object[] values) where T : Entity { return service.GetEntities(QueryExpressionFactory.CreateIn<T>(columnSet, columnName, values)); } #endregion GetEntitiesIn<T> #region GetFirstOrDefaultIn /// <summary> /// Retrieves the first active entity (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">An early bound Entity Type.</typeparam> /// <param name="service"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static T GetFirstOrDefaultIn<T>(this IOrganizationService service, string columnName, IEnumerable values) where T : Entity { var settings = new QuerySettings<T> { First = true }; return service.GetEntities<T>(settings.CreateInExpression(columnName, values)).FirstOrDefault(); } /// <summary> /// Retrieves the first active entity (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">An early bound Entity Type.</typeparam> /// <param name="service"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static T GetFirstOrDefaultIn<T>(this IOrganizationService service, string columnName, params object[] values) where T : Entity { var settings = new QuerySettings<T> { First = true }; return service.GetEntities<T>(settings.CreateInExpression(columnName, values)).FirstOrDefault(); } /// <summary> /// Retrieves the first active entity (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">An early bound Entity Type.</typeparam> /// <param name="service"></param> /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous /// type are the column names to add.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static T GetFirstOrDefaultIn<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer, string columnName, IEnumerable values) where T : Entity { var columnSet = AddColumns(new ColumnSet(), anonymousTypeInitializer); return service.GetFirstOrDefaultIn<T>(columnSet, columnName, values); } /// <summary> /// Retrieves the first active entity (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">An early bound Entity Type.</typeparam> /// <param name="service"></param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static T GetFirstOrDefaultIn<T>(this IOrganizationService service, ColumnSet columnSet, string columnName, IEnumerable values) where T : Entity { var settings = new QuerySettings<T> { Columns = columnSet, First = true }; return service.GetEntities<T>(settings.CreateInExpression(columnName, values)).FirstOrDefault(); } /// <summary> /// Retrieves the first active entity (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">An early bound Entity Type</typeparam> /// <param name="service"></param> /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous /// type are the column names to add.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static T GetFirstOrDefaultIn<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer, string columnName, params object[] values) where T : Entity { var columnSet = AddColumns(new ColumnSet(), anonymousTypeInitializer); return service.GetFirstOrDefaultIn<T>(columnSet, columnName, values); } /// <summary> /// Retrieves the first active entity (with the given subset of columns only) /// where the values are in the columnName /// </summary> /// <typeparam name="T">An early bound Entity Type</typeparam> /// <param name="service"></param> /// <param name="columnSet">Columns to Return.</param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> /// <returns></returns> public static T GetFirstOrDefaultIn<T>(this IOrganizationService service, ColumnSet columnSet, string columnName, params object[] values) where T : Entity { var settings = new QuerySettings<T> { Columns = columnSet, First = true }; return service.GetEntities<T>(settings.CreateInExpression(columnName, values)).FirstOrDefault(); } #endregion GetFirstOrDefaultIn #endregion IOrganizationService #region LinkEntity /// <summary> /// Adds an In Condition to the LinkEntity LinkCriteria /// </summary> /// <param name="linkEntity"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> public static LinkEntity WhereIn(this LinkEntity linkEntity, string columnName, IEnumerable values) { linkEntity.LinkCriteria.WhereIn(columnName, new Object[]{values}); return linkEntity; } /// <summary> /// Adds an In Condition to the LinkEntity LinkCriteria /// </summary> /// <param name="linkEntity"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> public static LinkEntity WhereIn(this LinkEntity linkEntity, string columnName, params object[] values) { linkEntity.LinkCriteria.WhereIn(columnName, values); return linkEntity; } #endregion LinkEntity #region QueryExpression /// <summary> /// Adds an In Condition to the QueryExpression Criteria /// </summary> /// <param name="query"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> public static QueryExpression WhereIn(this QueryExpression query, string columnName, IEnumerable values) { query.Criteria.WhereIn(columnName, values); return query; } /// <summary> /// Adds an In Condition to the QueryExpression Criteria /// </summary> /// <param name="query"></param> /// <param name="columnName">The name of the column to perform the in against.</param> /// <param name="values">The list of values to search for being in the column name.</param> public static QueryExpression WhereIn(this QueryExpression query, string columnName, params object[] values) { query.Criteria.WhereIn(columnName, values); return query; } #endregion QueryExpression } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D10_City (editable child object).<br/> /// This is a generated base class of <see cref="D10_City"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="D11_CityRoadObjects"/> of type <see cref="D11_CityRoadColl"/> (1:M relation to <see cref="D12_CityRoad"/>)<br/> /// This class is an item of <see cref="D09_CityColl"/> collection. /// </remarks> [Serializable] public partial class D10_City : BusinessBase<D10_City> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_ID"/> property. /// </summary> public static readonly PropertyInfo<int> City_IDProperty = RegisterProperty<int>(p => p.City_ID, "Cities ID"); /// <summary> /// Gets the Cities ID. /// </summary> /// <value>The Cities ID.</value> public int City_ID { get { return GetProperty(City_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="City_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_NameProperty = RegisterProperty<string>(p => p.City_Name, "Cities Name"); /// <summary> /// Gets or sets the Cities Name. /// </summary> /// <value>The Cities Name.</value> public string City_Name { get { return GetProperty(City_NameProperty); } set { SetProperty(City_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="D11_City_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<D11_City_Child> D11_City_SingleObjectProperty = RegisterProperty<D11_City_Child>(p => p.D11_City_SingleObject, "D11 City Single Object", RelationshipTypes.Child); /// <summary> /// Gets the D11 City Single Object ("self load" child property). /// </summary> /// <value>The D11 City Single Object.</value> public D11_City_Child D11_City_SingleObject { get { return GetProperty(D11_City_SingleObjectProperty); } private set { LoadProperty(D11_City_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="D11_City_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<D11_City_ReChild> D11_City_ASingleObjectProperty = RegisterProperty<D11_City_ReChild>(p => p.D11_City_ASingleObject, "D11 City ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the D11 City ASingle Object ("self load" child property). /// </summary> /// <value>The D11 City ASingle Object.</value> public D11_City_ReChild D11_City_ASingleObject { get { return GetProperty(D11_City_ASingleObjectProperty); } private set { LoadProperty(D11_City_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="D11_CityRoadObjects"/> property. /// </summary> public static readonly PropertyInfo<D11_CityRoadColl> D11_CityRoadObjectsProperty = RegisterProperty<D11_CityRoadColl>(p => p.D11_CityRoadObjects, "D11 CityRoad Objects", RelationshipTypes.Child); /// <summary> /// Gets the D11 City Road Objects ("self load" child property). /// </summary> /// <value>The D11 City Road Objects.</value> public D11_CityRoadColl D11_CityRoadObjects { get { return GetProperty(D11_CityRoadObjectsProperty); } private set { LoadProperty(D11_CityRoadObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D10_City"/> object. /// </summary> /// <returns>A reference to the created <see cref="D10_City"/> object.</returns> internal static D10_City NewD10_City() { return DataPortal.CreateChild<D10_City>(); } /// <summary> /// Factory method. Loads a <see cref="D10_City"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="D10_City"/> object.</returns> internal static D10_City GetD10_City(SafeDataReader dr) { D10_City obj = new D10_City(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D10_City"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D10_City() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D10_City"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(City_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(D11_City_SingleObjectProperty, DataPortal.CreateChild<D11_City_Child>()); LoadProperty(D11_City_ASingleObjectProperty, DataPortal.CreateChild<D11_City_ReChild>()); LoadProperty(D11_CityRoadObjectsProperty, DataPortal.CreateChild<D11_CityRoadColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D10_City"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_IDProperty, dr.GetInt32("City_ID")); LoadProperty(City_NameProperty, dr.GetString("City_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(D11_City_SingleObjectProperty, D11_City_Child.GetD11_City_Child(City_ID)); LoadProperty(D11_City_ASingleObjectProperty, D11_City_ReChild.GetD11_City_ReChild(City_ID)); LoadProperty(D11_CityRoadObjectsProperty, D11_CityRoadColl.GetD11_CityRoadColl(City_ID)); } /// <summary> /// Inserts a new <see cref="D10_City"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D08_Region parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddD10_City", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_Region_ID", parent.Region_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@City_Name", ReadProperty(City_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(City_IDProperty, (int) cmd.Parameters["@City_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="D10_City"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateD10_City", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Name", ReadProperty(City_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="D10_City"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteD10_City", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(D11_City_SingleObjectProperty, DataPortal.CreateChild<D11_City_Child>()); LoadProperty(D11_City_ASingleObjectProperty, DataPortal.CreateChild<D11_City_ReChild>()); LoadProperty(D11_CityRoadObjectsProperty, DataPortal.CreateChild<D11_CityRoadColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; using System.Windows.Forms; /// <summary> /// Version: 1.3.0 /// ------------------------------------------------------------------------- /// Simon Pucher 2016 /// ------------------------------------------------------------------------- /// todo /// + if markets are closed no OnCalculate() is called so we need an timer event. /// ------------------------------------------------------------------------- /// Adds instruments dynamical to a static list (e.g. portfolio) if the market is currently open. /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this indicator without any error you also need access to the utility indicator to use these global source code elements. /// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { [Description("Adds instruments dynamical to a static list (e.g. portfolio) if the market is currently open.")] public class DynamicListMarkets_Indicator_Tool : UserIndicator { #region Variables private bool _usemarkethours = true; private string _instrumentlists = "DAX30;ATX20;DOW30;NASDAQ;S&P500"; private static DateTime _lastupdate = DateTime.Now; private int _seconds = 60; private string _name_of_list = String.Empty; private IInstrumentsList _list = null; #endregion protected override void OnInit() { IsOverlay = true; CalculateOnClosedBar = false; } protected override void OnStart() { this.CheckForNewInstruments(); } protected override void OnCalculate() { this.CheckForNewInstruments(); } private void CheckForNewInstruments() { if (_lastupdate.AddSeconds(this._seconds) < DateTime.Now) { if (!String.IsNullOrEmpty(Name_of_list)) { this.Root.Core.InstrumentManager.GetInstrumentLists(); _list = this.Root.Core.InstrumentManager.GetInstrumentsListStatic(this.Name_of_list); if (_list == null || _list.Count == 0) { Log(this.DisplayName + ": The list " + this.Name_of_list + " does not exist.", InfoLogLevel.Warning); } } else { Log(this.DisplayName + ": You need to specify a name for the list.", InfoLogLevel.Warning); } if (_list != null) { //this.Root.Core.InstrumentManager.ClearInstrumentList(this.Name_of_list); Core.GuiManager.BeginInvoke((Action)(() => this.Root.Core.InstrumentManager.ClearInstrumentList(this.Name_of_list))); } if (!String.IsNullOrWhiteSpace(this.Instrumentlists)) { string[] arr_Instrumentlists = this.Instrumentlists.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (arr_Instrumentlists != null && arr_Instrumentlists.Count() > 0) { foreach (string item in arr_Instrumentlists) { IInstrumentsList instlist = this.Root.Core.InstrumentManager.GetInstrumentsListStatic(item); if (instlist != null && instlist.Count() > 0) { if (UseMarketHours) { ITimePeriod timper = this.Root.Core.MarketplaceManager.GetExchangeDescription(instlist.First().Exchange).TradingHours; if ((DateTime.Now.TimeOfDay > timper.StartTime) && (DateTime.Now.TimeOfDay < timper.EndTime)) { foreach (IInstrument inst in instlist) { if (!_list.Contains(inst)) { //this.Root.Core.InstrumentManager.AddInstrument2List(inst, this.Name_of_list); Core.GuiManager.BeginInvoke((Action)(() => Core.InstrumentManager.AddInstrument2List(inst, this.Name_of_list))); } } } } else { foreach (IInstrument inst in instlist) { if (!_list.Contains(inst)) { //this.Root.Core.InstrumentManager.AddInstrument2List(inst, this.Name_of_list); Core.GuiManager.BeginInvoke((Action)(() => Core.InstrumentManager.AddInstrument2List(inst, this.Name_of_list))); } } } } } } } _lastupdate = DateTime.Now; } } public override string DisplayName { get { return "DLM (T)"; } } public override string ToString() { return "DLM (T)"; } #region Properties #region InSeries [Description("The name of the static list to which you would like to add the instruments.")] [InputParameter] [DisplayName("Static list")] public string Name_of_list { get { return _name_of_list; } set { _name_of_list = value; } } [Description("If true then all markets with active trading session will be added to the static list.")] [InputParameter] [DisplayName("Use market hours")] public bool UseMarketHours { get { return _usemarkethours; } set { _usemarkethours = value; } } [Description("All of these markets will be added automatically to your list if if the market is currently open.")] [InputParameter] [DisplayName("Markets")] public string Instrumentlists { get { return _instrumentlists; } set { _instrumentlists = value; } } [Description("Update interval in seconds.")] [InputParameter] [DisplayName("Update interval (sec.)")] public int Seconds { get { return _seconds; } set { _seconds = value; } } #endregion #endregion } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; #if FEATURE_SERIALIZABLE_EXCEPTIONS using System.Runtime.Serialization; #endif namespace Lucene.Net.Util { /* * 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 DirectAllocator = Lucene.Net.Util.ByteBlockPool.DirectAllocator; /// <summary> /// <see cref="BytesRefHash"/> is a special purpose hash-map like data-structure /// optimized for <see cref="BytesRef"/> instances. <see cref="BytesRefHash"/> maintains mappings of /// byte arrays to ids (Map&lt;BytesRef,int&gt;) storing the hashed bytes /// efficiently in continuous storage. The mapping to the id is /// encapsulated inside <see cref="BytesRefHash"/> and is guaranteed to be increased /// for each added <see cref="BytesRef"/>. /// /// <para> /// Note: The maximum capacity <see cref="BytesRef"/> instance passed to /// <see cref="Add(BytesRef)"/> must not be longer than <see cref="ByteBlockPool.BYTE_BLOCK_SIZE"/>-2. /// The internal storage is limited to 2GB total byte storage. /// </para> /// /// @lucene.internal /// </summary> public sealed class BytesRefHash : IDisposable // LUCENENET specific: Implemented IDisposable to enable usage of the using statement { public const int DEFAULT_CAPACITY = 16; // the following fields are needed by comparer, // so package private to prevent access$-methods: internal readonly ByteBlockPool pool; internal int[] bytesStart; private readonly BytesRef scratch1 = new BytesRef(); private int hashSize; private int hashHalfSize; private int hashMask; private int count; private int lastCount = -1; private int[] ids; private readonly BytesStartArray bytesStartArray; private Counter bytesUsed; /// <summary> /// Creates a new <see cref="BytesRefHash"/> with a <see cref="ByteBlockPool"/> using a /// <see cref="DirectAllocator"/>. /// </summary> public BytesRefHash() : this(new ByteBlockPool(new DirectAllocator())) { } /// <summary> /// Creates a new <see cref="BytesRefHash"/> /// </summary> public BytesRefHash(ByteBlockPool pool) : this(pool, DEFAULT_CAPACITY, new DirectBytesStartArray(DEFAULT_CAPACITY)) { } /// <summary> /// Creates a new <see cref="BytesRefHash"/> /// </summary> public BytesRefHash(ByteBlockPool pool, int capacity, BytesStartArray bytesStartArray) { hashSize = capacity; hashHalfSize = hashSize >> 1; hashMask = hashSize - 1; this.pool = pool; ids = new int[hashSize]; Arrays.Fill(ids, -1); this.bytesStartArray = bytesStartArray; bytesStart = bytesStartArray.Init(); bytesUsed = bytesStartArray.BytesUsed() == null ? Counter.NewCounter() : bytesStartArray.BytesUsed(); bytesUsed.AddAndGet(hashSize * RamUsageEstimator.NUM_BYTES_INT32); } /// <summary> /// Returns the number of <see cref="BytesRef"/> values in this <see cref="BytesRefHash"/>. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> /// <returns> The number of <see cref="BytesRef"/> values in this <see cref="BytesRefHash"/>. </returns> public int Count { get { return count; } } /// <summary> /// Populates and returns a <see cref="BytesRef"/> with the bytes for the given /// bytesID. /// <para/> /// Note: the given bytesID must be a positive integer less than the current /// size (<see cref="Count"/>) /// </summary> /// <param name="bytesID"> /// The id </param> /// <param name="ref"> /// The <see cref="BytesRef"/> to populate /// </param> /// <returns> The given <see cref="BytesRef"/> instance populated with the bytes for the given /// bytesID </returns> public BytesRef Get(int bytesID, BytesRef @ref) { Debug.Assert(bytesStart != null, "bytesStart is null - not initialized"); Debug.Assert(bytesID < bytesStart.Length, "bytesID exceeds byteStart len: " + bytesStart.Length); pool.SetBytesRef(@ref, bytesStart[bytesID]); return @ref; } /// <summary> /// Returns the ids array in arbitrary order. Valid ids start at offset of 0 /// and end at a limit of <see cref="Count"/> - 1 /// <para> /// Note: this is a destructive operation. <see cref="Clear()"/> must be called in /// order to reuse this <see cref="BytesRefHash"/> instance. /// </para> /// </summary> public int[] Compact() { Debug.Assert(bytesStart != null, "bytesStart is null - not initialized"); int upto = 0; for (int i = 0; i < hashSize; i++) { if (ids[i] != -1) { if (upto < i) { ids[upto] = ids[i]; ids[i] = -1; } upto++; } } Debug.Assert(upto == count); lastCount = count; return ids; } /// <summary> /// Returns the values array sorted by the referenced byte values. /// <para> /// Note: this is a destructive operation. <see cref="Clear()"/> must be called in /// order to reuse this <see cref="BytesRefHash"/> instance. /// </para> /// </summary> /// <param name="comp"> /// The <see cref="T:IComparer{BytesRef}"/> used for sorting </param> public int[] Sort(IComparer<BytesRef> comp) { int[] compact = Compact(); new IntroSorterAnonymousInnerClassHelper(this, comp, compact).Sort(0, count); return compact; } private class IntroSorterAnonymousInnerClassHelper : IntroSorter { private BytesRefHash outerInstance; private IComparer<BytesRef> comp; private int[] compact; private readonly BytesRef pivot = new BytesRef(), scratch1 = new BytesRef(), scratch2 = new BytesRef(); public IntroSorterAnonymousInnerClassHelper(BytesRefHash outerInstance, IComparer<BytesRef> comp, int[] compact) { this.outerInstance = outerInstance; this.comp = comp; this.compact = compact; } protected override void Swap(int i, int j) { int o = compact[i]; compact[i] = compact[j]; compact[j] = o; } protected override int Compare(int i, int j) { int id1 = compact[i], id2 = compact[j]; Debug.Assert(outerInstance.bytesStart.Length > id1 && outerInstance.bytesStart.Length > id2); outerInstance.pool.SetBytesRef(outerInstance.scratch1, outerInstance.bytesStart[id1]); outerInstance.pool.SetBytesRef(scratch2, outerInstance.bytesStart[id2]); return comp.Compare(outerInstance.scratch1, scratch2); } protected override void SetPivot(int i) { int id = compact[i]; Debug.Assert(outerInstance.bytesStart.Length > id); outerInstance.pool.SetBytesRef(pivot, outerInstance.bytesStart[id]); } protected override int ComparePivot(int j) { int id = compact[j]; Debug.Assert(outerInstance.bytesStart.Length > id); outerInstance.pool.SetBytesRef(scratch2, outerInstance.bytesStart[id]); return comp.Compare(pivot, scratch2); } } private bool Equals(int id, BytesRef b) { pool.SetBytesRef(scratch1, bytesStart[id]); return scratch1.BytesEquals(b); } private bool Shrink(int targetSize) { // Cannot use ArrayUtil.shrink because we require power // of 2: int newSize = hashSize; while (newSize >= 8 && newSize / 4 > targetSize) { newSize /= 2; } if (newSize != hashSize) { bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * -(hashSize - newSize)); hashSize = newSize; ids = new int[hashSize]; Arrays.Fill(ids, -1); hashHalfSize = newSize / 2; hashMask = newSize - 1; return true; } else { return false; } } /// <summary> /// Clears the <see cref="BytesRef"/> which maps to the given <see cref="BytesRef"/> /// </summary> public void Clear(bool resetPool) { lastCount = count; count = 0; if (resetPool) { pool.Reset(false, false); // we don't need to 0-fill the buffers } bytesStart = bytesStartArray.Clear(); if (lastCount != -1 && Shrink(lastCount)) { // shrink clears the hash entries return; } Arrays.Fill(ids, -1); } public void Clear() { Clear(true); } /// <summary> /// Closes the <see cref="BytesRefHash"/> and releases all internally used memory /// </summary> public void Dispose() { Clear(true); ids = null; bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * -hashSize); } /// <summary> /// Adds a new <see cref="BytesRef"/> /// </summary> /// <param name="bytes"> /// The bytes to hash </param> /// <returns> The id the given bytes are hashed if there was no mapping for the /// given bytes, otherwise <c>(-(id)-1)</c>. this guarantees /// that the return value will always be &gt;= 0 if the given bytes /// haven't been hashed before. /// </returns> /// <exception cref="MaxBytesLengthExceededException"> /// if the given bytes are > 2 + /// <see cref="ByteBlockPool.BYTE_BLOCK_SIZE"/> </exception> public int Add(BytesRef bytes) { Debug.Assert(bytesStart != null, "Bytesstart is null - not initialized"); int length = bytes.Length; // final position int hashPos = FindHash(bytes); int e = ids[hashPos]; if (e == -1) { // new entry int len2 = 2 + bytes.Length; if (len2 + pool.ByteUpto > ByteBlockPool.BYTE_BLOCK_SIZE) { if (len2 > ByteBlockPool.BYTE_BLOCK_SIZE) { throw new MaxBytesLengthExceededException("bytes can be at most " + (ByteBlockPool.BYTE_BLOCK_SIZE - 2) + " in length; got " + bytes.Length); } pool.NextBuffer(); } var buffer = pool.Buffer; int bufferUpto = pool.ByteUpto; if (count >= bytesStart.Length) { bytesStart = bytesStartArray.Grow(); Debug.Assert(count < bytesStart.Length + 1, "count: " + count + " len: " + bytesStart.Length); } e = count++; bytesStart[e] = bufferUpto + pool.ByteOffset; // We first encode the length, followed by the // bytes. Length is encoded as vInt, but will consume // 1 or 2 bytes at most (we reject too-long terms, // above). if (length < 128) { // 1 byte to store length buffer[bufferUpto] = (byte)length; pool.ByteUpto += length + 1; Debug.Assert(length >= 0, "Length must be positive: " + length); System.Buffer.BlockCopy(bytes.Bytes, bytes.Offset, buffer, bufferUpto + 1, length); } else { // 2 byte to store length buffer[bufferUpto] = (byte)(0x80 | (length & 0x7f)); buffer[bufferUpto + 1] = (byte)((length >> 7) & 0xff); pool.ByteUpto += length + 2; System.Buffer.BlockCopy(bytes.Bytes, bytes.Offset, buffer, bufferUpto + 2, length); } Debug.Assert(ids[hashPos] == -1); ids[hashPos] = e; if (count == hashHalfSize) { Rehash(2 * hashSize, true); } return e; } return -(e + 1); } /// <summary> /// Returns the id of the given <see cref="BytesRef"/>. /// </summary> /// <param name="bytes"> /// The bytes to look for /// </param> /// <returns> The id of the given bytes, or <c>-1</c> if there is no mapping for the /// given bytes. </returns> public int Find(BytesRef bytes) { return ids[FindHash(bytes)]; } private int FindHash(BytesRef bytes) { Debug.Assert(bytesStart != null, "bytesStart is null - not initialized"); int code = DoHash(bytes.Bytes, bytes.Offset, bytes.Length); // final position int hashPos = code & hashMask; int e = ids[hashPos]; if (e != -1 && !Equals(e, bytes)) { // Conflict; use linear probe to find an open slot // (see LUCENE-5604): do { code++; hashPos = code & hashMask; e = ids[hashPos]; } while (e != -1 && !Equals(e, bytes)); } return hashPos; } /// <summary> /// Adds a "arbitrary" int offset instead of a <see cref="BytesRef"/> /// term. This is used in the indexer to hold the hash for term /// vectors, because they do not redundantly store the <see cref="T:byte[]"/> term /// directly and instead reference the <see cref="T:byte[]"/> term /// already stored by the postings <see cref="BytesRefHash"/>. See /// <see cref="Index.TermsHashPerField.Add(int)"/>. /// </summary> public int AddByPoolOffset(int offset) { Debug.Assert(bytesStart != null, "Bytesstart is null - not initialized"); // final position int code = offset; int hashPos = offset & hashMask; int e = ids[hashPos]; if (e != -1 && bytesStart[e] != offset) { // Conflict; use linear probe to find an open slot // (see LUCENE-5604): do { code++; hashPos = code & hashMask; e = ids[hashPos]; } while (e != -1 && bytesStart[e] != offset); } if (e == -1) { // new entry if (count >= bytesStart.Length) { bytesStart = bytesStartArray.Grow(); Debug.Assert(count < bytesStart.Length + 1, "count: " + count + " len: " + bytesStart.Length); } e = count++; bytesStart[e] = offset; Debug.Assert(ids[hashPos] == -1); ids[hashPos] = e; if (count == hashHalfSize) { Rehash(2 * hashSize, false); } return e; } return -(e + 1); } /// <summary> /// Called when hash is too small (&gt; 50% occupied) or too large (&lt; 20% /// occupied). /// </summary> private void Rehash(int newSize, bool hashOnData) { int newMask = newSize - 1; bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * (newSize)); int[] newHash = new int[newSize]; Arrays.Fill(newHash, -1); for (int i = 0; i < hashSize; i++) { int e0 = ids[i]; if (e0 != -1) { int code; if (hashOnData) { int off = bytesStart[e0]; int start = off & ByteBlockPool.BYTE_BLOCK_MASK; var bytes = pool.Buffers[off >> ByteBlockPool.BYTE_BLOCK_SHIFT]; int len; int pos; if ((bytes[start] & 0x80) == 0) { // length is 1 byte len = bytes[start]; pos = start + 1; } else { len = (bytes[start] & 0x7f) + ((bytes[start + 1] & 0xff) << 7); pos = start + 2; } code = DoHash(bytes, pos, len); } else { code = bytesStart[e0]; } int hashPos = code & newMask; Debug.Assert(hashPos >= 0); if (newHash[hashPos] != -1) { // Conflict; use linear probe to find an open slot // (see LUCENE-5604): do { code++; hashPos = code & newMask; } while (newHash[hashPos] != -1); } newHash[hashPos] = e0; } } hashMask = newMask; bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * (-ids.Length)); ids = newHash; hashSize = newSize; hashHalfSize = newSize / 2; } // TODO: maybe use long? But our keys are typically short... private static int DoHash(byte[] bytes, int offset, int length) { return StringHelper.Murmurhash3_x86_32(bytes, offset, length, StringHelper.GOOD_FAST_HASH_SEED); } /// <summary> /// Reinitializes the <see cref="BytesRefHash"/> after a previous <see cref="Clear()"/> /// call. If <see cref="Clear()"/> has not been called previously this method has no /// effect. /// </summary> public void Reinit() { if (bytesStart == null) { bytesStart = bytesStartArray.Init(); } if (ids == null) { ids = new int[hashSize]; bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * hashSize); } } /// <summary> /// Returns the bytesStart offset into the internally used /// <see cref="ByteBlockPool"/> for the given <paramref name="bytesID"/> /// </summary> /// <param name="bytesID"> /// The id to look up </param> /// <returns> The bytesStart offset into the internally used /// <see cref="ByteBlockPool"/> for the given id </returns> public int ByteStart(int bytesID) { Debug.Assert(bytesStart != null, "bytesStart is null - not initialized"); Debug.Assert(bytesID >= 0 && bytesID < count, bytesID.ToString()); return bytesStart[bytesID]; } /// <summary> /// Thrown if a <see cref="BytesRef"/> exceeds the <see cref="BytesRefHash"/> limit of /// <see cref="ByteBlockPool.BYTE_BLOCK_SIZE"/>-2. /// </summary> // LUCENENET: It is no longer good practice to use binary serialization. // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 #if FEATURE_SERIALIZABLE_EXCEPTIONS [Serializable] #endif public class MaxBytesLengthExceededException : Exception { internal MaxBytesLengthExceededException(string message) : base(message) { } #if FEATURE_SERIALIZABLE_EXCEPTIONS /// <summary> /// Initializes a new instance of this class with serialized data. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param> public MaxBytesLengthExceededException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// Manages allocation of the per-term addresses. </summary> public abstract class BytesStartArray { /// <summary> /// Initializes the <see cref="BytesStartArray"/>. This call will allocate memory. /// </summary> /// <returns> The initialized bytes start array. </returns> public abstract int[] Init(); /// <summary> /// Grows the <see cref="BytesStartArray"/>. /// </summary> /// <returns> The grown array. </returns> public abstract int[] Grow(); /// <summary> /// Clears the <see cref="BytesStartArray"/> and returns the cleared instance. /// </summary> /// <returns> The cleared instance, this might be <c>null</c>. </returns> public abstract int[] Clear(); /// <summary> /// A <see cref="Counter"/> reference holding the number of bytes used by this /// <see cref="BytesStartArray"/>. The <see cref="BytesRefHash"/> uses this reference to /// track it memory usage. /// </summary> /// <returns> a <see cref="AtomicInt64"/> reference holding the number of bytes used /// by this <see cref="BytesStartArray"/>. </returns> public abstract Counter BytesUsed(); } /// <summary> /// A simple <see cref="BytesStartArray"/> that tracks /// memory allocation using a private <see cref="Counter"/> /// instance. /// </summary> public class DirectBytesStartArray : BytesStartArray { // TODO: can't we just merge this w/ // TrackingDirectBytesStartArray...? Just add a ctor // that makes a private bytesUsed? protected readonly int m_initSize; internal int[] bytesStart; internal readonly Counter bytesUsed; public DirectBytesStartArray(int initSize, Counter counter) { this.bytesUsed = counter; this.m_initSize = initSize; } public DirectBytesStartArray(int initSize) : this(initSize, Counter.NewCounter()) { } public override int[] Clear() { return bytesStart = null; } public override int[] Grow() { Debug.Assert(bytesStart != null); return bytesStart = ArrayUtil.Grow(bytesStart, bytesStart.Length + 1); } public override int[] Init() { return bytesStart = new int[ArrayUtil.Oversize(m_initSize, RamUsageEstimator.NUM_BYTES_INT32)]; } public override Counter BytesUsed() { return bytesUsed; } } } }
/* * 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.Reflection; using System.Threading; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Hypergrid; using OpenMetaverse; using OpenMetaverse.Packets; using log4net; using Nini.Config; using Mono.Addins; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.CoreModules.Framework.UserManagement { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserManagementModule")] public class UserManagementModule : ISharedRegionModule, IUserManagement, IPeople { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled; protected List<Scene> m_Scenes = new List<Scene>(); protected IServiceThrottleModule m_ServiceThrottle; // The cache protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>(); #region ISharedRegionModule public void Initialise(IConfigSource config) { string umanmod = config.Configs["Modules"].GetString("UserManagementModule", Name); if (umanmod == Name) { m_Enabled = true; Init(); m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name); } } public bool IsSharedModule { get { return true; } } public virtual string Name { get { return "BasicUserManagementModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (m_Enabled) { m_Scenes.Add(scene); scene.RegisterModuleInterface<IUserManagement>(this); scene.RegisterModuleInterface<IPeople>(this); scene.EventManager.OnNewClient += new EventManager.OnNewClientDelegate(EventManager_OnNewClient); scene.EventManager.OnPrimsLoaded += new EventManager.PrimsLoaded(EventManager_OnPrimsLoaded); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserManagement>(this); m_Scenes.Remove(scene); } } public void RegionLoaded(Scene s) { if (m_Enabled && m_ServiceThrottle == null) m_ServiceThrottle = s.RequestModuleInterface<IServiceThrottleModule>(); } public void PostInitialise() { } public void Close() { m_Scenes.Clear(); lock (m_UserCache) m_UserCache.Clear(); } #endregion ISharedRegionModule #region Event Handlers void EventManager_OnPrimsLoaded(Scene s) { // let's sniff all the user names referenced by objects in the scene m_log.DebugFormat("[USER MANAGEMENT MODULE]: Caching creators' data from {0} ({1} objects)...", s.RegionInfo.RegionName, s.GetEntities().Length); s.ForEachSOG(delegate(SceneObjectGroup sog) { CacheCreators(sog); }); } void EventManager_OnNewClient(IClientAPI client) { client.OnConnectionClosed += new Action<IClientAPI>(HandleConnectionClosed); client.OnNameFromUUIDRequest += new UUIDNameRequest(HandleUUIDNameRequest); client.OnAvatarPickerRequest += new AvatarPickerRequest(HandleAvatarPickerRequest); } void HandleConnectionClosed(IClientAPI client) { client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest); client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest); } void HandleUUIDNameRequest(UUID uuid, IClientAPI client) { // m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: Handling request for name binding of UUID {0} from {1}", // uuid, remote_client.Name); if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid)) { client.SendNameReply(uuid, "Mr", "OpenSim"); } else { string[] names = new string[2]; if (TryGetUserNamesFromCache(uuid, names)) { client.SendNameReply(uuid, names[0], names[1]); return; } // Not found in cache, queue continuation m_ServiceThrottle.Enqueue("name", uuid.ToString(), delegate { //m_log.DebugFormat("[YYY]: Name request {0}", uuid); // As least upto September 2013, clients permanently cache UUID -> Name bindings. Some clients // appear to clear this when the user asks it to clear the cache, but others may not. // // So to avoid clients // (particularly Hypergrid clients) permanently binding "Unknown User" to a given UUID, we will // instead drop the request entirely. if (TryGetUserNames(uuid, names)) client.SendNameReply(uuid, names[0], names[1]); // else // m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: No bound name for {0} found, ignoring request from {1}", // uuid, client.Name); }); } } public void HandleAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query) { //EventManager.TriggerAvatarPickerRequest(); m_log.DebugFormat("[USER MANAGEMENT MODULE]: HandleAvatarPickerRequest for {0}", query); List<UserData> users = GetUserData(query, 500, 1); AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); // TODO: don't create new blocks if recycling an old packet AvatarPickerReplyPacket.DataBlock[] searchData = new AvatarPickerReplyPacket.DataBlock[users.Count]; AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock(); agentData.AgentID = avatarID; agentData.QueryID = RequestID; replyPacket.AgentData = agentData; //byte[] bytes = new byte[AvatarResponses.Count*32]; int i = 0; foreach (UserData item in users) { UUID translatedIDtem = item.Id; searchData[i] = new AvatarPickerReplyPacket.DataBlock(); searchData[i].AvatarID = translatedIDtem; searchData[i].FirstName = Utils.StringToBytes((string)item.FirstName); searchData[i].LastName = Utils.StringToBytes((string)item.LastName); i++; } if (users.Count == 0) { searchData = new AvatarPickerReplyPacket.DataBlock[0]; } replyPacket.Data = searchData; AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs(); agent_data.AgentID = replyPacket.AgentData.AgentID; agent_data.QueryID = replyPacket.AgentData.QueryID; List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>(); for (i = 0; i < replyPacket.Data.Length; i++) { AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs(); data_arg.AvatarID = replyPacket.Data[i].AvatarID; data_arg.FirstName = replyPacket.Data[i].FirstName; data_arg.LastName = replyPacket.Data[i].LastName; data_args.Add(data_arg); } client.SendAvatarPickerReply(agent_data, data_args); } protected virtual void AddAdditionalUsers(string query, List<UserData> users) { } #endregion Event Handlers #region IPeople public List<UserData> GetUserData(string query, int page_size, int page_number) { // search the user accounts service List<UserAccount> accs = m_Scenes[0].UserAccountService.GetUserAccounts(m_Scenes[0].RegionInfo.ScopeID, query); List<UserData> users = new List<UserData>(); if (accs != null) { foreach (UserAccount acc in accs) { UserData ud = new UserData(); ud.FirstName = acc.FirstName; ud.LastName = acc.LastName; ud.Id = acc.PrincipalID; users.Add(ud); } } // search the local cache lock (m_UserCache) { foreach (UserData data in m_UserCache.Values) { if (users.Find(delegate(UserData d) { return d.Id == data.Id; }) == null && (data.FirstName.ToLower().StartsWith(query.ToLower()) || data.LastName.ToLower().StartsWith(query.ToLower()))) users.Add(data); } } AddAdditionalUsers(query, users); return users; } #endregion IPeople private void CacheCreators(SceneObjectGroup sog) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: processing {0} {1}; {2}", sog.RootPart.Name, sog.RootPart.CreatorData, sog.RootPart.CreatorIdentification); AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData); foreach (SceneObjectPart sop in sog.Parts) { AddUser(sop.CreatorID, sop.CreatorData); foreach (TaskInventoryItem item in sop.TaskInventory.Values) AddUser(item.CreatorID, item.CreatorData); } } /// <summary> /// /// </summary> /// <param name="uuid"></param> /// <param name="names">Caller please provide a properly instantiated array for names, string[2]</param> /// <returns></returns> private bool TryGetUserNames(UUID uuid, string[] names) { if (names == null) names = new string[2]; if (TryGetUserNamesFromCache(uuid, names)) return true; if (TryGetUserNamesFromServices(uuid, names)) return true; return false; } private bool TryGetUserNamesFromCache(UUID uuid, string[] names) { lock (m_UserCache) { if (m_UserCache.ContainsKey(uuid)) { names[0] = m_UserCache[uuid].FirstName; names[1] = m_UserCache[uuid].LastName; return true; } } return false; } /// <summary> /// Try to get the names bound to the given uuid, from the services. /// </summary> /// <returns>True if the name was found, false if not.</returns> /// <param name='uuid'></param> /// <param name='names'>The array of names if found. If not found, then names[0] = "Unknown" and names[1] = "User"</param> private bool TryGetUserNamesFromServices(UUID uuid, string[] names) { UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, uuid); if (account != null) { names[0] = account.FirstName; names[1] = account.LastName; UserData user = new UserData(); user.FirstName = account.FirstName; user.LastName = account.LastName; lock (m_UserCache) m_UserCache[uuid] = user; return true; } else { // Let's try the GridUser service GridUserInfo uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString()); if (uInfo != null) { string url, first, last, tmp; UUID u; if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp)) { AddUser(uuid, first, last, url); if (m_UserCache.ContainsKey(uuid)) { names[0] = m_UserCache[uuid].FirstName; names[1] = m_UserCache[uuid].LastName; return true; } } else m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID); } else { m_log.DebugFormat("[USER MANAGEMENT MODULE]: No grid user found for {0}", uuid); } names[0] = "Unknown"; names[1] = "UserUMMTGUN9"; return false; } } #region IUserManagement public UUID GetUserIdByName(string name) { string[] parts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) throw new Exception("Name must have 2 components"); return GetUserIdByName(parts[0], parts[1]); } public UUID GetUserIdByName(string firstName, string lastName) { // TODO: Optimize for reverse lookup if this gets used by non-console commands. lock (m_UserCache) { foreach (UserData user in m_UserCache.Values) { if (user.FirstName == firstName && user.LastName == lastName) return user.Id; } } UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); if (account != null) return account.PrincipalID; return UUID.Zero; } public string GetUserName(UUID uuid) { string[] names = new string[2]; TryGetUserNames(uuid, names); return names[0] + " " + names[1]; } public string GetUserHomeURL(UUID userID) { lock (m_UserCache) { if (m_UserCache.ContainsKey(userID)) return m_UserCache[userID].HomeURL; } return string.Empty; } public string GetUserServerURL(UUID userID, string serverType) { UserData userdata; lock (m_UserCache) m_UserCache.TryGetValue(userID, out userdata); if (userdata != null) { // m_log.DebugFormat("[USER MANAGEMENT MODULE]: Requested url type {0} for {1}", serverType, userID); if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null) { return userdata.ServerURLs[serverType].ToString(); } if (!string.IsNullOrEmpty(userdata.HomeURL)) { //m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: Did not find url type {0} so requesting urls from '{1}' for {2}", // serverType, userdata.HomeURL, userID); UserAgentServiceConnector uConn = new UserAgentServiceConnector(userdata.HomeURL); userdata.ServerURLs = uConn.GetServerURLs(userID); if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null) return userdata.ServerURLs[serverType].ToString(); } } return string.Empty; } public string GetUserUUI(UUID userID) { UserData ud; lock (m_UserCache) m_UserCache.TryGetValue(userID, out ud); if (ud == null) // It's not in the cache { string[] names = new string[2]; // This will pull the data from either UserAccounts or GridUser // and stick it into the cache TryGetUserNamesFromServices(userID, names); lock (m_UserCache) m_UserCache.TryGetValue(userID, out ud); } if (ud != null) { string homeURL = ud.HomeURL; string first = ud.FirstName, last = ud.LastName; if (ud.LastName.StartsWith("@")) { string[] parts = ud.FirstName.Split('.'); if (parts.Length >= 2) { first = parts[0]; last = parts[1]; } return userID + ";" + homeURL + ";" + first + " " + last; } } return userID.ToString(); } public void AddUser(UUID uuid, string first, string last) { lock (m_UserCache) { if (m_UserCache.ContainsKey(uuid)) return; } UserData user = new UserData(); user.Id = uuid; user.FirstName = first; user.LastName = last; AddUserInternal(user); } public void AddUser(UUID uuid, string first, string last, string homeURL) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, first {1}, last {2}, url {3}", uuid, first, last, homeURL); if (homeURL == string.Empty) return; AddUser(uuid, homeURL + ";" + first + " " + last); } public void AddUser(UUID id, string creatorData) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData); UserData oldUser; lock (m_UserCache) m_UserCache.TryGetValue(id, out oldUser); if (oldUser != null) { if (string.IsNullOrEmpty(creatorData)) { //ignore updates without creator data return; } //try update unknown users, but don't update anyone else if (oldUser.FirstName == "Unknown" && !creatorData.Contains("Unknown")) { lock (m_UserCache) m_UserCache.Remove(id); m_log.DebugFormat("[USER MANAGEMENT MODULE]: Re-adding user with id {0}, creatorData [{1}] and old HomeURL {2}", id, creatorData, oldUser.HomeURL); } else { //we have already a valid user within the cache return; } } UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, id); if (account != null) { AddUser(id, account.FirstName, account.LastName); } else { UserData user = new UserData(); user.Id = id; if (!string.IsNullOrEmpty(creatorData)) { //creatorData = <endpoint>;<name> string[] parts = creatorData.Split(';'); if (parts.Length >= 1) { user.HomeURL = parts[0]; try { Uri uri = new Uri(parts[0]); user.LastName = "@" + uri.Authority; } catch (UriFormatException) { m_log.DebugFormat("[SCENE]: Unable to parse Uri {0}", parts[0]); user.LastName = "@unknown"; } } if (parts.Length >= 2) user.FirstName = parts[1].Replace(' ', '.'); } else { // Temporarily add unknown user entries of this type into the cache so that we can distinguish // this source from other recent (hopefully resolved) bugs that fail to retrieve a user name binding // TODO: Can be removed when GUN* unknown users have definitely dropped significantly or // disappeared. user.FirstName = "Unknown"; user.LastName = "UserUMMAU4"; } AddUserInternal(user); } } void AddUserInternal(UserData user) { lock (m_UserCache) m_UserCache[user.Id] = user; //m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: Added user {0} {1} {2} {3}", // user.Id, user.FirstName, user.LastName, user.HomeURL); } public bool IsLocalGridUser(UUID uuid) { UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid); if (account == null || (account != null && !account.LocalToGrid)) return false; return true; } #endregion IUserManagement protected void Init() { AddUser(UUID.Zero, "Unknown", "User"); RegisterConsoleCmds(); } protected void RegisterConsoleCmds() { MainConsole.Instance.Commands.AddCommand("Users", true, "show name", "show name <uuid>", "Show the bindings between a single user UUID and a user name", String.Empty, HandleShowUser); MainConsole.Instance.Commands.AddCommand("Users", true, "show names", "show names", "Show the bindings between user UUIDs and user names", String.Empty, HandleShowUsers); } private void HandleShowUser(string module, string[] cmd) { if (cmd.Length < 3) { MainConsole.Instance.OutputFormat("Usage: show name <uuid>"); return; } UUID userId; if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, cmd[2], out userId)) return; string[] names; UserData ud; lock (m_UserCache) { if (!m_UserCache.TryGetValue(userId, out ud)) { MainConsole.Instance.OutputFormat("No name known for user with id {0}", userId); return; } } ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("UUID", 36); cdt.AddColumn("Name", 30); cdt.AddColumn("HomeURL", 40); cdt.AddRow(userId, string.Format("{0} {1}", ud.FirstName, ud.LastName), ud.HomeURL); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowUsers(string module, string[] cmd) { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("UUID", 36); cdt.AddColumn("Name", 30); cdt.AddColumn("HomeURL", 40); lock (m_UserCache) { foreach (KeyValuePair<UUID, UserData> kvp in m_UserCache) cdt.AddRow(kvp.Key, string.Format("{0} {1}", kvp.Value.FirstName, kvp.Value.LastName), kvp.Value.HomeURL); } MainConsole.Instance.Output(cdt.ToString()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.AzureStack.Management.Fabric.Admin { using Microsoft.AzureStack; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Fabric; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; 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> /// LogicalNetworksOperations operations. /// </summary> internal partial class LogicalNetworksOperations : IServiceOperations<FabricAdminClient>, ILogicalNetworksOperations { /// <summary> /// Initializes a new instance of the LogicalNetworksOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LogicalNetworksOperations(FabricAdminClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FabricAdminClient /// </summary> public FabricAdminClient Client { get; private set; } /// <summary> /// Get a logical network. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='logicalNetwork'> /// Name of the logical network. /// </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<LogicalNetwork>> GetWithHttpMessagesAsync(string location, string logicalNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (logicalNetwork == null) { throw new ValidationException(ValidationRules.CannotBeNull, "logicalNetwork"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("logicalNetwork", logicalNetwork); 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/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/logicalNetworks/{logicalNetwork}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{logicalNetwork}", System.Uri.EscapeDataString(logicalNetwork)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new 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<LogicalNetwork>(); _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<LogicalNetwork>(_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> /// Get a list of all logical networks at a location. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the 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<LogicalNetwork>>> ListWithHttpMessagesAsync(string location, ODataQuery<LogicalNetwork> odataQuery = default(ODataQuery<LogicalNetwork>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); 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/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/logicalNetworks").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new 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<LogicalNetwork>>(); _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<LogicalNetwork>>(_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> /// Get a list of all logical networks at a location. /// </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<LogicalNetwork>>> 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 HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new 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<LogicalNetwork>>(); _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<LogicalNetwork>>(_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; } } }
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if UNITY_EDITOR namespace InControl.ReorderableList { using System.Collections.Generic; using Internal; using UnityEditor; using UnityEngine; /// <summary> /// Utility class for drawing reorderable lists. /// </summary> public static class ReorderableListGUI { /// <summary> /// Default list item height is 18 pixels. /// </summary> public const float DefaultItemHeight = 18; /// <summary> /// Gets or sets zero-based index of last item which was changed. A value of -1 /// indicates that no item was changed by list. /// </summary> /// <remarks> /// <para>This property should not be set when items are added or removed.</para> /// </remarks> public static int indexOfChangedItem { get; internal set; } /// <summary> /// Gets zero-based index of list item which is currently being drawn; /// or a value of -1 if no item is currently being drawn. /// </summary> public static int currentItemIndex { get { return ReorderableListControl.currentItemIndex; } } #region Basic Item Drawers /// <summary> /// Default list item drawer implementation. /// </summary> /// <remarks> /// <para>Always presents the label "Item drawer not implemented.".</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Unmodified value of list item. /// </returns> /// <typeparam name="T">Type of list item.</typeparam> public static T DefaultItemDrawer<T>( Rect position, T item ) { GUI.Label( position, "Item drawer not implemented." ); return item; } /// <summary> /// Draws text field allowing list items to be edited. /// </summary> /// <remarks> /// <para>Null values are automatically changed to empty strings since null /// values cannot be edited using a text field.</para> /// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item /// is modified.</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Modified value of list item. /// </returns> public static string TextFieldItemDrawer( Rect position, string item ) { if (item == null) { item = ""; GUI.changed = true; } return EditorGUI.TextField( position, item ); } #endregion /// <summary> /// Gets the default list control implementation. /// </summary> private static ReorderableListControl defaultListControl { get; set; } static ReorderableListGUI() { InitStyles(); defaultListControl = new ReorderableListControl(); // Duplicate default styles to prevent user scripts from interferring with // the default list control instance. defaultListControl.containerStyle = new GUIStyle( defaultContainerStyle ); defaultListControl.addButtonStyle = new GUIStyle( defaultAddButtonStyle ); defaultListControl.removeButtonStyle = new GUIStyle( defaultRemoveButtonStyle ); indexOfChangedItem = -1; } #region Custom Styles /// <summary> /// Gets default style for title header. /// </summary> public static GUIStyle defaultTitleStyle { get; private set; } /// <summary> /// Gets default style for background of list control. /// </summary> public static GUIStyle defaultContainerStyle { get; private set; } /// <summary> /// Gets default style for add item button. /// </summary> public static GUIStyle defaultAddButtonStyle { get; private set; } /// <summary> /// Gets default style for remove item button. /// </summary> public static GUIStyle defaultRemoveButtonStyle { get; private set; } private static void InitStyles() { //defaultTitleStyle = new GUIStyle(); //defaultTitleStyle.border = new RectOffset( 2, 2, 2, 1 ); //defaultTitleStyle.margin = new RectOffset( 5, 5, 5, 0 ); //defaultTitleStyle.padding = new RectOffset( 5, 5, 0, 0 ); //defaultTitleStyle.alignment = TextAnchor.MiddleLeft; //defaultTitleStyle.normal.background = ReorderableListResources.texTitleBackground; //defaultTitleStyle.normal.textColor = EditorGUIUtility.isProSkin // ? new Color( 0.8f, 0.8f, 0.8f ) // : new Color( 0.0f, 0.0f, 0.0f ); defaultTitleStyle = new GUIStyle( InControl.Internal.EditorUtility.titleStyle ); //defaultContainerStyle = new GUIStyle(); //defaultContainerStyle.border = new RectOffset( 2, 2, 1, 2 ); //defaultContainerStyle.margin = new RectOffset( 5, 5, 5, 5 ); //defaultContainerStyle.padding = new RectOffset( 1, 1, 2, 2 ); //defaultContainerStyle.normal.background = ReorderableListResources.texContainerBackground; defaultContainerStyle = new GUIStyle( InControl.Internal.EditorUtility.groupStyle ); defaultContainerStyle.padding = new RectOffset( 1, 1, 2, 2 ); defaultAddButtonStyle = new GUIStyle(); defaultAddButtonStyle.fixedWidth = 30; defaultAddButtonStyle.fixedHeight = 16; defaultAddButtonStyle.normal.background = ReorderableListResources.texAddButton; defaultAddButtonStyle.active.background = ReorderableListResources.texAddButtonActive; defaultRemoveButtonStyle = new GUIStyle(); defaultRemoveButtonStyle.fixedWidth = 27; defaultRemoveButtonStyle.active.background = ReorderableListResources.CreatePixelTexture( "Dark Pixel (List GUI)", new Color32( 18, 18, 18, 255 ) ); defaultRemoveButtonStyle.imagePosition = ImagePosition.ImageOnly; defaultRemoveButtonStyle.alignment = TextAnchor.MiddleCenter; } #endregion private static GUIContent s_Temp = new GUIContent(); #region Title Control /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Content for title control.</param> public static void Title( GUIContent title ) { Rect position = GUILayoutUtility.GetRect( title, defaultTitleStyle ); position.height += 6; Title( position, title ); } /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title("Your Title"); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title('Your Title'); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Text for title control.</param> public static void Title( string title ) { s_Temp.text = title; Title( s_Temp ); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="title">Content for title control.</param> public static void Title( Rect position, GUIContent title ) { if (Event.current.type == EventType.Repaint) defaultTitleStyle.Draw( position, title, false, false, false, false ); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="text">Text for title control.</param> public static void Title( Rect position, string text ) { s_Temp.text = text; Title( position, s_Temp ); } #endregion #region List<T> Control /// <summary> /// Draw list field control. /// </summary> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags ) { var adaptor = new GenericListAdaptor<T>( list, drawItem, itemHeight ); ReorderableListControl.DrawControlFromState( adaptor, drawEmpty, flags ); } /// <summary> /// Draw list field control with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags ) { var adaptor = new GenericListAdaptor<T>( list, drawItem, itemHeight ); ReorderableListControl.DrawControlFromState( position, adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, drawEmpty, itemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, itemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight ) { DoListField<T>( list, drawItem, drawEmpty, itemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, itemHeight, 0 ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, drawEmpty, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField<T>( list, drawItem, drawEmpty, DefaultItemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute<T>( position, list, drawItem, drawEmpty, DefaultItemHeight, 0 ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, null, itemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, null, itemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight ) { DoListField<T>( list, drawItem, null, itemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight ) { DoListFieldAbsolute<T>( position, list, drawItem, null, itemHeight, 0 ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags ) { DoListField<T>( list, drawItem, null, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags ) { DoListFieldAbsolute<T>( position, list, drawItem, null, DefaultItemHeight, flags ); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>( IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem ) { DoListField<T>( list, drawItem, null, DefaultItemHeight, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>( Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem ) { DoListFieldAbsolute<T>( position, list, drawItem, null, DefaultItemHeight, 0 ); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="itemCount">Count of items in list.</param> /// <param name="itemHeight">Fixed height of list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight( int itemCount, float itemHeight, ReorderableListFlags flags ) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight( itemCount, itemHeight ); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight( int itemCount, ReorderableListFlags flags ) { return CalculateListFieldHeight( itemCount, DefaultItemHeight, flags ); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight( int itemCount, float itemHeight ) { return CalculateListFieldHeight( itemCount, itemHeight, 0 ); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight( int itemCount ) { return CalculateListFieldHeight( itemCount, DefaultItemHeight, 0 ); } #endregion #region SerializedProperty Control /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { var adaptor = new SerializedPropertyAdaptor( arrayProperty, fixedItemHeight ); ReorderableListControl.DrawControlFromState( adaptor, drawEmpty, flags ); } /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="position">Position of control.</param> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { var adaptor = new SerializedPropertyAdaptor( arrayProperty, fixedItemHeight ); ReorderableListControl.DrawControlFromState( position, adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField( arrayProperty, 0, drawEmpty, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, 0, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( arrayProperty, 0, drawEmpty, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, arrayProperty, 0, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, ReorderableListFlags flags ) { DoListField( arrayProperty, 0, null, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, 0, null, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty ) { DoListField( arrayProperty, 0, null, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty ) { DoListFieldAbsolute( position, arrayProperty, 0, null, 0 ); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight( SerializedProperty arrayProperty, ReorderableListFlags flags ) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight( new SerializedPropertyAdaptor( arrayProperty ) ); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/> public static float CalculateListFieldHeight( SerializedProperty arrayProperty ) { return CalculateListFieldHeight( arrayProperty, 0 ); } #endregion #region SerializedProperty Control (Fixed Item Height) /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField( arrayProperty, fixedItemHeight, drawEmpty, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( arrayProperty, fixedItemHeight, drawEmpty, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags ) { DoListField( arrayProperty, fixedItemHeight, null, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, null, flags ); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( SerializedProperty arrayProperty, float fixedItemHeight ) { DoListField( arrayProperty, fixedItemHeight, null, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, SerializedProperty arrayProperty, float fixedItemHeight ) { DoListFieldAbsolute( position, arrayProperty, fixedItemHeight, null, 0 ); } #endregion #region Adaptor Control /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { ReorderableListControl.DrawControlFromState( adaptor, drawEmpty, flags ); } private static void DoListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( adaptor, drawEmpty, 0 ); } /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="position">Position of control.</param> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { ReorderableListControl.DrawControlFromState( position, adaptor, drawEmpty, flags ); } private static void DoListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, adaptor, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags ) { DoListField( adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags ) { DoListFieldAbsolute( position, adaptor, drawEmpty, flags ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty ) { DoListField( adaptor, drawEmpty, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty ) { DoListFieldAbsolute( position, adaptor, drawEmpty, 0 ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor, ReorderableListFlags flags ) { DoListField( adaptor, null, flags ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags ) { DoListFieldAbsolute( position, adaptor, null, flags ); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField( IReorderableListAdaptor adaptor ) { DoListField( adaptor, null, 0 ); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute( Rect position, IReorderableListAdaptor adaptor ) { DoListFieldAbsolute( position, adaptor, null, 0 ); } /// <summary> /// Calculate height of list field for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight( IReorderableListAdaptor adaptor, ReorderableListFlags flags ) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = defaultListControl.flags; try { defaultListControl.flags = flags; return defaultListControl.CalculateListHeight( adaptor ); } finally { defaultListControl.flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/> public static float CalculateListFieldHeight( IReorderableListAdaptor adaptor ) { return CalculateListFieldHeight( adaptor, 0 ); } #endregion } } #endif
using System; using System.Collections; using System.Collections.Generic; using Gtk; using Gdk; using Moscrif.IDE.Iface.Entities; using Moscrif.IDE.Components; namespace Moscrif.IDE.Controls { public class BuyDialog: Dialog { TextView viewHeader; TextView viewFooter; TextView viewTable; bool hoveringOverLink = false; Gdk.Cursor handCursor, regularCursor; License featureLicence = null; string featureTitle; int featureLicenceId =-100; public BuyDialog(int featureLicenceId,string featureTitle,Gtk.Window parent) : base () { this.featureTitle = featureTitle; this.featureLicenceId = featureLicenceId; this.HasSeparator = false; if(parent!=null) this.TransientFor = parent; this.WidthRequest = 570; this.HeightRequest = 450; this.ModifyBg (Gtk.StateType.Normal, Style.White); string userLicenceId ="-100"; if(MainClass.User != null){ userLicenceId = MainClass.User.LicenseId; } int iTyp =0; if(!Int32.TryParse(userLicenceId,out iTyp)){ iTyp = -100; } featureLicence = MainClass.LicencesSystem.GetLicence(this.featureLicenceId.ToString()); handCursor = new Gdk.Cursor (Gdk.CursorType.Hand2); regularCursor = new Gdk.Cursor (Gdk.CursorType.Xterm); viewHeader = new TextView (); viewHeader.CanFocus = false; TextBuffer buffer = viewHeader.Buffer; viewFooter = new TextView (); TextBuffer buffer2 = viewFooter.Buffer; viewFooter.KeyPressEvent += new KeyPressEventHandler (KeyPress); viewFooter.WidgetEventAfter += new WidgetEventAfterHandler (EventAfter); viewFooter.MotionNotifyEvent += new MotionNotifyEventHandler (MotionNotify); viewFooter.HeightRequest = 15; viewFooter.CanFocus = false; viewTable = new TextView (); viewTable.CanFocus = false; TextBuffer buffer3 = viewTable.Buffer; ScrolledWindow sw = new ScrolledWindow (); sw.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); sw.HeightRequest = 115; sw.Add (viewHeader); ScrolledWindow sw2 = new ScrolledWindow (); sw2.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); sw2.HeightRequest = 15; sw2.Add (viewFooter); ScrolledWindow sw3 = new ScrolledWindow (); sw3.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); sw3.Add (viewTable); CreateTags (buffer); CreateTags (buffer2); CreateTags (buffer3); InsertTextHeader (buffer); InsertTextFooter (buffer2); InsertTextTable (buffer3); Table tbl = new Table(4,1,false); if(MainClass.Platform.IsMac) tbl.BorderWidth=20; else tbl.BorderWidth=6; BannerButton btnBuy = new BannerButton(); btnBuy.ModifyBase(StateType.Normal,new Gdk.Color(109,158,24)); btnBuy.ModifyBg(StateType.Normal,new Color(109,158,24)); btnBuy.HeightRequest = 38; btnBuy.WidthRequest = 170; string buyPath = System.IO.Path.Combine(MainClass.Paths.ResDir,"btnBuy.png"); btnBuy.ButtonPressEvent+= delegate(object o, ButtonPressEventArgs args) { string url = "http://moscrif.com/download?t={0}"; if (MainClass.User!=null && (!String.IsNullOrEmpty(MainClass.User.Token))) { url = string.Format(url,MainClass.User.Token); } System.Diagnostics.Process.Start(url); this.Respond( Gtk.ResponseType.Ok ); }; btnBuy.ImageIcon = new Pixbuf(buyPath); BannerButton btnCancel = new BannerButton(); btnCancel.HeightRequest = 38; btnCancel.WidthRequest = 170; string cancelPath = System.IO.Path.Combine(MainClass.Paths.ResDir,"btnCancel.png"); btnCancel.ImageIcon = new Pixbuf(cancelPath); btnCancel.ButtonPressEvent+= delegate(object o, ButtonPressEventArgs args) { this.Respond( Gtk.ResponseType.Cancel ); }; Table tblButton = new Table (1,4,false); tblButton.ColumnSpacing = 12; tblButton.BorderWidth = 6; tblButton.Attach(new Label(""),0,1,0,1,AttachOptions.Expand,AttachOptions.Expand,0,0); tblButton.Attach(btnCancel,1,2,0,1,AttachOptions.Shrink,AttachOptions.Shrink,0,0); tblButton.Attach(btnBuy,2,3,0,1,AttachOptions.Shrink,AttachOptions.Shrink,0,0); tblButton.Attach(new Label(""),3,4,0,1,AttachOptions.Expand,AttachOptions.Expand,0,0); tbl.Attach(sw,0,1,0,1,AttachOptions.Fill,AttachOptions.Fill,0,0); tbl.Attach(sw3,0,1,1,2,AttachOptions.Fill|AttachOptions.Expand,AttachOptions.Fill|AttachOptions.Expand,0,0); tbl.Attach(tblButton,0,1,2,3,AttachOptions.Fill,AttachOptions.Fill,0,0); tbl.Attach(sw2,0,1,3,4,AttachOptions.Fill,AttachOptions.Shrink,0,0); tbl.ShowAll(); this.VBox.Add (tbl); this.ShowAll(); } private void CreateTags (TextBuffer buffer) { TextTag tag = new TextTag ("heading"); tag.Weight = Pango.Weight.Bold; tag.Size = (int) Pango.Scale.PangoScale * 15; //tag.Justification = Justification.Center; tag.Editable = false; tag.Foreground= "#5A646E"; buffer.TagTable.Add (tag); tag = new TextTag ("word_wrap"); tag.WrapMode = WrapMode.Word; tag.Editable = false; buffer.TagTable.Add (tag); tag = new TextTag ("word_justification"); tag.Justification = Justification.Center; tag.Editable = false; buffer.TagTable.Add (tag); } private void InsertTextHeader (TextBuffer buffer) { TextIter insertIter = buffer.StartIter; string upgradeLicence = ""; if(featureLicence != null){ upgradeLicence = featureLicence.Name; } buffer.InsertWithTagsByName (ref insertIter, String.Format("Moscrif {0} ",upgradeLicence), "heading"); buffer.Insert (ref insertIter,"\n\n"); buffer.Insert (ref insertIter, String.Format("The \"{0}\" is available for Moscrif {1} license. Please purchase an upgrade to unlock this Buying Moscrif {1} License you also unlock:\n\n",featureTitle,upgradeLicence)); buffer.ApplyTag ("word_wrap", buffer.StartIter, buffer.EndIter); } private void InsertTextFooter (TextBuffer buffer) { TextIter insertIter = buffer.StartIter; buffer.Insert (ref insertIter,"More features area avalable in Pro License. "); InsertLink (buffer, ref insertIter, "Buy Pro now!", 1); buffer.ApplyTag ("word_justification", buffer.StartIter, buffer.EndIter); } private void InsertTextTable (TextBuffer buffer) { Pixbuf pixbuf2 = MainClass.Tools.GetIconFromStock("file-ms.png",IconSize.Menu); TextIter insertIter = buffer.StartIter; List<Feature> listDif = MainClass.LicencesSystem.GetUserDifferent(featureLicence); if(listDif!= null){ foreach(Feature ftv in listDif){ buffer.Insert (ref insertIter," "); buffer.InsertPixbuf (ref insertIter, pixbuf2); buffer.Insert (ref insertIter, String.Format(" {0} \n", ftv.Name)); } } buffer.ApplyTag ("word_wrap", buffer.StartIter, buffer.EndIter); } void InsertLink (TextBuffer buffer, ref TextIter iter, string text, int page) { TextTag tag = new TextTag (null); tag.Foreground = "blue"; tag.Underline = Pango.Underline.Single; buffer.TagTable.Add (tag); buffer.InsertWithTags (ref iter, text, tag); } void KeyPress (object sender, KeyPressEventArgs args) { TextView view = sender as TextView; switch ((Gdk.Key) args.Event.KeyValue) { case Gdk.Key.Return: case Gdk.Key.KP_Enter: TextIter iter = view.Buffer.GetIterAtMark (view.Buffer.InsertMark); FollowIfLink (view, iter); break; default: break; } } void EventAfter (object sender, WidgetEventAfterArgs args) { if (args.Event.Type != Gdk.EventType.ButtonRelease) return; Gdk.EventButton evt = (Gdk.EventButton)args.Event; if (evt.Button != 1) return; TextView view = sender as TextView; TextIter start, end, iter; int x, y; // we shouldn't follow a link if the user has selected something view.Buffer.GetSelectionBounds (out start, out end); if (start.Offset != end.Offset) return; view.WindowToBufferCoords (TextWindowType.Widget, (int) evt.X, (int) evt.Y, out x, out y); iter = view.GetIterAtLocation (x, y); FollowIfLink (view, iter); } void MotionNotify (object sender, MotionNotifyEventArgs args) { TextView view = sender as TextView; int x, y; Gdk.ModifierType state; view.WindowToBufferCoords (TextWindowType.Widget, (int) args.Event.X, (int) args.Event.Y, out x, out y); SetCursorIfAppropriate (view, x, y); view.GdkWindow.GetPointer (out x, out y, out state); } void SetCursorIfAppropriate (TextView view, int x, int y) { bool hovering = false; TextIter iter = view.GetIterAtLocation (x, y); foreach (TextTag tag in iter.Tags) { if (tag.Underline == Pango.Underline.Single) { hovering = true; break; } } if (hovering != hoveringOverLink) { Gdk.Window window = view.GetWindow (Gtk.TextWindowType.Text); hoveringOverLink = hovering; if (hoveringOverLink) window.Cursor = handCursor; else window.Cursor = regularCursor; } } void FollowIfLink (TextView view, TextIter iter) { foreach (TextTag tag in iter.Tags) { if (tag.Underline == Pango.Underline.Single){ string url = "http://moscrif.com/download"; if (MainClass.User!=null && (!String.IsNullOrEmpty(MainClass.User.Token))) { url = string.Format(url,MainClass.User.Token); } System.Diagnostics.Process.Start(url); } } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace Microsoft.Tools.ServiceModel.ComSvcConfig { using System; using System.ServiceModel.Channels; using System.Diagnostics; using System.Configuration; using System.Globalization; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Configuration; using System.ServiceModel.ComIntegration; using Microsoft.Tools.ServiceModel; using Microsoft.Tools.ServiceModel.SvcUtil; class SvcFileManager { string webDirectoryPath; Dictionary<Guid, SvcFile> svcFiles; public SvcFileManager(string webDirectoryPath) { this.webDirectoryPath = webDirectoryPath; this.svcFiles = new Dictionary<Guid, SvcFile>(); string[] fileNames = Directory.GetFiles(webDirectoryPath, "*.svc"); foreach (string fileName in fileNames) { SvcFile svcFile = SvcFile.OpenExisting(fileName); if (svcFile != null) { this.svcFiles.Add(svcFile.Clsid, svcFile); } } } public void Abort() { foreach (SvcFile file in svcFiles.Values) { file.Abort(); } } public void Add(Guid appid, Guid clsid) { SvcFile svcFile = null; if (this.svcFiles.TryGetValue(clsid, out svcFile)) { // we found an existing SVC file, all is good // We should never be adding and deleting SVC files at the same time.. Debug.Assert(svcFile.State != SvcFileState.Deleted, "svcFile.State != SvcFileState.Deleted"); } else { svcFile = SvcFile.CreateNew(this.webDirectoryPath, appid, clsid); this.svcFiles.Add(clsid, svcFile); } } public bool Remove(Guid appid, Guid clsid) { SvcFile svcFile = null; if (this.svcFiles.TryGetValue(clsid, out svcFile)) { // we found an existing SVC file // We should never be adding and deleting SVC files at the same time.. Debug.Assert(svcFile.State != SvcFileState.Added, "svcFile.State != SvcFileState.Added"); if (svcFile.State == SvcFileState.Deleted) { // already marked for deletion return true; } else { Debug.Assert(svcFile.State == SvcFileState.Existing, "svcFile.State == SvcFileState.Existing"); svcFile.Delete(); return true; } } else { // didn't find any SVC file to remove return false; } } public void Prepare() { foreach (SvcFile file in svcFiles.Values) { file.Prepare(); } } public void Commit() { foreach (SvcFile file in svcFiles.Values) { file.Commit(); } } public bool ResolveClsid(Guid clsid, out Guid appid) { SvcFile svcFile; appid = Guid.Empty; if (this.svcFiles.TryGetValue(clsid, out svcFile)) { if (svcFile.State == SvcFileState.Deleted) { return false; // we cant resolve because we think its deleted } else { appid = svcFile.Appid; return true; } } else { return false; // Clsid not found } } enum SvcFileState { Existing, Added, Deleted } class SvcFile { Guid appid; Guid clsid; SvcFileState state; AtomicFile svcFile; const string factoryAttributeName = "Factory"; const string serviceAttributeName = "Service"; SvcFile(Guid appid, Guid clsid, SvcFileState state, AtomicFile svcFile) { this.appid = appid; this.clsid = clsid; this.state = state; this.svcFile = svcFile; } public static SvcFile CreateNew(string webDirectoryPath, Guid appid, Guid clsid) { ComAdminAppInfo adminAppInfo = ComAdminWrapper.GetAppInfo(appid.ToString("B")); if (null == adminAppInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindAppInfo, appid.ToString("B")), null); } ComAdminClassInfo adminClassInfo = adminAppInfo.FindClass(clsid.ToString("B")); if (null == adminClassInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindClassInfo, clsid.ToString("B")), null); } string fileName = webDirectoryPath + "\\" + adminClassInfo.Name; if (File.Exists(fileName + ".svc")) { int count = 1; while (File.Exists(fileName + "." + count.ToString(CultureInfo.InvariantCulture) + ".svc")) { count++; } fileName = fileName + "." + count.ToString(CultureInfo.InvariantCulture); } fileName = fileName + ".svc"; string comPlusString = clsid.ToString("B") + "," + appid.ToString("B"); using (StreamWriter sw = File.CreateText(fileName)) { sw.WriteLine("<%@ServiceHost {0}=\"{1}\" {2}=\"{3}\" %>", factoryAttributeName, typeof(WasHostedComPlusFactory).FullName, serviceAttributeName, comPlusString); } return new SvcFile(appid, clsid, SvcFileState.Added, new AtomicFile(fileName)); } // this function wraps the call to the internal method in ServiceModel assembly. static IDictionary<string, string> ParseServiceDirective(string serviceText) { IDictionary<string, string> dictionary = null; try { Type serviceParser = typeof(ServiceHostFactory).Assembly.GetType("System.ServiceModel.Activation.ServiceParser"); dictionary = (IDictionary<string, string>)serviceParser.InvokeMember("ParseServiceDirective", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new object[1] { serviceText }, CultureInfo.InvariantCulture); } catch (TargetInvocationException e) { throw e.InnerException; } return dictionary; } public static SvcFile OpenExisting(string fileName) { if (!File.Exists(fileName)) { return null; } string svcFileContents = null; Guid appid; Guid clsid; using (StreamReader sr = File.OpenText(fileName)) { svcFileContents = sr.ReadToEnd(); } IDictionary<string, string> dictionary = null; try { dictionary = ParseServiceDirective(svcFileContents); } catch (Exception e) { if (e is NullReferenceException || e is SEHException) { throw e; } ToolConsole.WriteWarning(SR.GetString(SR.SvcFileParsingFailedWithError, fileName, e.Message)); return null; } if (dictionary == null) { return null; } if (!dictionary.ContainsKey(factoryAttributeName) || !dictionary.ContainsKey(serviceAttributeName)) { return null; } string typeName = dictionary[factoryAttributeName]; Type factoryType = typeof(WasHostedComPlusFactory); Type compiledType = factoryType.Assembly.GetType(dictionary[factoryAttributeName], false); if (compiledType != factoryType) { return null; } string comPlusText = dictionary[serviceAttributeName]; string[] parameters = comPlusText.Split(','); if (parameters.Length != 2) { ToolConsole.WriteWarning(SR.GetString(SR.BadlyFormattedSvcFile, fileName)); return null; } try { clsid = new Guid(parameters[0]); appid = new Guid(parameters[1]); } catch (FormatException) { ToolConsole.WriteWarning(SR.GetString(SR.BadlyFormattedAppIDOrClsidInSvcFile, fileName)); return null; } return new SvcFile(appid, clsid, SvcFileState.Existing, new AtomicFile(fileName)); } public Guid Appid { get { return this.appid; } } public Guid Clsid { get { return this.clsid; } } public SvcFileState State { get { return this.state; } } public void Abort() { this.svcFile.Abort(); } public void Commit() { this.svcFile.Commit(); } public void Delete() { Debug.Assert(this.state == SvcFileState.Existing, "this.state == SvcFileState.Existing"); this.svcFile.Delete(); this.state = SvcFileState.Deleted; } public void Prepare() { this.svcFile.Prepare(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.MultiCluster; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Versions; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private readonly GlobalConfiguration globalConfig; private readonly IMultiClusterOracle multiClusterOracle; private readonly IInternalGrainFactory internalGrainFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly MembershipTableFactory membershipTableFactory; private readonly GrainTypeManager grainTypeManager; private readonly IVersionStore versionStore; private ILogger logger; public ManagementGrain( GlobalConfiguration globalConfig, IMultiClusterOracle multiClusterOracle, IInternalGrainFactory internalGrainFactory, ISiloStatusOracle siloStatusOracle, MembershipTableFactory membershipTableFactory, GrainTypeManager grainTypeManager, IVersionStore versionStore) { this.globalConfig = globalConfig; this.multiClusterOracle = multiClusterOracle; this.internalGrainFactory = internalGrainFactory; this.siloStatusOracle = siloStatusOracle; this.membershipTableFactory = membershipTableFactory; this.grainTypeManager = grainTypeManager; this.versionStore = versionStore; } public override Task OnActivateAsync() { logger = this.ServiceProvider.GetRequiredService<ILogger<ManagementGrain>>(); return Task.CompletedTask; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { // If the status oracle isn't MembershipOracle, then it is assumed that it does not use IMembershipTable. // In that event, return the approximate silo statuses from the status oracle. if (!(this.siloStatusOracle is MembershipOracle)) return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive); // Explicitly read the membership table and return the results. var table = await GetMembershipTable(); var members = await table.ReadAll(); var results = onlyActive ? members.Members.Where(item => item.Item1.Status == SiloStatus.Active) : members.Members; return results.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing) { var global = new[] { "Globals/", "/Globals/", "OrleansConfiguration/Globals/", "/OrleansConfiguration/Globals/" }; if (hostIds != null && configuration.Keys.Any(k => global.Any(k.StartsWith))) throw new ArgumentException("Must update global configuration settings on all silos"); var silos = GetSiloAddresses(hostIds); if (silos.Length == 0) return; var document = XPathValuesToXml(configuration); if (tracing != null) { AddXPathValue(document, new[] { "OrleansConfiguration", "Defaults", "Tracing" }, null); var parent = document["OrleansConfiguration"]["Defaults"]["Tracing"]; foreach (var trace in tracing) { var child = document.CreateElement("TraceLevelOverride"); child.SetAttribute("LogPrefix", trace.Key); child.SetAttribute("TraceLevel", trace.Value); parent.AppendChild(child); } } using(var sw = new StringWriter()) { using(var xw = XmlWriter.Create(sw)) { document.WriteTo(xw); xw.Flush(); var xml = sw.ToString(); // do first one, then all the rest to avoid spamming all the silos in case of a parameter error await GetSiloControlReference(silos[0]).UpdateConfiguration(xml); await Task.WhenAll(silos.Skip(1).Select(s => GetSiloControlReference(s).UpdateConfiguration(xml))); } } } public async Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { SiloAddress[] silos = GetSiloAddresses(hostIds); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).UpdateStreamProviders(streamProviderConfigurations)); await Task.WhenAll(actionPromises); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task SetCompatibilityStrategy(CompatibilityStrategy strategy) { await SetStrategy( store => store.SetCompatibilityStrategy(strategy), siloControl => siloControl.SetCompatibilityStrategy(strategy)); } public async Task SetSelectorStrategy(VersionSelectorStrategy strategy) { await SetStrategy( store => store.SetSelectorStrategy(strategy), siloControl => siloControl.SetSelectorStrategy(strategy)); } public async Task SetCompatibilityStrategy(int interfaceId, CompatibilityStrategy strategy) { CheckIfIsExistingInterface(interfaceId); await SetStrategy( store => store.SetCompatibilityStrategy(interfaceId, strategy), siloControl => siloControl.SetCompatibilityStrategy(interfaceId, strategy)); } public async Task SetSelectorStrategy(int interfaceId, VersionSelectorStrategy strategy) { CheckIfIsExistingInterface(interfaceId); await SetStrategy( store => store.SetSelectorStrategy(interfaceId, strategy), siloControl => siloControl.SetSelectorStrategy(interfaceId, strategy)); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private void CheckIfIsExistingInterface(int interfaceId) { Type unused; var interfaceMap = this.grainTypeManager.ClusterGrainInterfaceMap; if (!interfaceMap.TryGetServiceInterface(interfaceId, out unused)) { throw new ArgumentException($"Interface code '{interfaceId} not found", nameof(interfaceId)); } } private async Task SetStrategy(Func<IVersionStore, Task> storeFunc, Func<ISiloControl, Task> applyFunc) { await storeFunc(versionStore); var silos = GetSiloAddresses(null); var actionPromises = PerformPerSiloAction( silos, s => applyFunc(GetSiloControlReference(s))); try { await Task.WhenAll(actionPromises); } catch (Exception) { // ignored: silos that failed to set the new strategy will reload it from the storage // in the future. } } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private Task<IMembershipTable> GetMembershipTable() { if (!(this.siloStatusOracle is MembershipOracle)) throw new InvalidOperationException("The current membership oracle does not support detailed silo status reporting."); return this.membershipTableFactory.GetMembershipTable(); } private SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return this.siloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action functiona to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } #region MultiCluster private IMultiClusterOracle GetMultiClusterOracle() { if (!this.globalConfig.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return this.multiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.Rendering; using Microsoft.Data.Entity; using DI.Web.Models; using DI.Web.Services; using DI.Web.ViewModels.Account; namespace DI.Web.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ApplicationDbContext _applicationDbContext; private static bool _databaseChecked; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ApplicationDbContext applicationDbContext) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _applicationDbContext = applicationDbContext; } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { EnsureDatabaseCreated(_applicationDbContext); ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { EnsureDatabaseCreated(_applicationDbContext); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(HomeController.Index), "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { EnsureDatabaseCreated(_applicationDbContext); // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null) { var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (User.IsSignedIn()) { return RedirectToAction(nameof(ManageController.Index),"Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { return View("Lockout"); } else { ModelState.AddModelError("", "Invalid code."); return View(model); } } #region Helpers // The following code creates the database and schema if they don't exist. // This is a temporary workaround since deploying database through EF migrations is // not yet supported in this release. // Please see this http://go.microsoft.com/fwlink/?LinkID=615859 for more information on how to do deploy the database // when publishing your application. private static void EnsureDatabaseCreated(ApplicationDbContext context) { if (!_databaseChecked) { _databaseChecked = true; context.Database.Migrate(); } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private async Task<ApplicationUser> GetCurrentUserAsync() { return await _userManager.FindByIdAsync(HttpContext.User.GetUserId()); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lucene.Net.Analysis.Hunspell { /// <summary> /// HunspellStemmer uses the affix rules declared in the HunspellDictionary to generate one or /// more stems for a word. It conforms to the algorithm in the original hunspell algorithm, /// including recursive suffix stripping. /// </summary> /// <author>Chris Male</author> public class HunspellStemmer { private static Int32 RECURSION_CAP = 2; private readonly HunspellDictionary _dictionary; /// <summary> /// Constructs a new HunspellStemmer which will use the provided HunspellDictionary /// to create its stems. /// </summary> /// <param name="dictionary">HunspellDictionary that will be used to create the stems.</param> public HunspellStemmer(HunspellDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } /// <summary> /// Find the stem(s) of the provided word. /// </summary> /// <param name="word">Word to find the stems for.</param> /// <returns>List of stems for the word.</returns> public IEnumerable<HunspellStem> Stem(String word) { if (word == null) throw new ArgumentNullException("word"); var stems = new List<HunspellStem>(); if (_dictionary.LookupWord(word) != null) stems.Add(new HunspellStem(word)); stems.AddRange(Stem(word, null, 0)); return stems; } /// <summary> /// Find the unique stem(s) of the provided word. /// </summary> /// <param name="word">Word to find the stems for.</param> /// <returns>List of stems for the word.</returns> public IEnumerable<HunspellStem> UniqueStems(String word) { if (word == null) throw new ArgumentNullException("word"); var stems = new List<HunspellStem>(); var terms = new CharArraySet(8, false); if (_dictionary.LookupWord(word) != null) { stems.Add(new HunspellStem(word)); terms.Add(word); } var otherStems = Stem(word, null, 0); foreach (var s in otherStems) { if (!terms.Contains(s.Stem)) { stems.Add(s); terms.Add(s.Stem); } } return stems; } /// <summary> /// Generates a list of stems for the provided word. /// </summary> /// <param name="word">Word to generate the stems for.</param> /// <param name="flags">Flags from a previous stemming step that need to be cross-checked with any affixes in this recursive step.</param> /// <param name="recursionDepth">Level of recursion this stemming step is at.</param> /// <returns>List of stems, pr an empty if no stems are found.</returns> private IEnumerable<HunspellStem> Stem(String word, Char[] flags, Int32 recursionDepth) { if (word == null) throw new ArgumentNullException("word"); var stems = new List<HunspellStem>(); var chars = word.ToCharArray(); var length = word.Length; for (var i = 0; i < length; i++) { var suffixes = _dictionary.LookupSuffix(chars, i, length - i); if (suffixes != null) { foreach (var suffix in suffixes) { if (HasCrossCheckedFlag(suffix.Flag, flags)) { var deAffixedLength = length - suffix.Append.Length; // TODO: can we do this in-place? var strippedWord = new StringBuilder() .Append(word, 0, deAffixedLength) .Append(suffix.Strip) .ToString(); var stemList = ApplyAffix(strippedWord, suffix, recursionDepth); foreach (var stem in stemList) { stem.AddSuffix(suffix); } stems.AddRange(stemList); } } } } for (var i = length - 1; i >= 0; i--) { var prefixes = _dictionary.LookupPrefix(chars, 0, i); if (prefixes != null) { foreach (var prefix in prefixes) { if (HasCrossCheckedFlag(prefix.Flag, flags)) { var deAffixedStart = prefix.Append.Length; var deAffixedLength = length - deAffixedStart; var strippedWord = new StringBuilder() .Append(prefix.Strip) .Append(word, deAffixedStart, deAffixedLength) .ToString(); var stemList = ApplyAffix(strippedWord, prefix, recursionDepth); foreach (var stem in stemList) { stem.AddPrefix(prefix); } stems.AddRange(stemList); } } } } return stems; } /// <summary> /// Applies the affix rule to the given word, producing a list of stems if any are found. /// </summary> /// <param name="strippedWord">Word the affix has been removed and the strip added.</param> /// <param name="affix">HunspellAffix representing the affix rule itself.</param> /// <param name="recursionDepth">Level of recursion this stemming step is at.</param> /// <returns>List of stems for the word, or an empty list if none are found.</returns> public IEnumerable<HunspellStem> ApplyAffix(String strippedWord, HunspellAffix affix, Int32 recursionDepth) { if (strippedWord == null) throw new ArgumentNullException("strippedWord"); if (affix == null) throw new ArgumentNullException("affix"); if (!affix.CheckCondition(strippedWord)) { return new List<HunspellStem>(); } var words = _dictionary.LookupWord(strippedWord); if (words == null) { return new List<HunspellStem>(); } var stems = new List<HunspellStem>(); foreach (var hunspellWord in words) { if (hunspellWord.HasFlag(affix.Flag)) { if (affix.IsCrossProduct && recursionDepth < RECURSION_CAP) { var recursiveStems = Stem(strippedWord, affix.AppendFlags, ++recursionDepth); if (recursiveStems.Any()) { stems.AddRange(recursiveStems); } else { stems.Add(new HunspellStem(strippedWord)); } } else { stems.Add(new HunspellStem(strippedWord)); } } } return stems; } /// <summary> /// Checks if the given flag cross checks with the given array of flags. /// </summary> /// <param name="flag">Flag to cross check with the array of flags.</param> /// <param name="flags">Array of flags to cross check against. Can be <c>null</c>.</param> /// <returns><c>true</c> if the flag is found in the array or the array is <c>null</c>, <c>false</c> otherwise.</returns> private static Boolean HasCrossCheckedFlag(Char flag, Char[] flags) { return flags == null || Array.BinarySearch(flags, flag) >= 0; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.WindowsAzure.Management.Sql; namespace Microsoft.WindowsAzure.Management.Sql.Models { /// <summary> /// A standard service response including an HTTP status code and request /// ID. /// </summary> public partial class DatabaseUpdateResponse : OperationResponse { private string _collationName; /// <summary> /// Gets or sets the database resource's collation name. /// </summary> public string CollationName { get { return this._collationName; } set { this._collationName = value; } } private DateTime _creationDate; /// <summary> /// Gets or sets the date this database was created. /// </summary> public DateTime CreationDate { get { return this._creationDate; } set { this._creationDate = value; } } private string _edition; /// <summary> /// Gets or sets the database resource's edition. /// </summary> public string Edition { get { return this._edition; } set { this._edition = value; } } private int _id; /// <summary> /// Gets or sets the id of the database. /// </summary> public int Id { get { return this._id; } set { this._id = value; } } private bool _isFederationRoot; /// <summary> /// Gets or sets a value indicating whether the database is a /// federation root. /// </summary> public bool IsFederationRoot { get { return this._isFederationRoot; } set { this._isFederationRoot = value; } } private bool _isSystemObject; /// <summary> /// Gets or sets a value indicating whether the database is a system /// object. /// </summary> public bool IsSystemObject { get { return this._isSystemObject; } set { this._isSystemObject = value; } } private long _maximumDatabaseSizeInGB; /// <summary> /// Gets or sets the maximum size of this database, in Gigabytes. /// </summary> public long MaximumDatabaseSizeInGB { get { return this._maximumDatabaseSizeInGB; } set { this._maximumDatabaseSizeInGB = value; } } private string _name; /// <summary> /// Gets or sets the name of the database. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _serviceObjectiveAssignmentErrorCode; /// <summary> /// Gets or sets the error code for this service objective. /// </summary> public string ServiceObjectiveAssignmentErrorCode { get { return this._serviceObjectiveAssignmentErrorCode; } set { this._serviceObjectiveAssignmentErrorCode = value; } } private string _serviceObjectiveAssignmentErrorDescription; /// <summary> /// Gets or sets the error description, if any. /// </summary> public string ServiceObjectiveAssignmentErrorDescription { get { return this._serviceObjectiveAssignmentErrorDescription; } set { this._serviceObjectiveAssignmentErrorDescription = value; } } private string _serviceObjectiveAssignmentState; /// <summary> /// Gets or sets the state of the current assignment. /// </summary> public string ServiceObjectiveAssignmentState { get { return this._serviceObjectiveAssignmentState; } set { this._serviceObjectiveAssignmentState = value; } } private string _serviceObjectiveAssignmentStateDescription; /// <summary> /// Gets or sets the state description. /// </summary> public string ServiceObjectiveAssignmentStateDescription { get { return this._serviceObjectiveAssignmentStateDescription; } set { this._serviceObjectiveAssignmentStateDescription = value; } } private string _serviceObjectiveAssignmentSuccessDate; /// <summary> /// Gets or sets the date the service's assignment succeeded. /// </summary> public string ServiceObjectiveAssignmentSuccessDate { get { return this._serviceObjectiveAssignmentSuccessDate; } set { this._serviceObjectiveAssignmentSuccessDate = value; } } private string _serviceObjectiveId; /// <summary> /// Gets or sets the id of this service objective. /// </summary> public string ServiceObjectiveId { get { return this._serviceObjectiveId; } set { this._serviceObjectiveId = value; } } private string _sizeMB; /// <summary> /// Gets or sets the size of this database in megabytes (MB). /// </summary> public string SizeMB { get { return this._sizeMB; } set { this._sizeMB = value; } } private string _state; /// <summary> /// Gets or sets the state of the database. /// </summary> public string State { get { return this._state; } set { this._state = value; } } private string _type; /// <summary> /// Gets or sets the type of resource. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the DatabaseUpdateResponse class. /// </summary> public DatabaseUpdateResponse() { } } }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; using NUnit.Framework; using Quartz.Simpl; using Quartz.Util; namespace Quartz.Tests.Unit { /// <author>Marko Lahma (.NET)</author> [TestFixture(typeof(BinaryObjectSerializer))] [TestFixture(typeof(JsonObjectSerializer))] public class CronExpressionTest : SerializationTestSupport<CronExpression> { private static readonly TimeZoneInfo testTimeZone = TimeZoneInfo.Local; public CronExpressionTest(Type serializerType) : base(serializerType) { } /// <summary> /// Get the object to serialize when generating serialized file for future /// tests, and against which to validate deserialized object. /// </summary> /// <returns></returns> protected override CronExpression GetTargetObject() { CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005"); cronExpression.TimeZone = testTimeZone; return cronExpression; } protected override void VerifyMatch(CronExpression original, CronExpression deserialized) { Assert.IsNotNull(deserialized); Assert.AreEqual(original.CronExpressionString, deserialized.CronExpressionString); Assert.AreEqual(original.TimeZone, deserialized.TimeZone); } /// <summary> /// Test method for 'CronExpression.IsSatisfiedBy(DateTime)'. /// </summary> [Test] public void TestIsSatisfiedBy() { CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005"); DateTime cal = new DateTime(2005, 6, 1, 10, 15, 0).ToUniversalTime(); Assert.IsTrue(cronExpression.IsSatisfiedBy(cal)); cal = cal.AddYears(1); Assert.IsFalse(cronExpression.IsSatisfiedBy(cal)); cal = new DateTime(2005, 6, 1, 10, 16, 0).ToUniversalTime(); Assert.IsFalse(cronExpression.IsSatisfiedBy(cal)); cal = new DateTime(2005, 6, 1, 10, 14, 0).ToUniversalTime(); Assert.IsFalse(cronExpression.IsSatisfiedBy(cal)); cronExpression = new CronExpression("0 15 10 ? * MON-FRI"); // weekends cal = new DateTime(2007, 6, 9, 10, 15, 0).ToUniversalTime(); Assert.IsFalse(cronExpression.IsSatisfiedBy(cal)); Assert.IsFalse(cronExpression.IsSatisfiedBy(cal.AddDays(1))); } [Test] public void TestLastDayOffset() { CronExpression cronExpression = new CronExpression("0 15 10 L-2 * ? 2010"); DateTime cal = new DateTime(2010, 10, 29, 10, 15, 0).ToUniversalTime(); // last day - 2 Assert.IsTrue(cronExpression.IsSatisfiedBy(cal)); cal = new DateTime(2010, 10, 28, 10, 15, 0).ToUniversalTime(); Assert.IsFalse(cronExpression.IsSatisfiedBy(cal)); cronExpression = new CronExpression("0 15 10 L-5W * ? 2010"); cal = new DateTime(2010, 10, 26, 10, 15, 0).ToUniversalTime(); // last day - 5 Assert.IsTrue(cronExpression.IsSatisfiedBy(cal)); cronExpression = new CronExpression("0 15 10 L-1 * ? 2010"); cal = new DateTime(2010, 10, 30, 10, 15, 0).ToUniversalTime(); // last day - 1 Assert.IsTrue(cronExpression.IsSatisfiedBy(cal)); cronExpression = new CronExpression("0 15 10 L-1W * ? 2010"); cal = new DateTime(2010, 10, 29, 10, 15, 0).ToUniversalTime(); // nearest weekday to last day - 1 (29th is a friday in 2010) Assert.IsTrue(cronExpression.IsSatisfiedBy(cal)); } [Test] public void TestCronExpressionPassingMidnight() { CronExpression cronExpression = new CronExpression("0 15 23 * * ?"); DateTimeOffset cal = new DateTime(2005, 6, 1, 23, 16, 0).ToUniversalTime(); DateTimeOffset nextExpectedFireTime = new DateTime(2005, 6, 2, 23, 15, 0).ToUniversalTime(); Assert.AreEqual(nextExpectedFireTime, cronExpression.GetTimeAfter(cal).Value); } [Test] public void TestCronExpressionPassingYear() { DateTimeOffset start = new DateTime(2007, 12, 1, 23, 59, 59).ToUniversalTime(); CronExpression ce = new CronExpression("0 55 15 1 * ?"); DateTimeOffset expected = new DateTime(2008, 1, 1, 15, 55, 0).ToUniversalTime(); DateTimeOffset d = ce.GetNextValidTimeAfter(start).Value; Assert.AreEqual(expected, d, "Got wrong date and time when passed year"); } [Test] public void TestCronExpressionWeekdaysMonFri() { CronExpression cronExpression = new CronExpression("0 0 12 ? * MON-FRI"); int[] arrJuneDaysThatShouldFire = {1, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 18, 19, 20, 22, 21, 25, 26, 27, 28, 29}; List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire); TestCorrectWeekFireDays(cronExpression, juneDays); } [Test] public void TestCronExpressionWeekdaysFriday() { CronExpression cronExpression = new CronExpression("0 0 12 ? * FRI"); var nextRunTime = cronExpression.GetTimeAfter(DateTimeOffset.Now); var nextRunTime2 = cronExpression.GetTimeAfter((DateTimeOffset)nextRunTime); int[] arrJuneDaysThatShouldFire = {1, 8, 15, 22, 29}; List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire); TestCorrectWeekFireDays(cronExpression, juneDays); } [Test] public void TestCronExpressionWeekdaysFridayEveryTwoWeeks() { CronExpression cronExpression = new CronExpression("0 0 12 ? * FRI/2"); var nextRunTime = cronExpression.GetTimeAfter(DateTimeOffset.Now); var nextRunTime2 = cronExpression.GetTimeAfter((DateTimeOffset)nextRunTime); int[] arrJuneDaysThatShouldFire = {1, 15, 29}; List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire); TestCorrectWeekFireDays(cronExpression, juneDays); } [Test] public void TestCronExpressionWeekdaysThirsdayAndFridayEveryTwoWeeks() { CronExpression cronExpression = new CronExpression("0 0 12 ? * THU,FRI/2"); var nextRunTime = cronExpression.GetTimeAfter(DateTimeOffset.Now); var nextRunTime2 = cronExpression.GetTimeAfter((DateTimeOffset)nextRunTime); int[] arrJuneDaysThatShouldFire = {1, 14, 15, 28, 29}; List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire); TestCorrectWeekFireDays(cronExpression, juneDays); } [Test] public void TestCronExpressionLastDayOfMonth() { CronExpression cronExpression = new CronExpression("0 0 12 L * ?"); int[] arrJuneDaysThatShouldFire = {30}; List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire); TestCorrectWeekFireDays(cronExpression, juneDays); } [Test] public void TestHourShift() { // cronexpression that fires every 5 seconds CronExpression cronExpression = new CronExpression("0/5 * * * * ?"); DateTimeOffset cal = new DateTimeOffset(2005, 6, 1, 1, 59, 55, TimeSpan.Zero); DateTimeOffset nextExpectedFireTime = new DateTimeOffset(2005, 6, 1, 2, 0, 0, TimeSpan.Zero); Assert.AreEqual(nextExpectedFireTime, cronExpression.GetTimeAfter(cal).Value); } [Test] public void TestMonthShift() { // QRTZNET-28 CronExpression cronExpression = new CronExpression("* * 1 * * ?"); DateTimeOffset cal = new DateTime(2005, 7, 31, 22, 59, 57).ToUniversalTime(); DateTimeOffset nextExpectedFireTime = new DateTime(2005, 8, 1, 1, 0, 0).ToUniversalTime(); Assert.AreEqual(nextExpectedFireTime, cronExpression.GetTimeAfter(cal).Value); } [Test] public void TestYearChange() { // QRTZNET-85 CronExpression cronExpression = new CronExpression("0 12 4 ? * 3"); cronExpression.GetNextValidTimeAfter(new DateTime(2007, 12, 28)); } [Test] public void TestCronExpressionParsingIncorrectDayOfWeek() { // test failed before because of improper trimming try { string expr = $" * * * * * {DateTime.Now.Year}"; CronExpression ce = new CronExpression(expr); ce.IsSatisfiedBy(DateTime.UtcNow.AddMinutes(2)); Assert.Fail("Accepted wrong format"); } catch (FormatException fe) { Assert.AreEqual("Day-of-Week values must be between 1 and 7", fe.Message); } } [Test] public void TestCronExpressionWithExtraWhiteSpace() { // test failed before because of improper trimming string expr = " 30 * * * * ? "; CronExpression calendar = new CronExpression(expr); Assert.IsFalse(calendar.IsSatisfiedBy(DateTime.UtcNow.Date.AddMinutes(2)), "Time was included"); } private static void TestCorrectWeekFireDays(CronExpression cronExpression, IList<int> correctFireDays) { List<int> fireDays = new List<int>(); DateTime cal = new DateTime(2007, 6, 1, 11, 0, 0).ToUniversalTime(); DateTimeOffset? nextFireTime = cal; for (int i = 0; i < DateTime.DaysInMonth(2007, 6); ++i) { nextFireTime = cronExpression.GetTimeAfter((DateTimeOffset)nextFireTime); if (!fireDays.Contains(nextFireTime.Value.Day) && nextFireTime.Value.Month == 6 && nextFireTime.Value.Year == 2007) { // next fire day may be monday for several days.. fireDays.Add(nextFireTime.Value.Day); } //cal = cal.AddDays(1); } // check rite dates fired for (int i = 0; i < fireDays.Count; ++i) { int idx = correctFireDays.IndexOf(fireDays[i]); Assert.Greater(idx, -1, $"CronExpression evaluated true for {fireDays[i]} even when it shouldn't have"); correctFireDays.RemoveAt(idx); } // check that all fired Assert.IsTrue(correctFireDays.Count == 0, $"CronExpression did not evaluate true for all expected days (count: {correctFireDays.Count})."); } [Test] public void TestFormatExceptionWildCardDayOfMonthAndDayOfWeek() { Assert.Throws<FormatException>(() => new CronExpression("0 0 * * * *"), "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); } [Test] public void TestFormatExceptionSpecifiedDayOfMonthAndWildCardDayOfWeek() { Assert.Throws<FormatException>(() => new CronExpression("0 0 * 4 * *"), "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); } [Test] public void TestFormatExceptionWildCardDayOfMonthAndSpecifiedDayOfWeek() { Assert.Throws<FormatException>(() => new CronExpression("0 0 * * * 4"), "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); } [Test] public void TestNthWeekDayPassingMonth() { CronExpression ce = new CronExpression("0 30 10-13 ? * FRI#3"); DateTime start = new DateTime(2008, 12, 19, 0, 0, 0); for (int i = 0; i < 200; ++i) { bool shouldFire = start.Hour >= 10 && start.Hour <= 13 && start.Minute == 30 && (start.DayOfWeek == DayOfWeek.Wednesday || start.DayOfWeek == DayOfWeek.Friday); shouldFire = shouldFire && start.Day > 15 && start.Day < 28; bool satisfied = ce.IsSatisfiedBy(start.ToUniversalTime()); Assert.AreEqual(shouldFire, satisfied); // cycle with half hour precision start = start.AddHours(0.5); } } [Test] public void TestNormal() { for (int i = 0; i < 6; i++) { AssertParsesForField("0 15 10 * * ? 2005", i); } } [Test] public void TestSecond() { AssertParsesForField("58-4 5 21 ? * MON-FRI", 0); } [Test] public void TestMinute() { AssertParsesForField("0 58-4 21 ? * MON-FRI", 1); } [Test] public void TestHour() { AssertParsesForField("0 0/5 21-3 ? * MON-FRI", 2); } [Test] public void TestDayOfWeekNumber() { AssertParsesForField("58 5 21 ? * 6-2", 5); } [Test] public void TestDayOfWeek() { AssertParsesForField("58 5 21 ? * FRI-TUE", 5); } [Test] public void TestDayOfMonth() { AssertParsesForField("58 5 21 28-5 1 ?", 3); } [Test] public void TestMonth() { AssertParsesForField("58 5 21 ? 11-2 FRI", 4); } [Test] public void TestAmbiguous() { AssertParsesForField("0 0 14-6 ? * FRI-MON", 2); AssertParsesForField("0 0 14-6 ? * FRI-MON", 5); AssertParsesForField("55-3 56-2 6 ? * FRI", 0); AssertParsesForField("55-3 56-2 6 ? * FRI", 1); } private static void AssertParsesForField(string expression, int constant) { try { SimpleCronExpression cronExpression = new SimpleCronExpression(expression); ICollection<int> set = cronExpression.GetSetPublic(constant); if (set.Count == 0) { Assert.Fail("Empty field [" + constant + "] returned for " + expression); } } catch (FormatException pe) { Assert.Fail("Exception thrown during parsing: " + pe); } } [Test] public void TestQuartz640() { try { new CronExpression("0 43 9 1,5,29,L * ?"); Assert.Fail("Expected FormatException did not fire for L combined with other days of the month"); } catch (FormatException fe) { Assert.IsTrue( fe.Message.StartsWith("Support for specifying 'L' and 'LW' with other days of the month is not implemented"), "Incorrect FormatException thrown"); } try { new CronExpression("0 43 9 ? * SAT,SUN,L"); Assert.Fail("Expected FormatException did not fire for L combined with other days of the week"); } catch (FormatException pe) { Assert.IsTrue( pe.Message.StartsWith("Support for specifying 'L' with other days of the week is not implemented"), "Incorrect FormatException thrown"); } try { new CronExpression("0 43 9 ? * 6,7,L"); Assert.Fail("Expected FormatException did not fire for L combined with other days of the week"); } catch (FormatException pe) { Assert.IsTrue( pe.Message.StartsWith("Support for specifying 'L' with other days of the week is not implemented"), "Incorrect FormatException thrown"); } try { new CronExpression("0 43 9 ? * 5L"); } catch (FormatException) { Assert.Fail("Unexpected ParseException thrown for supported '5L' expression."); } } [Test] public void TestGetTimeAfter_QRTZNET149() { CronExpression expression = new CronExpression("0 0 0 29 * ?"); DateTimeOffset? after = expression.GetNextValidTimeAfter(new DateTime(2009, 1, 30, 0, 0, 0).ToUniversalTime()); Assert.IsTrue(after.HasValue); Assert.AreEqual(new DateTime(2009, 3, 29, 0, 0, 0).ToUniversalTime(), after.Value.DateTime); after = expression.GetNextValidTimeAfter(new DateTime(2009, 12, 30).ToUniversalTime()); Assert.IsTrue(after.HasValue); Assert.AreEqual(new DateTime(2010, 1, 29, 0, 0, 0).ToUniversalTime(), after.Value.DateTime); } [Test] public void TestQRTZNET152() { CronExpression expression = new CronExpression("0 5 13 5W 1-12 ?"); DateTimeOffset test = new DateTimeOffset(2009, 3, 8, 0, 0, 0, TimeSpan.Zero); DateTimeOffset d = expression.GetNextValidTimeAfter(test).Value; Assert.AreEqual(new DateTimeOffset(2009, 4, 6, 13, 5, 0, TimeZoneUtil.GetUtcOffset(d, TimeZoneInfo.Local)).ToUniversalTime(), d); d = expression.GetNextValidTimeAfter(d).Value; Assert.AreEqual(new DateTimeOffset(2009, 5, 5, 13, 5, 0, TimeZoneUtil.GetUtcOffset(d, TimeZoneInfo.Local)), d); } [Test] public void ShouldThrowExceptionIfWParameterMakesNoSense() { try { new CronExpression("0/5 * * 32W 1 ?"); Assert.Fail("Expected FormatException did not fire for W with value larger than 31"); } catch (FormatException pe) { Assert.IsTrue(pe.Message.StartsWith("The 'W' option does not make sense with values larger than"), "Incorrect ParseException thrown"); } } /// <summary> /// QTZ-259 : last day offset causes repeating fire time /// </summary> [Test] public void TestQtz259() { ITrigger trigger = TriggerBuilder.Create().WithIdentity("test").WithCronSchedule("0 0 0 L-2 * ? *").Build(); int i = 0; DateTimeOffset? pdate = trigger.GetFireTimeAfter(DateTimeOffset.Now); while (++i < 26) { DateTimeOffset? date = trigger.GetFireTimeAfter(pdate); // Console.WriteLine("fireTime: " + date + ", previousFireTime: " + pdate); Assert.False(pdate.Equals(date), "Next fire time is the same as previous fire time!"); pdate = date; } } /// <summary> /// QTZ-259 : last day offset causes repeating fire time /// </summary> [Test] public void TestQtz259Lw() { ITrigger trigger = TriggerBuilder.Create().WithIdentity("test").WithCronSchedule("0 0 0 LW * ? *").Build(); int i = 0; DateTimeOffset? pdate = trigger.GetFireTimeAfter(DateTimeOffset.Now); while (++i < 26) { DateTimeOffset? date = trigger.GetFireTimeAfter(pdate); // Console.WriteLine("fireTime: " + date + ", previousFireTime: " + pdate); Assert.False(pdate.Equals(date), "Next fire time is the same as previous fire time!"); pdate = date; } } [Test] [Platform("WIN")] public void TestDaylightSaving_QRTZNETZ186() { CronExpression expression = new CronExpression("0 15 * * * ?"); if (!TimeZoneInfo.Local.SupportsDaylightSavingTime) { return; } var daylightChange = TimeZone.CurrentTimeZone.GetDaylightChanges(2012); DateTimeOffset before = daylightChange.Start.ToUniversalTime().AddMinutes(-5); // keep outside the potentially undefined interval DateTimeOffset? after = expression.GetNextValidTimeAfter(before); Assert.IsTrue(after.HasValue); DateTimeOffset expected = daylightChange.Start.Add(daylightChange.Delta).AddMinutes(15).ToUniversalTime(); Assert.AreEqual(expected, after.Value); } [Test] public void TestDaylightSavingsDoesNotMatchAnHourBefore() { TimeZoneInfo est = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); CronExpression expression = new CronExpression("0 15 15 5 11 ?"); expression.TimeZone = est; DateTimeOffset startTime = new DateTimeOffset(2012, 11, 4, 0, 0, 0, TimeSpan.Zero); var actualTime = expression.GetTimeAfter(startTime); DateTimeOffset expected = new DateTimeOffset(2012, 11, 5, 15, 15, 0, TimeSpan.FromHours(-5)); Assert.AreEqual(expected, actualTime.Value); } [Test] public void TestDaylightSavingsDoesNotMatchAnHourBefore2() { //another case TimeZoneInfo est = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); CronExpression expression = new CronExpression("0 0 0 ? * THU"); expression.TimeZone = est; DateTimeOffset startTime = new DateTimeOffset(2012, 11, 4, 0, 0, 0, TimeSpan.Zero); var actualTime = expression.GetTimeAfter(startTime); DateTimeOffset expected = new DateTimeOffset(2012, 11, 8, 0, 0, 0, TimeSpan.FromHours(-5)); Assert.AreEqual(expected, actualTime); } [Test] public void TestSecRangeIntervalAfterSlash() { // Test case 1 var e = Assert.Throws<FormatException>(() => new CronExpression("/120 0 8-18 ? * 2-6"), "Cron did not validate bad range interval in '_blank/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 60 : 120")); // Test case 2 e = Assert.Throws<FormatException>(() => new CronExpression("0/120 0 8-18 ? * 2-6"), "Cron did not validate bad range interval in in '0/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 60 : 120")); // Test case 3 e = Assert.Throws<FormatException>(() => new CronExpression("/ 0 8-18 ? * 2-6"), "Cron did not validate bad range interval in '_blank/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); // Test case 4 e = Assert.Throws<FormatException>(() => new CronExpression("0/ 0 8-18 ? * 2-6"), "Cron did not validate bad range interval in '0/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); } [Test] public void TestMinRangeIntervalAfterSlash() { // Test case 1 var e = Assert.Throws<FormatException>(() => new CronExpression("0 /120 8-18 ? * 2-6"), "Cron did not validate bad range interval in '_blank/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 60 : 120")); // Test case 2 e = Assert.Throws<FormatException>(() => new CronExpression("0 0/120 8-18 ? * 2-6"), "Cron did not validate bad range interval in in '0/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 60 : 120")); // Test case 3 e = Assert.Throws<FormatException>(() => new CronExpression("0 / 8-18 ? * 2-6"), "Cron did not validate bad range interval in '_blank/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); // Test case 4 e = Assert.Throws<FormatException>(() => new CronExpression("0 0/ 8-18 ? * 2-6"), "Cron did not validate bad range interval in '0/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); } [Test] public void TestHourRangeIntervalAfterSlash() { // Test case 1 var e = Assert.Throws<FormatException>(() => new CronExpression("0 0 /120 ? * 2-6"), "Cron did not validate bad range interval in '_blank/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 24 : 120")); // Test case 2 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0/120 ? * 2-6"), "Cron did not validate bad range interval in in '0/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 24 : 120")); // Test case 3 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 / ? * 2-6"), "Cron did not validate bad range interval in '_blank/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); // Test case 4 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0/ ? * 2-6"), "Cron did not validate bad range interval in '0/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); } [Test] public void TestDayOfMonthRangeIntervalAfterSlash() { // Test case 1 var e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 /120 * 2-6"), "Cron did not validate bad range interval in '_blank/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 31 : 120")); // Test case 2 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 0/120 * 2-6"), "Cron did not validate bad range interval in in '0/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 31 : 120")); // Test case 3 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 / * 2-6"), "Cron did not validate bad range interval in '_blank/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); // Test case 4 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 0/ * 2-6"), "Cron did not validate bad range interval in '0/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); } [Test] public void TestMonthRangeIntervalAfterSlash() { // Test case 1 var e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? /120 2-6"), "Cron did not validate bad range interval in '_blank/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 12 : 120")); // Test case 2 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? 0/120 2-6"), "Cron did not validate bad range interval in in '0/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 12 : 120")); // Test case 3 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? / 2-6"), "Cron did not validate bad range interval in '_blank/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); // Test case 4 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? 0/ 2-6"), "Cron did not validate bad range interval in '0/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); } [Test] public void TestDayOfWeekRangeIntervalAfterSlash() { // Test case 1 var e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? * /120"), "Cron did not validate bad range interval in '_blank/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 7 : 120")); // Test case 2 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? * 0/120"), "Cron did not validate bad range interval in in '0/xxx' form"); Assert.That(e.Message, Is.EqualTo("Increment > 7 : 120")); // Test case 3 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? * /"), "Cron did not validate bad range interval in '_blank/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); // Test case 4 e = Assert.Throws<FormatException>(() => new CronExpression("0 0 0 ? * 0/"), "Cron did not validate bad range interval in '0/_blank'"); Assert.That(e.Message, Is.EqualTo("'/' must be followed by an integer.")); } [Test] public void TestInvalidCharactersAfterAsterisk() { Assert.That(CronExpression.IsValidExpression("* * * ? * *A&/5:"), Is.False); Assert.That(CronExpression.IsValidExpression("* * * ? *14 "), Is.False); Assert.That(CronExpression.IsValidExpression(" * * ? *A&/5 *"), Is.False); Assert.That(CronExpression.IsValidExpression("* * ? */5 *"), Is.False); Assert.That(CronExpression.IsValidExpression("* * ? */52 *"), Is.False); Assert.That(CronExpression.IsValidExpression("0 0/30 * * * ?"), Is.True); Assert.That(CronExpression.IsValidExpression("0 0/1 * * * ?"), Is.True); Assert.That(CronExpression.IsValidExpression("0 0/30 * * */2 ?"), Is.True); } [Test] public void TestExtraCharactersAfterWeekDay() { Assert.That(CronExpression.IsValidExpression("0 0 15 ? * FRI*"), Is.False); } [Test] public void TestHourRangeAndSlash() { CronExpression.ValidateExpression("0 0 18-21/1 ? * MON,TUE,WED,THU,FRI,SAT,SUN"); } private class SimpleCronExpression : CronExpression { public SimpleCronExpression(string cronExpression) : base(cronExpression) { } public ISet<int> GetSetPublic(int constant) { return GetSet(constant); } } [Test] [Explicit] public void PerformanceTest() { var quartz = new CronExpression("* * * * * ?"); var sw = new Stopwatch(); sw.Start(); DateTimeOffset? next = new DateTimeOffset(2012, 1, 1, 0, 0, 0, TimeSpan.Zero); for (int i = 0; i < 1000000; i++) { next = quartz.GetNextValidTimeAfter(next.Value); if (next == null) break; } Console.WriteLine("{0}ms", sw.ElapsedMilliseconds); } } }
/// <summary> /// NoiseType.cs /// Author: trent (5/16/16) /// Modified: /// /// Based on the implementation by Jordan Peck: https://github.com/Auburns/FastNoise /// </summary> /// <summary> /// Noise Class Definition. /// /// Base noise class for all subsequent noise types. /// </summary> public abstract class Noise { public const int kLUTMask = 127; protected int seed = 0; protected float frequency = 0.01f; protected InterpolationType interpolationType = InterpolationType.Quintic; protected NoiseType noiseType = NoiseType.Value; protected uint octaves = 3; protected float lacunarity = 2.0f; protected float gain = 0.5f; protected FractalType fractalType = FractalType.FBM; /// <summary> /// Set the noise seed value. /// </summary> /// <param name="_seed">Noise seed value.</param> public void SetSeed( int _seed ) { seed = _seed; } /// <summary> /// Get the noise seed value. /// </summary> /// <returns>Noise seed value.</returns> public int GetSeed( ) { return seed; } /// <summary> /// Set the noise frequency. /// </summary> /// <param name="_frequency">Noise frequency.</param> public void SetFrequency( float _frequency ) { frequency = _frequency; } /// <summary> /// Set the noise interpolation type. /// </summary> /// <param name="type">Noise interpolation type.</param> public void SetInterpolationType( InterpolationType type ) { interpolationType = type; } /// <summary> /// Set the noise type (this is likely going to be removed). /// </summary> /// <param name="type">Noise type.</param> void SetNoiseType( NoiseType type ) { noiseType = type; } /// <summary> /// Set the number of fractal octaves. /// </summary> /// <param name="_octaves">Number of octaves.</param> public void SetFractalOctaves( uint _octaves ) { octaves = _octaves; } /// <summary> /// Set the noise lacunarity value. /// </summary> /// <param name="_lacunarity">Lacunarity value.</param> public void SetFractalLacunarity( float _lacunarity ) { lacunarity = _lacunarity; } /// <summary> /// Set the noise gain value. /// </summary> /// <param name="_gain">Noise gain value.</param> public void SetFractalGain( float _gain ) { gain = _gain; } /// <summary> /// Set the fractal type. /// </summary> /// <param name="_fractalType">Noise fractal type.</param> public void SetFractalType( FractalType _fractalType ) { fractalType = _fractalType; } /// <summary> /// Utility methods. /// </summary> protected static int FastFloor( float f ) { return ( f >= 0.0f ? ( int )f : ( int )f - 1 ); } protected static int FastRound( float f ) { return ( f >= 0.0f ) ? ( int )( f + 0.5f ) : ( int )( f - 0.5f ); } protected static float FastAbs( float f ) { return ( f >= 0.0f ) ? f : -f; } protected static int FastAbs( int i ) { return ( i > 0 ) ? i : -i; } protected static float Lerp( float a, float b, float t ) { return a + t * ( b - a ); } /// <summary> /// Linear intepolation function. /// </summary> /// <param name="o">Output of the linear interpolation (three-dimensional vector).</param> /// <param name="a">Vector a (three-dimensional vector).</param> /// <param name="b">Vector b (three-dimensional vector).</param> /// <param name="t">Interpolant.</param> protected static void LerpVector3( out float[] o, float[] a, float[] b, float t ) { o = new float [3]; o[0] = Lerp( a[0], b[0], t); o[1] = Lerp( a[1], b[1], t); o[2] = Lerp( a[2], b[2], t); } /// <summary> /// Hermite interpolation method. /// </summary> /// <param name="t">Interpolant.</param> /// <returns>Interpolated value.</returns> protected static float InterpHermite( float t ) { return( t*t*( 3 - 2 * t ) ); } /// <summary> /// Quintic interpolation method. /// </summary> /// <param name="t">Interpolant.</param> /// <returns>Interpolated value.</returns> protected static float InterpQuintic( float t ) { return( t*t*t*( t*( t * 6 - 15 ) + 10 ) ); } /// <summary> /// Get the look-up table index for a 2D coordinate. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <returns>Look-up table index.</returns> protected int GetLUTIndex( int x, int y ) { int hash = seed; hash^= x; hash*= 15485863; hash^= y; hash*= 10057189; hash^= hash >> 16; return( hash & kLUTMask ); } /// <summary> /// Get the look-up table index for a 3D coordinate. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <param name="z">z</param> /// <returns>Look-up table index.</returns> protected int GetLUTIndex( int x, int y, int z ) { int hash = seed; hash^= x; hash*= 15485863; hash^= y; hash*= 10057189; hash^= z; hash*= 987391; hash^= hash >> 16; return( hash & kLUTMask ); } /// <summary> /// Get the look-up table index for a 4D coordinate. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <param name="z">z</param> /// <param name="w">w</param> /// <returns>Look-up table index.</returns> protected int GetLUTIndex( int x, int y, int z, int w ) { int hash = seed; hash^= x; hash*= 15485863; hash^= y; hash*= 10057189; hash^= z; hash*= 987391; hash^= w; hash*= 418493; hash^= hash >> 16; return( hash & kLUTMask ); } // Abstract noise methods. public abstract float GetNoise( float x, float y ); public abstract float GetNoise( float x, float y, float z ); public abstract float GetNoise( float x, float y, float z, float w ); }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace XenAPI { public enum JsonRpcVersion { v1, v2 } internal abstract class JsonRequest { protected JsonRequest(int id, string method, JToken parameters) { this.Id = id; this.Method = method; this.Parameters = parameters; } public static JsonRequest Create(JsonRpcVersion jsonRpcVersion, int id, string method, JToken parameters) { switch (jsonRpcVersion) { case JsonRpcVersion.v2: return new JsonRequestV2(id, method, parameters); default: return new JsonRequestV1(id, method, parameters); } } /// <summary> /// Unique call id. Can be null in JSON_RPC v2.0, but xapi disallows it. /// </summary> [JsonProperty("id", Required = Required.Always)] public int Id { get; private set; } /// <summary> /// The API function to call. /// </summary> [JsonProperty("method", Required = Required.Always)] public string Method { get; private set; } /// <summary> /// Any parameters, optional in JSON-RPC v2.0. /// </summary> [JsonProperty("params", Required = Required.Always)] public JToken Parameters { get; private set; } public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } internal class JsonRequestV1 : JsonRequest { public JsonRequestV1(int id, string method, JToken parameters) : base(id, method, parameters) { } } internal class JsonRequestV2 : JsonRequest { public JsonRequestV2(int id, string method, JToken parameters) : base(id, method, parameters) { } [JsonProperty("jsonrpc", Required = Required.Always)] public string JsonRPC { get { return "2.0"; } } } internal abstract class JsonResponse<T> { [JsonProperty("id", Required = Required.AllowNull)] public int Id = 0; [JsonProperty("result", Required = Required.Default)] public T Result = default(T); public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } internal class JsonResponseV1<T> : JsonResponse<T> { [JsonProperty("error", Required = Required.AllowNull)] public JToken Error = null; } internal class JsonResponseV2<T> : JsonResponse<T> { [JsonProperty("error", Required = Required.DisallowNull)] public JsonResponseV2Error Error = null; [JsonProperty("jsonrpc", Required = Required.Always)] public string JsonRpc = null; } internal class JsonResponseV2Error { [JsonProperty("code", Required = Required.Always)] public int Code = 0; [JsonProperty("message", Required = Required.Always)] public string Message = null; [JsonProperty("data", Required = Required.Default)] public JToken Data = null; public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } public partial class JsonRpcClient { private int _globalId; public JsonRpcClient(string baseUrl) { Url = baseUrl; JsonRpcUrl = new Uri(new Uri(baseUrl), "/jsonrpc").ToString(); JsonRpcVersion = JsonRpcVersion.v1; } /// <summary> /// Fired when a request has been serialized taking as a parameter the call name in RELEASE and the /// Json string in DEBUG mode. /// IMPORTANT: the latter may contain sensitive data, so handle it carefully. /// </summary> public event Action<string> RequestEvent; public JsonRpcVersion JsonRpcVersion { get; set; } public string UserAgent { get; set; } public bool KeepAlive { get; set; } public IWebProxy WebProxy { get; set; } public int Timeout { get; set; } public string ConnectionGroupName { get; set; } public Version ProtocolVersion { get; set; } public bool Expect100Continue { get; set; } public bool AllowAutoRedirect { get; set; } public bool PreAuthenticate { get; set; } public CookieContainer Cookies { get; set; } public string Url { get; private set; } public string JsonRpcUrl { get; private set; } private void Rpc(string callName, JToken parameters, JsonSerializer serializer) { Rpc<object>(callName, parameters, serializer); } private T Rpc<T>(string callName, JToken parameters, JsonSerializer serializer) { // Note that the following method handles an overflow condition by wrapping; // if the _globalId reaches Int32.MaxValue, _globalId + 1 starts over from // Int32.MinValue and no exception is thrown. var id = Interlocked.Increment(ref _globalId); JsonRequest request = JsonRequest.Create(JsonRpcVersion, id, callName, parameters); var webRequest = (HttpWebRequest)WebRequest.Create(JsonRpcUrl); webRequest.Method = "POST"; webRequest.ContentType = "application/json"; webRequest.Accept = "application/json"; webRequest.Timeout = Timeout; webRequest.Proxy = WebProxy; webRequest.KeepAlive = KeepAlive; webRequest.UserAgent = UserAgent; webRequest.ConnectionGroupName = ConnectionGroupName; webRequest.ProtocolVersion = ProtocolVersion; webRequest.ServicePoint.Expect100Continue = Expect100Continue; webRequest.AllowAutoRedirect = AllowAutoRedirect; webRequest.PreAuthenticate = PreAuthenticate; webRequest.AllowWriteStreamBuffering = true; webRequest.CookieContainer = Cookies; // for performance reasons it's preferable to deserialize directly // from the Stream rather than allocating strings inbetween // therefore the latter will be done only in DEBUG mode #if DEBUG var settings = CreateSettings(serializer.Converters); #endif using (var str = webRequest.GetRequestStream()) using (var sw = new StreamWriter(str)) { #if DEBUG string jsonReq = JsonConvert.SerializeObject(request, settings); if (RequestEvent != null) RequestEvent(jsonReq); sw.Write(jsonReq); #else if (RequestEvent != null) RequestEvent(callName); serializer.Serialize(sw, request); #endif sw.Flush(); } using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) { if (webResponse.StatusCode != HttpStatusCode.OK) throw new WebException(webResponse.StatusCode.ToString()); using (var str = webResponse.GetResponseStream()) { if (str == null) throw new WebException(); using (var responseReader = new StreamReader(str)) { switch (JsonRpcVersion) { case JsonRpcVersion.v2: #if DEBUG string json2 = responseReader.ReadToEnd(); var res2 = JsonConvert.DeserializeObject<JsonResponseV2<T>>(json2, settings); #else var res2 = (JsonResponseV2<T>)serializer.Deserialize(responseReader, typeof(JsonResponseV2<T>)); #endif if (res2.Error != null) { var descr = new List<string> {res2.Error.Message}; descr.AddRange(res2.Error.Data.ToObject<string[]>()); throw new Failure(descr); } return res2.Result; default: #if DEBUG string json1 = responseReader.ReadToEnd(); var res1 = JsonConvert.DeserializeObject<JsonResponseV1<T>>(json1, settings); #else var res1 = (JsonResponseV1<T>)serializer.Deserialize(responseReader, typeof(JsonResponseV1<T>)); #endif if (res1.Error != null) { var errorArray = res1.Error.ToObject<string[]>(); if (errorArray != null) throw new Failure(errorArray); } return res1.Result; } } } } } private JsonSerializerSettings CreateSettings(IList<JsonConverter> converters) { return new JsonSerializerSettings { #if DEBUG Formatting = Formatting.Indented, #endif Converters = converters, DateParseHandling = DateParseHandling.None, NullValueHandling = NullValueHandling.Ignore }; } private JsonSerializer CreateSerializer(IList<JsonConverter> converters) { var settings = CreateSettings(converters); return JsonSerializer.Create(settings); } } }
// Copyright 2014 Google 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 UnityEngine; using System.Collections; using System.Collections.Generic; public abstract class GazeTarget : MonoBehaviour{ bool isTarget = false; int gazeStartFrame = -1; float gazeStartTime = -1; int gazeExitFrame = -1; float gazeExitTime =-1; VRInput input; int clickedFrame = -1; int lastUpdateFrame = -1; ///This is the ability to split entry and exit into separate colliders ///TODO: figure out a way to do this intuitively [SerializeField] Collider entryTarget; [SerializeField] Collider exitTarget; [SerializeField] bool invisible = false; [SerializeField] bool clickSound = false; //if the target hides the cursor, should be if it's clickable, but we got too far along, I don't want to find all the instances in this project. public bool Invisible{ get{ return invisible; } set{ invisible = value; } } public Vector3 Position{ get{ return transform.position; } } public void Gaze(VRInput context){ input = context; if(context.Target != this){ context.Target = this; } } public int GazeStartFrame{ get{ return gazeStartFrame; } } public int GazeExitFrame{ get{ return gazeExitFrame; } } public float GazeExitTime{ get{ return gazeExitTime; } } public bool IsTargetThisFrame{ get{ if(lastUpdateFrame != Time.frameCount){ DoUpdate(); } return gazeStartFrame == Time.frameCount; } } public bool IsTarget{ get{ if(lastUpdateFrame != Time.frameCount){ DoUpdate(); } return isTarget; } } public bool IsClicked{ get{ if(lastUpdateFrame != Time.frameCount){ DoUpdate(); } return clickedFrame == Time.frameCount; } } protected virtual void Update(){ if(lastUpdateFrame != Time.frameCount){ DoUpdate(); } } ///we need to make sure this is called after the VRInput updates... protected virtual void DoUpdate(){ lastUpdateFrame = Time.frameCount; if(input != null){ if(input.Target == this){ if(isTarget){ ContinueGaze(); } else{ if(input.TargetCollider == entryTarget){ BeginGaze(); } } VRButton btn = input.PrimaryButton; VRButton.VRButtonState buttonState = btn.State; switch(buttonState){ case VRButton.VRButtonState.Down: Click(btn); break; case VRButton.VRButtonState.Up: OnButtonUp(btn); break; case VRButton.VRButtonState.Held: OnButtonHeld(btn); break; default: case VRButton.VRButtonState.None: break; } } else{ if(isTarget){ EndGaze(); } ///otherwise, we aren't the target and never were. } } } private void Click(VRButton btn){ clickedFrame = Time.frameCount; if(clickSound){ if(UISounds.Instance != null){ UISounds.Instance.PlayClick(); } } OnButtonDown(btn); } private void BeginGaze(){ gazeStartFrame = Time.frameCount; gazeStartTime = Time.time; isTarget = true; OnGazeEnter(); } private void EndGaze(){ gazeExitFrame = Time.frameCount; gazeExitTime = Time.time; isTarget = false; OnGazeExit(Time.time - gazeStartTime); } private void ContinueGaze(){ float gazeTime = Time.time - gazeStartTime; OnGaze(gazeTime); } protected virtual void OnGazeEnter(){ } protected virtual void OnGaze(float gazeDuration){ } protected virtual void OnGazeExit(float gazeDuration){ } protected virtual void OnGazeActivate(){ } protected virtual void OnButtonDown(VRButton button){ } protected virtual void OnButtonUp(VRButton button){ } protected virtual void OnButtonHeld(VRButton button){ } //void OnEnable(){ ///just to be overly cautious, let's make sure we never ever double add, even though .Contains is O(n) //if( !targets.Contains(this) ){ // targets.Add(this); //} //} void OnDisable(){ if(isTarget){ EndGaze(); } ///It's O(n), but less than 100 elements, probably, so who cares //targets.Remove(this); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.IO; using System.Linq; using System.Management.Automation.Internal; /* * * This visitor makes a determination as to whether an operation is safe in a GetPowerShell API Context. * It is modeled on the ConstantValueVisitor with changes which allow those * operations which are deemed safe, rather than constant. The following are differences from * ConstantValueVisitor: * o Because we are going to call for values in ScriptBlockToPowerShell, the * Get*ValueVisitor class is removed * o IsGetPowerShellSafeValueVisitor only needs to determine whether it is safe, we won't return * anything but that determination (vs actually returning a value in the out constantValue parameter * as is found in the ConstantValueVisitor). * o the internal bool members (Checking* members in ConstantValues) aren't needed as those checks are not germane * o VisitExpandableStringExpression may be safe under the proper circumstances * o VisitIndexExpression may be safe under the proper circumstances * o VisitStatementBlock is safe if its component statements are safe * o VisitBinaryExpression is not safe as it allows for a DOS attack * o VisitVariableExpression is generally safe, there are checks outside of this code for ensuring variables actually * have provided references. Those other checks ensure that the variable isn't something like $PID or $HOME, etc., * otherwise it's a safe operation, such as reference to a variable such as $true, or passed parameters. * o VisitTypeExpression is not safe as it enables determining what types are available on the system which * can imply what software has been installed on the system. * o VisitMemberExpression is not safe as allows for the same attack as VisitTypeExpression * o VisitArrayExpression may be safe if its components are safe * o VisitArrayLiteral may be safe if its components are safe * o VisitHashtable may be safe if its components are safe * */ namespace System.Management.Automation.Language { internal class IsSafeValueVisitor : ICustomAstVisitor { public static bool IsAstSafe(Ast ast, GetSafeValueVisitor.SafeValueContext safeValueContext) { IsSafeValueVisitor visitor = new IsSafeValueVisitor(safeValueContext); return visitor.IsAstSafe(ast); } internal IsSafeValueVisitor(GetSafeValueVisitor.SafeValueContext safeValueContext) { _safeValueContext = safeValueContext; } internal bool IsAstSafe(Ast ast) { if ((bool)ast.Accept(this) && _visitCount < MaxVisitCount) { return true; } return false; } // A readonly singleton with the default SafeValueContext. internal static readonly IsSafeValueVisitor Default = new IsSafeValueVisitor(GetSafeValueVisitor.SafeValueContext.Default); // This is a check of the number of visits private uint _visitCount = 0; private const uint MaxVisitCount = 5000; private const int MaxHashtableKeyCount = 500; // Used to determine if we are being called within a GetPowerShell() context, // which does some additional security verification outside of the scope of // what we can verify. private readonly GetSafeValueVisitor.SafeValueContext _safeValueContext; public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return false; } public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return false; } public object VisitParamBlock(ParamBlockAst paramBlockAst) { return false; } public object VisitNamedBlock(NamedBlockAst namedBlockAst) { return false; } public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { return false; } public object VisitAttribute(AttributeAst attributeAst) { return false; } public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { return false; } public object VisitParameter(ParameterAst parameterAst) { return false; } public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return false; } public object VisitIfStatement(IfStatementAst ifStmtAst) { return false; } public object VisitTrap(TrapStatementAst trapStatementAst) { return false; } public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return false; } public object VisitDataStatement(DataStatementAst dataStatementAst) { return false; } public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return false; } public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return false; } public object VisitForStatement(ForStatementAst forStatementAst) { return false; } public object VisitWhileStatement(WhileStatementAst whileStatementAst) { return false; } public object VisitCatchClause(CatchClauseAst catchClauseAst) { return false; } public object VisitTryStatement(TryStatementAst tryStatementAst) { return false; } public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return false; } public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return false; } public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { return false; } public object VisitExitStatement(ExitStatementAst exitStatementAst) { return false; } public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { return false; } public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return false; } public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return false; } public object VisitCommand(CommandAst commandAst) { return false; } public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return false; } public object VisitCommandParameter(CommandParameterAst commandParameterAst) { return false; } public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { return false; } public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { return false; } public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { return false; } public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return false; } public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return false; } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) { return (bool)indexExpressionAst.Index.Accept(this) && (bool)indexExpressionAst.Target.Accept(this); } public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { bool isSafe = true; foreach (var nestedExpression in expandableStringExpressionAst.NestedExpressions) { _visitCount++; if (!(bool)nestedExpression.Accept(this)) { isSafe = false; break; } } return isSafe; } public object VisitStatementBlock(StatementBlockAst statementBlockAst) { bool isSafe = true; foreach (var statement in statementBlockAst.Statements) { _visitCount++; if (statement == null) { isSafe = false; break; } if (!(bool)statement.Accept(this)) { isSafe = false; break; } } return isSafe; } public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); return expr != null && (bool)expr.Accept(this); } public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { // This can be used for a denial of service // Write-Output (((((("AAAAAAAAAAAAAAAAAAAAAA"*2)*2)*2)*2)*2)*2) // Keep on going with that pattern, and we're generating gigabytes of strings. return false; } public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { bool unaryExpressionIsSafe = unaryExpressionAst.TokenKind.HasTrait(TokenFlags.CanConstantFold) && !unaryExpressionAst.TokenKind.HasTrait(TokenFlags.DisallowedInRestrictedMode) && (bool)unaryExpressionAst.Child.Accept(this); if (unaryExpressionIsSafe) { _visitCount++; } return unaryExpressionIsSafe; } public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { var type = convertExpressionAst.Type.TypeName.GetReflectionType(); if (type == null) { return false; } if (!type.IsSafePrimitive()) { // Only do conversions to built-in types - other conversions might not // be safe to optimize. return false; } _visitCount++; return (bool)convertExpressionAst.Child.Accept(this); } public object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) { _visitCount++; return true; } public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { _visitCount++; return true; } public object VisitSubExpression(SubExpressionAst subExpressionAst) { return subExpressionAst.SubExpression.Accept(this); } public object VisitUsingExpression(UsingExpressionAst usingExpressionAst) { // $using:true should be safe - it's silly to write that, but not harmful. _visitCount++; return usingExpressionAst.SubExpression.Accept(this); } public object VisitVariableExpression(VariableExpressionAst variableExpressionAst) { _visitCount++; if (_safeValueContext == GetSafeValueVisitor.SafeValueContext.GetPowerShell) { // GetPowerShell does its own validation of allowed variables in the // context of the entire script block, and then supplies this visitor // with the CommandExpressionAst directly. This // prevents us from evaluating variable safety in this visitor, // so we rely on GetPowerShell's implementation. return true; } if (_safeValueContext == GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) { return variableExpressionAst.IsConstantVariable() || (variableExpressionAst.VariablePath.IsUnqualified && variableExpressionAst.VariablePath.UnqualifiedPath.Equals(SpecialVariables.PSScriptRoot, StringComparison.OrdinalIgnoreCase)); } bool unused = false; return variableExpressionAst.IsSafeVariableReference(null, ref unused); } public object VisitTypeExpression(TypeExpressionAst typeExpressionAst) { // Type expressions are not safe as they allow fingerprinting by providing // a set of types, you can inspect the types in the AppDomain implying which assemblies are in use // and their version return false; } public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) { return false; } public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) { // An Array expression *may* be safe, if its components are safe return arrayExpressionAst.SubExpression.Accept(this); } public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { bool isSafe = arrayLiteralAst.Elements.All(e => (bool)e.Accept(this)); // An array literal is safe return isSafe; } public object VisitHashtable(HashtableAst hashtableAst) { if (hashtableAst.KeyValuePairs.Count > MaxHashtableKeyCount) { return false; } return hashtableAst.KeyValuePairs.All(pair => (bool)pair.Item1.Accept(this) && (bool)pair.Item2.Accept(this)); } public object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { // Returning a ScriptBlock instance itself is OK, bad stuff only happens // when invoking one (which is blocked) return true; } public object VisitParenExpression(ParenExpressionAst parenExpressionAst) { return parenExpressionAst.Pipeline.Accept(this); } } /* * This implementation retrieves the safe value without directly calling the compiler * except in the case of handling the unary operator * ExecutionContext is provided to ensure we can resolve variables */ internal class GetSafeValueVisitor : ICustomAstVisitor { internal enum SafeValueContext { Default, GetPowerShell, ModuleAnalysis } // future proofing private GetSafeValueVisitor() { } public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueContext safeValueContext) { s_context = context; if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) { return ast.Accept(new GetSafeValueVisitor()); } if (safeValueContext == SafeValueContext.ModuleAnalysis) { return null; } throw PSTraceSource.NewArgumentException("ast"); } private static ExecutionContext s_context; public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitParamBlock(ParamBlockAst paramBlockAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitNamedBlock(NamedBlockAst namedBlockAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitAttribute(AttributeAst attributeAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitParameter(ParameterAst parameterAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitIfStatement(IfStatementAst ifStmtAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitTrap(TrapStatementAst trapStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitDataStatement(DataStatementAst dataStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitForStatement(ForStatementAst forStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitWhileStatement(WhileStatementAst whileStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitCatchClause(CatchClauseAst catchClauseAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitTryStatement(TryStatementAst tryStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitBreakStatement(BreakStatementAst breakStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitExitStatement(ExitStatementAst exitStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitCommand(CommandAst commandAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitCommandParameter(CommandParameterAst commandParameterAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitBlockStatement(BlockStatementAst blockStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } // // This is similar to logic used deep in the engine for slicing something that can be sliced // It's recreated here because there isn't really a simple API which can be called for this case. // this can throw, but there really isn't useful information we can add, as the // offending expression will be presented in the case of any failure // private object GetSingleValueFromTarget(object target, object index) { var targetString = target as string; if (targetString != null) { var offset = (int)index; if (Math.Abs(offset) >= targetString.Length) { return null; } return offset >= 0 ? targetString[offset] : targetString[targetString.Length + offset]; } var targetArray = target as object[]; if (targetArray != null) { // this can throw, that just gets percolated back var offset = (int)index; if (Math.Abs(offset) >= targetArray.Length) { return null; } return offset >= 0 ? targetArray[offset] : targetArray[targetArray.Length + offset]; } var targetHashtable = target as Hashtable; if (targetHashtable != null) { return targetHashtable[index]; } // The actual exception doesn't really matter because the caller in ScriptBlockToPowerShell // will present the user with the offending script segment throw new Exception(); } private object GetIndexedValueFromTarget(object target, object index) { var indexArray = index as object[]; return indexArray != null ? ((object[])indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) { // Get the value of the index and value and call the compiler var index = indexExpressionAst.Index.Accept(this); var target = indexExpressionAst.Target.Accept(this); if (index == null || target == null) { throw new ArgumentNullException("indexExpressionAst"); } return GetIndexedValueFromTarget(target, index); } public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { object[] safeValues = new object[expandableStringExpressionAst.NestedExpressions.Count]; // retrieve OFS, and if it doesn't exist set it to space string ofs = null; if (s_context != null) { ofs = s_context.SessionState.PSVariable.GetValue("OFS") as string; } if (ofs == null) { ofs = " "; } for (int offset = 0; offset < safeValues.Length; offset++) { var result = expandableStringExpressionAst.NestedExpressions[offset].Accept(this); // depending on the nested expression we may retrieve a variable, or even need to // execute a sub-expression. The result of which may be returned // as a scalar, array or nested array. If the unwrap of first array doesn't contain a nested // array we can then pass it to string.Join. If it *does* contain an array, // we need to unwrap the inner array and pass *that* to string.Join. // // This means we get the same answer with GetPowerShell() as in the command-line // { echo "abc $true $(1) $(2,3) def" }.Invoke() gives the same answer as // { echo "abc $true $(1) $(2,3) def" }.GetPowerShell().Invoke() // abc True 1 2 3 def // as does { echo "abc $true $(1) $(@(1,2),@(3,4)) def" // which is // abc True 1 System.Object[] System.Object[] def // fortunately, at this point, we're dealing with strings, so whatever the result // from the ToString method of the array (or scalar) elements, that's symmetrical with // a standard scriptblock invocation behavior var resultArray = result as object[]; // In this environment, we can't use $OFS as we might expect. Retrieving OFS // might possibly leak server side info which we don't want, so we'll // assign ' ' as our OFS for purposes of GetPowerShell // Also, this will not call any script implementations of ToString (ala types.clixml) // This *will* result in a different result in those cases. However, to execute some // arbitrary script at this stage would be opening ourselves up to an attack if (resultArray != null) { object[] subExpressionResult = new object[resultArray.Length]; for (int subExpressionOffset = 0; subExpressionOffset < subExpressionResult.Length; subExpressionOffset++) { // check to see if there is an array in our array, object[] subResult = resultArray[subExpressionOffset] as object[]; if (subResult != null) { subExpressionResult[subExpressionOffset] = string.Join(ofs, subResult); } else // it is a scalar, so we can just add it to our collections { subExpressionResult[subExpressionOffset] = resultArray[subExpressionOffset]; } } safeValues[offset] = string.Join(ofs, subExpressionResult); } else { safeValues[offset] = result; } } return StringUtil.Format(expandableStringExpressionAst.FormatExpression, safeValues); } public object VisitStatementBlock(StatementBlockAst statementBlockAst) { ArrayList statementList = new ArrayList(); foreach (var statement in statementBlockAst.Statements) { if (statement != null) { var obj = statement.Accept(this); var enumerator = LanguagePrimitives.GetEnumerator(obj); if (enumerator != null) { while (enumerator.MoveNext()) { statementList.Add(enumerator.Current); } } else { statementList.Add(obj); } } else { throw PSTraceSource.NewArgumentException("ast"); } } return statementList.ToArray(); } public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); if (expr != null) { return expr.Accept(this); } throw PSTraceSource.NewArgumentException("ast"); } public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { // This can be used for a denial of service // Write-Output (((((("AAAAAAAAAAAAAAAAAAAAAA"*2)*2)*2)*2)*2)*2) // Keep on going with that pattern, and we're generating gigabytes of strings. throw PSTraceSource.NewArgumentException("ast"); } public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { if (s_context != null) { return Compiler.GetExpressionValue(unaryExpressionAst, true, s_context, null); } else { throw PSTraceSource.NewArgumentException("ast"); } } public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { // at this point, we know we're safe because we checked both the type and the child, // so now we can just call the compiler and indicate that it's trusted (at this point) if (s_context != null) { return Compiler.GetExpressionValue(convertExpressionAst, true, s_context, null); } else { throw PSTraceSource.NewArgumentException("ast"); } } public object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) { return constantExpressionAst.Value; } public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { return stringConstantExpressionAst.Value; } public object VisitSubExpression(SubExpressionAst subExpressionAst) { return subExpressionAst.SubExpression.Accept(this); } public object VisitUsingExpression(UsingExpressionAst usingExpressionAst) { // $using:true should be safe - it's silly to write that, but not harmful. return usingExpressionAst.SubExpression.Accept(this); } public object VisitVariableExpression(VariableExpressionAst variableExpressionAst) { // There are earlier checks to be sure that we are not using unreferenced variables // this ensures that we only use what was declared in the param block // other variables such as true/false/args etc have been already vetted string name = variableExpressionAst.VariablePath.UnqualifiedPath; if (variableExpressionAst.IsConstantVariable()) { if (name.Equals(SpecialVariables.True, StringComparison.OrdinalIgnoreCase)) return true; if (name.Equals(SpecialVariables.False, StringComparison.OrdinalIgnoreCase)) return false; Diagnostics.Assert(name.Equals(SpecialVariables.Null, StringComparison.OrdinalIgnoreCase), "Unexpected constant variable"); return null; } if (name.Equals(SpecialVariables.PSScriptRoot, StringComparison.OrdinalIgnoreCase)) { var scriptFileName = variableExpressionAst.Extent.File; if (scriptFileName == null) return null; return Path.GetDirectoryName(scriptFileName); } if (s_context != null) { return VariableOps.GetVariableValue(variableExpressionAst.VariablePath, s_context, variableExpressionAst); } throw PSTraceSource.NewArgumentException("ast"); } public object VisitTypeExpression(TypeExpressionAst typeExpressionAst) { // Type expressions are not safe as they allow fingerprinting by providing // a set of types, you can inspect the types in the AppDomain implying which assemblies are in use // and their version throw PSTraceSource.NewArgumentException("ast"); } public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) { // An Array expression *may* be safe, if its components are safe var arrayExpressionAstResult = (object[])arrayExpressionAst.SubExpression.Accept(this); return arrayExpressionAstResult; } public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { // An array literal is safe ArrayList arrayElements = new ArrayList(); foreach (var element in arrayLiteralAst.Elements) { arrayElements.Add(element.Accept(this)); } return arrayElements.ToArray(); } public object VisitHashtable(HashtableAst hashtableAst) { Hashtable hashtable = new Hashtable(StringComparer.CurrentCultureIgnoreCase); foreach (var pair in hashtableAst.KeyValuePairs) { var key = pair.Item1.Accept(this); var value = pair.Item2.Accept(this); hashtable.Add(key, value); } return hashtable; } public object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { return ScriptBlock.Create(scriptBlockExpressionAst.Extent.Text); } public object VisitParenExpression(ParenExpressionAst parenExpressionAst) { return parenExpressionAst.Pipeline.Accept(this); } } }
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using System; using System.Collections; using System.Collections.Generic; using System.Text; using Alachisoft.NCache.Common.Configuration; using Alachisoft.NCache.Runtime.Serialization; using Newtonsoft.Json; using Runtime = Alachisoft.NCache.Runtime; namespace Alachisoft.NCache.Config.Dom { [Serializable] public class CompactClass : ICloneable,ICompactSerializable { private string id; private string name; private string assembly; private string type; private bool isGeneric = false; private string genericId; private string noOfArgs; private bool portable = false; private Hashtable nonCompactFields; public CompactClass() { nonCompactFields = new Hashtable(); } [ConfigurationSection("non-compact-field")] public Attrib[] NonCompactFields { get { List<Attrib> fields = new List<Attrib>(); IDictionaryEnumerator id = nonCompactFields.GetEnumerator(); while (id.MoveNext()) { Attrib temp = id.Value as Attrib; fields.Add(temp); } return fields.ToArray(); } set { nonCompactFields.Clear(); foreach(Attrib field in value) { nonCompactFields.Add(field.Name,field); } } } public Hashtable NonCompactFieldsTable { get { return nonCompactFields; } set { nonCompactFields=value; } } [ConfigurationAttribute("id")] public string ID { get { return id; } set { id = value; } } [ConfigurationAttribute("name")] public string Name { get { return name; } set { name = value; } } [ConfigurationAttribute("assembly")] public string Assembly { get { return assembly; } set { assembly = value; } } [ConfigurationAttribute("type")] public string Type { get { return type; } set { type = value; } } [ConfigurationAttribute("is-generic")] public bool IsGeneric { get { return isGeneric; } set { isGeneric = value; } } [ConfigurationAttribute("generic-id")] public string GenericId { get { return genericId; } set { genericId = value; } } [ConfigurationAttribute("no-of-args")] public string NumberOfArgs { get { return noOfArgs; } set { noOfArgs = value; } } private GenericArgumentType[] _genericArgumentType; private List<GenericArgumentType> _genericArgumentTypeList; [ConfigurationSection("arguments-type")] public GenericArgumentType[] GenericArgumentTypes { get { if (_genericArgumentTypeList != null) return _genericArgumentTypeList.ToArray(); return null; } set { if (_genericArgumentTypeList == null) _genericArgumentTypeList = new List<GenericArgumentType>(); _genericArgumentTypeList.Clear(); if (value != null) { _genericArgumentTypeList.AddRange(value); } } } [JsonIgnore] public List<GenericArgumentType> GenericArgumentTypeList { get { return _genericArgumentTypeList; } set { _genericArgumentTypeList = value; } } public bool Portable { get { return portable; } } #region ICloneable Members public object Clone() { CompactClass compactClass = new CompactClass(); compactClass.Name = Name != null ? (string)Name.Clone() : null; compactClass.ID = ID != null ? (string)ID.Clone() : null; compactClass.Assembly = Assembly != null ? (string) Assembly.Clone() : null; compactClass.Type = Type != null ? (string)Type.Clone() : null; compactClass.IsGeneric = IsGeneric; compactClass.GenericId = GenericId != null ? (string)GenericId.Clone() : null; compactClass.NumberOfArgs = NumberOfArgs != null ? (string)NumberOfArgs.Clone() : null; compactClass.GenericArgumentTypes = GenericArgumentTypes != null ? (GenericArgumentType[])GenericArgumentTypes.Clone() : null; compactClass.NonCompactFields = NonCompactFields != null ? (Attrib[])NonCompactFields.Clone() : null; return compactClass; } #endregion #region ICompactSerializable Members public void Deserialize(Runtime.Serialization.IO.CompactReader reader) { id = reader.ReadObject() as string; name = reader.ReadObject() as string; assembly = reader.ReadObject() as string; type = reader.ReadObject() as string; isGeneric = reader.ReadBoolean(); genericId = reader.ReadObject() as string; noOfArgs = reader.ReadObject() as string; portable = reader.ReadBoolean(); nonCompactFields = reader.ReadObject() as Hashtable; _genericArgumentTypeList = reader.ReadObject() as List<GenericArgumentType>; } public void Serialize(Runtime.Serialization.IO.CompactWriter writer) { writer.WriteObject(id); writer.WriteObject(name); writer.WriteObject(assembly); writer.WriteObject(type); writer.Write(isGeneric); writer.WriteObject(genericId); writer.WriteObject(noOfArgs); writer.Write(portable); writer.WriteObject(nonCompactFields); writer.WriteObject(_genericArgumentTypeList); } #endregion } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.Courier { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Contracts; using InternalMessages; using Newtonsoft.Json; using Util; public class RoutingSlipEventPublisher : IRoutingSlipEventPublisher { readonly HostInfo _host; readonly IPublishEndpoint _publishEndpoint; readonly RoutingSlip _routingSlip; readonly ISendEndpointProvider _sendEndpointProvider; static RoutingSlipEventPublisher() { RoutingSlipEventCorrelation.ConfigureMessageCorrelation(); } public RoutingSlipEventPublisher(CompensateContext compensateContext, RoutingSlip routingSlip) : this(compensateContext, compensateContext, routingSlip) { _sendEndpointProvider = compensateContext; _publishEndpoint = compensateContext; _routingSlip = routingSlip; _host = compensateContext.Host; } public RoutingSlipEventPublisher(ExecuteContext executeContext, RoutingSlip routingSlip) : this(executeContext, executeContext, routingSlip) { _sendEndpointProvider = executeContext; _publishEndpoint = executeContext; _routingSlip = routingSlip; _host = executeContext.Host; } public RoutingSlipEventPublisher(ISendEndpointProvider sendEndpointProvider, IPublishEndpoint publishEndpoint, RoutingSlip routingSlip) { _sendEndpointProvider = sendEndpointProvider; _publishEndpoint = publishEndpoint; _routingSlip = routingSlip; _host = HostMetadataCache.Host; } public Task PublishRoutingSlipCompleted(DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables) { return PublishEvent<RoutingSlipCompleted>(RoutingSlipEvents.Completed, contents => new RoutingSlipCompletedMessage( _routingSlip.TrackingNumber, timestamp, duration, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject() )); } public Task PublishRoutingSlipFaulted(DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, params ActivityException[] exceptions) { return PublishEvent<RoutingSlipFaulted>(RoutingSlipEvents.Faulted, contents => new RoutingSlipFaultedMessage( _routingSlip.TrackingNumber, timestamp, duration, exceptions, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject() )); } public Task PublishRoutingSlipActivityCompleted(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, IDictionary<string, object> arguments, IDictionary<string, object> data) { return PublishEvent<RoutingSlipActivityCompleted>(RoutingSlipEvents.ActivityCompleted, contents => new RoutingSlipActivityCompletedMessage( _host, _routingSlip.TrackingNumber, activityName, executionId, timestamp, duration, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)) ? arguments : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Data)) ? data : GetEmptyObject())); } public Task PublishRoutingSlipActivityFaulted(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, ExceptionInfo exceptionInfo, IDictionary<string, object> variables, IDictionary<string, object> arguments) { return PublishEvent<RoutingSlipActivityFaulted>(RoutingSlipEvents.ActivityFaulted, contents => new RoutingSlipActivityFaultedMessage( _host, _routingSlip.TrackingNumber, activityName, executionId, timestamp, duration, exceptionInfo, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)) ? arguments : GetEmptyObject())); } public Task PublishRoutingSlipActivityCompensated(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, IDictionary<string, object> data) { return PublishEvent<RoutingSlipActivityCompensated>(RoutingSlipEvents.ActivityCompensated, contents => new RoutingSlipActivityCompensatedMessage( _host, _routingSlip.TrackingNumber, activityName, executionId, timestamp, duration, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)) ? data : GetEmptyObject())); } public Task PublishRoutingSlipRevised(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, IList<Activity> itinerary, IList<Activity> previousItinerary) { return PublishEvent<RoutingSlipRevised>(RoutingSlipEvents.Revised, contents => new RoutingSlipRevisedMessage( _host, _routingSlip.TrackingNumber, activityName, executionId, timestamp, duration, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Itinerary)) ? itinerary : Enumerable.Empty<Activity>(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Itinerary)) ? previousItinerary : Enumerable.Empty<Activity>())); } public Task PublishRoutingSlipTerminated(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, IDictionary<string, object> variables, IList<Activity> previousItinerary) { return PublishEvent<RoutingSlipTerminated>(RoutingSlipEvents.Terminated, contents => new RoutingSlipTerminatedMessage( _host, _routingSlip.TrackingNumber, activityName, executionId, timestamp, duration, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Itinerary)) ? previousItinerary : Enumerable.Empty<Activity>())); } public Task PublishRoutingSlipActivityCompensationFailed(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, DateTime failureTimestamp, TimeSpan routingSlipDuration, ExceptionInfo exceptionInfo, IDictionary<string, object> variables, IDictionary<string, object> data) { return PublishEvent(RoutingSlipEvents.ActivityCompensationFailed | RoutingSlipEvents.CompensationFailed, contents => new CompensationFailed( _host, _routingSlip.TrackingNumber, activityName, executionId, timestamp, duration, failureTimestamp, routingSlipDuration, exceptionInfo, (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)) ? variables : GetEmptyObject(), (contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Data)) ? data : GetEmptyObject())); } static IDictionary<string, object> GetEmptyObject() { return JsonConvert.DeserializeObject<IDictionary<string, object>>("{}"); } async Task PublishEvent<T>(RoutingSlipEvents eventFlag, Func<RoutingSlipEventContents, T> messageFactory) where T : class { if (_routingSlip.Subscriptions.Any()) { foreach (var subscription in _routingSlip.Subscriptions) { if (subscription.Events == RoutingSlipEvents.All || subscription.Events.HasFlag(eventFlag)) { var endpoint = await _sendEndpointProvider.GetSendEndpoint(subscription.Address).ConfigureAwait(false); var subscriptionMessage = messageFactory(subscription.Include); await endpoint.Send(subscriptionMessage).ConfigureAwait(false); } } } else await _publishEndpoint.Publish(messageFactory(RoutingSlipEventContents.All)).ConfigureAwait(false); } } }
using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Query; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; using Microsoft.Crm.Sdk; namespace DynamicsNode { public class CRMBridge { private IOrganizationService _service; private Dictionary<string, EntityMetadata> _metadataCache = new Dictionary<string, EntityMetadata>(); public CRMBridge(string connectionString, bool useFake) { // TODO: Fix this // This is to force .net framework to load the Microsoft.Crm.Sdk assembly var x = new WhoAmIRequest(); if (useFake) { _service = new FakeService(connectionString); } else { _service = new CrmService(connectionString); } } public object Delete(dynamic options) { string entityName = options.entityName; Guid id = new Guid(options.id); _service.Delete(entityName, id); return null; } public object Create(dynamic entity) { Guid createdId = Guid.Empty; Entity e = ConvertFromDynamic(entity); createdId = _service.Create(e); return createdId; } public void Update(dynamic entity) { // convert the values to an entity type Entity e = ConvertFromDynamic(entity); _service.Update(e); } public object Retrieve(dynamic options) { object[] result = null; string entityName = options.entityName; Guid id = new Guid(options.id); ColumnSet columns = new ColumnSet(true); // convert the columns option to the right type if (options.columns.GetType() == typeof(bool)) { columns = new ColumnSet((bool)options.columns); } else { string[] cols = new string[options.columns.Length]; ((object[])options.columns).CopyTo(cols, 0); columns = new ColumnSet(cols); } Entity entityRecord = null; entityRecord = _service.Retrieve(entityName, id, columns); if (entityRecord != null) { result = Convert(entityRecord); } return result; } private QueryExpression FetchXmlToQueryExpression(string fetchXml) { return ((FetchXmlToQueryExpressionResponse)_service.Execute(new FetchXmlToQueryExpressionRequest() { FetchXml = fetchXml })).Query; } public object RetrieveMultiple(string fetchXml) { var result = new List<object>(); // validate parameters if (fetchXml == null || string.IsNullOrWhiteSpace(fetchXml)) throw new Exception("fetchXml not specified"); var query = FetchXmlToQueryExpression(fetchXml); var foundRecords = _service.RetrieveMultiple(query); if (foundRecords != null && foundRecords.Entities != null && foundRecords.Entities.Count > 0) { for (int i = 0; i < foundRecords.Entities.Count; i++) { var record = foundRecords.Entities[i]; var convertedRecord = Convert(record); result.Add(convertedRecord); } } return result.ToArray(); } public object Associate(dynamic options) { string entityName = options.entityName; Guid entityId = new Guid(options.entityId); Relationship relationship = new Relationship(options.relationship); var relatedEntitiesList = new List<EntityReference>(); foreach (var rel in options.relatedEntities) { relatedEntitiesList.Add(new EntityReference(rel.entityName, new Guid(rel.entityId))); } EntityReferenceCollection relatedEntities = new EntityReferenceCollection(relatedEntitiesList); _service.Associate(entityName, entityId, relationship, relatedEntities); return null; } public object Disassociate(dynamic options) { string entityName = options.entityName; Guid entityId = new Guid(options.entityId); Relationship relationship = new Relationship(options.relationship); var relatedEntitiesList = new List<EntityReference>(); foreach (var rel in options.relatedEntities) { relatedEntitiesList.Add(new EntityReference(rel.entityName, new Guid(rel.entityId))); } EntityReferenceCollection relatedEntities = new EntityReferenceCollection(relatedEntitiesList); _service.Disassociate(entityName, entityId, relationship, relatedEntities); return null; } private object[] Convert(Entity entityRecord) { var values = new List<object>(); string[] entityAttributes = new string[entityRecord.Attributes.Keys.Count]; entityRecord.Attributes.Keys.CopyTo(entityAttributes, 0); for (int i = 0; i < entityAttributes.Length; i++) { string attributeName = entityAttributes[i]; object attributeValue = entityRecord.Attributes[entityAttributes[i]]; if (attributeValue.GetType() == typeof(EntityReference)) { var er = (EntityReference)attributeValue; values.Add(new object[] { attributeName, er.Id }); values.Add(new object[] { string.Format("{0}_name", attributeName), er.Name }); values.Add(new object[] { string.Format("{0}_type", attributeName), er.LogicalName }); } else if (attributeValue.GetType() == typeof(OptionSetValue)) { var os = (OptionSetValue)attributeValue; values.Add(new object[] { attributeName, os.Value }); // Add attribute text from metadata } else { values.Add(new object[] { attributeName, attributeValue }); } } return values.ToArray(); } public OrganizationResponse Execute(dynamic request) { OrganizationRequest objRequest = ConvertFromDynamic(request); OrganizationResponse response = _service.Execute(objRequest); return response; } private Assembly GetAssembly(string name) { var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => string.Compare(x.GetName().Name,name,true)==0); if (assembly == null) { // TODO: Try to load the assembly from a file } return assembly; } private object ConvertFromDynamic(ExpandoObject value) { object converted = null; var valueDictionary = (IDictionary<string, object>)value; string typeName = (string)valueDictionary["__typeName"]; if (string.IsNullOrEmpty(typeName)) throw new Exception("Type Name not specified"); // Convert from a simple object if (typeName==typeof(Guid).FullName) { string propValue = (string)valueDictionary["Value"]; converted = new Guid(propValue); } else if (typeName == typeof(Decimal).FullName) { object propValue = valueDictionary["Value"]; converted = System.Convert.ToDecimal(propValue); } else { // Create an instance of the object to return converted = GetTypeInstance(typeName); Type convertedType = converted.GetType(); foreach (var prop in valueDictionary) { if (prop.Value != null) { var propDef = convertedType.GetProperty(prop.Key); if (propDef != null) { object propValue = prop.Value; Type propValueType = prop.Value.GetType(); if (propDef.PropertyType == typeof(AttributeCollection)) { if (propValueType != typeof(ExpandoObject)) throw new Exception(string.Format("Can't convert from {0} to AttributeCollection", propValueType.Name)); propValue = ConvertFromDynamicToAttributeCollection((ExpandoObject)propValue); } else if (propValueType == typeof(ExpandoObject)) { var propExpando = (ExpandoObject)propValue; propValue = ConvertFromDynamic(propExpando); } else if (propValueType.IsArray) { propValue = ConvertFromArray((Array)prop.Value); } else if (propDef.PropertyType == typeof(Guid) && propValueType == typeof(string)) { propValue = new Guid((string)propValue); } propDef.SetValue(converted, propValue); } } } } return converted; } private AttributeCollection ConvertFromDynamicToAttributeCollection(ExpandoObject value) { AttributeCollection retVal = null; if (value != null) { var valueDictionary = (IDictionary<string, object>)value; if (valueDictionary.Keys.Count > 0) retVal = new AttributeCollection(); foreach (var prop in valueDictionary) { object convertedValue = prop.Value; if (prop.Value != null) { // Convert values var propValueType = prop.Value.GetType(); if (propValueType == typeof(ExpandoObject)) { convertedValue = ConvertFromDynamic((ExpandoObject)prop.Value); } else if (propValueType.IsArray) { convertedValue = ConvertFromArray((Array)prop.Value); } else if (propValueType == typeof(string)) { Guid guidValue; if (Guid.TryParse((string)prop.Value, out guidValue)) { convertedValue = guidValue; } } } retVal.Add(prop.Key, convertedValue); } } return retVal; } private object ConvertFromArray(Array arrayToConvert) { object retVal = null; if (arrayToConvert != null) { var convertedItems = new List<object>(); Type lastItemType = null; bool sameTypeArray = true; foreach (var item in arrayToConvert) { object convertedValue = null; if (item != null) { if (item.GetType() != typeof(ExpandoObject)) throw new Exception("The element in the array is not an ExpandoObject.Check the PartyList attributes in your entity"); var expandoItem = (ExpandoObject)item; convertedValue = ConvertFromDynamic(expandoItem); if (convertedValue != null) { if (lastItemType != null && lastItemType != convertedValue.GetType()) sameTypeArray = false; lastItemType = convertedValue.GetType(); } } convertedItems.Add(convertedValue); } if (sameTypeArray && lastItemType != null) { // If all the items in the array are ExpandoObjects and their underlying type is the same, then return a specific type array retVal = Array.CreateInstance(lastItemType, convertedItems.Count); Array.Copy(convertedItems.ToArray(), (Array)retVal, convertedItems.Count); } else { retVal = convertedItems.ToArray(); } } return retVal; } private object GetTypeInstance(string typeFullName) { object typeInstance; var typeNameParts = typeFullName.Split(','); string assemblyName = typeNameParts[0], className = typeNameParts[1]; var assembly = GetAssembly(assemblyName); if (assembly == null) throw new Exception(string.Format("Can't find assembly '{0}'", assemblyName)); typeInstance = assembly.CreateInstance(className); if (typeInstance == null) throw new Exception(string.Format("Can't create class of type '{0}'", typeFullName)); return typeInstance; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// Container for the parameters to the RestoreDBInstanceToPointInTime operation. /// <para> Restores a DB Instance to an arbitrary point-in-time. Users can restore to any point in time before the latestRestorableTime for up /// to backupRetentionPeriod days. The target database is created from the source database with the same configuration as the original database /// except that the DB instance is created with the default DB security group. </para> /// </summary> /// <seealso cref="Amazon.RDS.AmazonRDS.RestoreDBInstanceToPointInTime"/> public class RestoreDBInstanceToPointInTimeRequest : AmazonWebServiceRequest { private string sourceDBInstanceIdentifier; private string targetDBInstanceIdentifier; private DateTime? restoreTime; private bool? useLatestRestorableTime; private string dBInstanceClass; private int? port; private string availabilityZone; private string dBSubnetGroupName; private bool? multiAZ; private bool? publiclyAccessible; private bool? autoMinorVersionUpgrade; private string licenseModel; private string dBName; private string engine; private int? iops; private string optionGroupName; /// <summary> /// The identifier of the source DB Instance from which to restore. Constraints: <ul> <li>Must be the identifier of an existing database /// instance</li> <li>Must contain from 1 to 63 alphanumeric characters or hyphens</li> <li>First character must be a letter</li> <li>Cannot end /// with a hyphen or contain two consecutive hyphens</li> </ul> /// /// </summary> public string SourceDBInstanceIdentifier { get { return this.sourceDBInstanceIdentifier; } set { this.sourceDBInstanceIdentifier = value; } } /// <summary> /// Sets the SourceDBInstanceIdentifier property /// </summary> /// <param name="sourceDBInstanceIdentifier">The value to set for the SourceDBInstanceIdentifier property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithSourceDBInstanceIdentifier(string sourceDBInstanceIdentifier) { this.sourceDBInstanceIdentifier = sourceDBInstanceIdentifier; return this; } // Check to see if SourceDBInstanceIdentifier property is set internal bool IsSetSourceDBInstanceIdentifier() { return this.sourceDBInstanceIdentifier != null; } /// <summary> /// The name of the new database instance to be created. Constraints: <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens</li> /// <li>First character must be a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li> </ul> /// /// </summary> public string TargetDBInstanceIdentifier { get { return this.targetDBInstanceIdentifier; } set { this.targetDBInstanceIdentifier = value; } } /// <summary> /// Sets the TargetDBInstanceIdentifier property /// </summary> /// <param name="targetDBInstanceIdentifier">The value to set for the TargetDBInstanceIdentifier property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithTargetDBInstanceIdentifier(string targetDBInstanceIdentifier) { this.targetDBInstanceIdentifier = targetDBInstanceIdentifier; return this; } // Check to see if TargetDBInstanceIdentifier property is set internal bool IsSetTargetDBInstanceIdentifier() { return this.targetDBInstanceIdentifier != null; } /// <summary> /// The date and time to restore from. Valid Values: Value must be a UTC time Constraints: <ul> <li>Must be before the latest restorable time /// for the DB Instance</li> <li>Cannot be specified if UseLatestRestorableTime parameter is true</li> </ul> Example: /// <c>2009-09-07T23:45:00Z</c> /// /// </summary> public DateTime RestoreTime { get { return this.restoreTime ?? default(DateTime); } set { this.restoreTime = value; } } /// <summary> /// Sets the RestoreTime property /// </summary> /// <param name="restoreTime">The value to set for the RestoreTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithRestoreTime(DateTime restoreTime) { this.restoreTime = restoreTime; return this; } // Check to see if RestoreTime property is set internal bool IsSetRestoreTime() { return this.restoreTime.HasValue; } /// <summary> /// Specifies whether (<c>true</c>) or not (<c>false</c>) the DB Instance is restored from the latest backup time. Default: <c>false</c> /// Constraints: Cannot be specified if RestoreTime parameter is provided. /// /// </summary> public bool UseLatestRestorableTime { get { return this.useLatestRestorableTime ?? default(bool); } set { this.useLatestRestorableTime = value; } } /// <summary> /// Sets the UseLatestRestorableTime property /// </summary> /// <param name="useLatestRestorableTime">The value to set for the UseLatestRestorableTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithUseLatestRestorableTime(bool useLatestRestorableTime) { this.useLatestRestorableTime = useLatestRestorableTime; return this; } // Check to see if UseLatestRestorableTime property is set internal bool IsSetUseLatestRestorableTime() { return this.useLatestRestorableTime.HasValue; } /// <summary> /// The compute and memory capacity of the Amazon RDS DB instance. Valid Values: <c>db.t1.micro | db.m1.small | db.m1.medium | db.m1.large | /// db.m1.xlarge | db.m2.2xlarge | db.m2.4xlarge</c> Default: The same DBInstanceClass as the original DB Instance. /// /// </summary> public string DBInstanceClass { get { return this.dBInstanceClass; } set { this.dBInstanceClass = value; } } /// <summary> /// Sets the DBInstanceClass property /// </summary> /// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithDBInstanceClass(string dBInstanceClass) { this.dBInstanceClass = dBInstanceClass; return this; } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this.dBInstanceClass != null; } /// <summary> /// The port number on which the database accepts connections. Constraints: Value must be <c>1150-65535</c> Default: The same port as the /// original DB Instance. /// /// </summary> public int Port { get { return this.port ?? default(int); } set { this.port = value; } } /// <summary> /// Sets the Port property /// </summary> /// <param name="port">The value to set for the Port property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithPort(int port) { this.port = port; return this; } // Check to see if Port property is set internal bool IsSetPort() { return this.port.HasValue; } /// <summary> /// The EC2 Availability Zone that the database instance will be created in. Default: A random, system-chosen Availability Zone. Constraint: You /// cannot specify the AvailabilityZone parameter if the MultiAZ parameter is set to true. Example: <c>us-east-1a</c> /// /// </summary> public string AvailabilityZone { get { return this.availabilityZone; } set { this.availabilityZone = value; } } /// <summary> /// Sets the AvailabilityZone property /// </summary> /// <param name="availabilityZone">The value to set for the AvailabilityZone property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithAvailabilityZone(string availabilityZone) { this.availabilityZone = availabilityZone; return this; } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this.availabilityZone != null; } /// <summary> /// The DB subnet group name to use for the new instance. /// /// </summary> public string DBSubnetGroupName { get { return this.dBSubnetGroupName; } set { this.dBSubnetGroupName = value; } } /// <summary> /// Sets the DBSubnetGroupName property /// </summary> /// <param name="dBSubnetGroupName">The value to set for the DBSubnetGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithDBSubnetGroupName(string dBSubnetGroupName) { this.dBSubnetGroupName = dBSubnetGroupName; return this; } // Check to see if DBSubnetGroupName property is set internal bool IsSetDBSubnetGroupName() { return this.dBSubnetGroupName != null; } /// <summary> /// Specifies if the DB Instance is a Multi-AZ deployment. Constraint: You cannot specify the AvailabilityZone parameter if the MultiAZ /// parameter is set to <c>true</c>. /// /// </summary> public bool MultiAZ { get { return this.multiAZ ?? default(bool); } set { this.multiAZ = value; } } /// <summary> /// Sets the MultiAZ property /// </summary> /// <param name="multiAZ">The value to set for the MultiAZ property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithMultiAZ(bool multiAZ) { this.multiAZ = multiAZ; return this; } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this.multiAZ.HasValue; } /// <summary> /// Specifies the accessibility options for the DB Instance. A value of true specifies an Internet-facing instance with a publicly resolvable /// DNS name, which resolves to a public IP address. A value of false specifies an internal instance with a DNS name that resolves to a private /// IP address. Default: The default behavior varies depending on whether a VPC has been requested or not. The following list shows the default /// behavior in each case. <ul> <li><b>Default VPC:</b>true</li> <li><b>VPC:</b>false</li> </ul> If no DB subnet group has been specified as /// part of the request and the PubliclyAccessible value has not been set, the DB instance will be publicly accessible. If a specific DB subnet /// group has been specified as part of the request and the PubliclyAccessible value has not been set, the DB instance will be private. /// /// </summary> public bool PubliclyAccessible { get { return this.publiclyAccessible ?? default(bool); } set { this.publiclyAccessible = value; } } /// <summary> /// Sets the PubliclyAccessible property /// </summary> /// <param name="publiclyAccessible">The value to set for the PubliclyAccessible property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithPubliclyAccessible(bool publiclyAccessible) { this.publiclyAccessible = publiclyAccessible; return this; } // Check to see if PubliclyAccessible property is set internal bool IsSetPubliclyAccessible() { return this.publiclyAccessible.HasValue; } /// <summary> /// Indicates that minor version upgrades will be applied automatically to the DB Instance during the maintenance window. /// /// </summary> public bool AutoMinorVersionUpgrade { get { return this.autoMinorVersionUpgrade ?? default(bool); } set { this.autoMinorVersionUpgrade = value; } } /// <summary> /// Sets the AutoMinorVersionUpgrade property /// </summary> /// <param name="autoMinorVersionUpgrade">The value to set for the AutoMinorVersionUpgrade property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithAutoMinorVersionUpgrade(bool autoMinorVersionUpgrade) { this.autoMinorVersionUpgrade = autoMinorVersionUpgrade; return this; } // Check to see if AutoMinorVersionUpgrade property is set internal bool IsSetAutoMinorVersionUpgrade() { return this.autoMinorVersionUpgrade.HasValue; } /// <summary> /// License model information for the restored DB Instance. Default: Same as source. Valid values: <c>license-included</c> | /// <c>bring-your-own-license</c> | <c>general-public-license</c> /// /// </summary> public string LicenseModel { get { return this.licenseModel; } set { this.licenseModel = value; } } /// <summary> /// Sets the LicenseModel property /// </summary> /// <param name="licenseModel">The value to set for the LicenseModel property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithLicenseModel(string licenseModel) { this.licenseModel = licenseModel; return this; } // Check to see if LicenseModel property is set internal bool IsSetLicenseModel() { return this.licenseModel != null; } /// <summary> /// The database name for the restored DB Instance. <note> This parameter is not used for the MySQL engine. </note> /// /// </summary> public string DBName { get { return this.dBName; } set { this.dBName = value; } } /// <summary> /// Sets the DBName property /// </summary> /// <param name="dBName">The value to set for the DBName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithDBName(string dBName) { this.dBName = dBName; return this; } // Check to see if DBName property is set internal bool IsSetDBName() { return this.dBName != null; } /// <summary> /// The database engine to use for the new instance. Default: The same as source Constraint: Must be compatible with the engine of the source /// Example: <c>oracle-ee</c> /// /// </summary> public string Engine { get { return this.engine; } set { this.engine = value; } } /// <summary> /// Sets the Engine property /// </summary> /// <param name="engine">The value to set for the Engine property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithEngine(string engine) { this.engine = engine; return this; } // Check to see if Engine property is set internal bool IsSetEngine() { return this.engine != null; } /// <summary> /// The amount of Provisioned IOPS (input/output operations per second) to be initially allocated for the DB Instance. Constraints: Must be an /// integer greater than 1000. /// /// </summary> public int Iops { get { return this.iops ?? default(int); } set { this.iops = value; } } /// <summary> /// Sets the Iops property /// </summary> /// <param name="iops">The value to set for the Iops property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithIops(int iops) { this.iops = iops; return this; } // Check to see if Iops property is set internal bool IsSetIops() { return this.iops.HasValue; } /// <summary> /// The name of the option group to be used for the restored DB instance. <!-- Note that persistent options, such as the TDE_SQLServer option /// for Microsoft SQL Server, cannot be removed from an option group while DB instances are associated with the option group. --> Permanent /// options, such as the TDE option for Oracle Advanced Security TDE, cannot be removed from an option group, and that option group cannot be /// removed from a DB instance once it is associated with a DB instance /// /// </summary> public string OptionGroupName { get { return this.optionGroupName; } set { this.optionGroupName = value; } } /// <summary> /// Sets the OptionGroupName property /// </summary> /// <param name="optionGroupName">The value to set for the OptionGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RestoreDBInstanceToPointInTimeRequest WithOptionGroupName(string optionGroupName) { this.optionGroupName = optionGroupName; return this; } // Check to see if OptionGroupName property is set internal bool IsSetOptionGroupName() { return this.optionGroupName != null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.IO; using System.Text; using System.Globalization; using System.Collections.Generic; namespace System.Xml { // Represents an entire document. An XmlDocument contains XML data. public class XmlDocument : XmlNode { private XmlImplementation implementation; private DomNameTable domNameTable; // hash table of XmlName private XmlLinkedNode lastChild; private XmlNamedNodeMap entities; private Dictionary<string, List<WeakReference<XmlElement>>> htElementIdMap; //This variable represents the actual loading status. Since, IsLoading will //be manipulated sometimes for adding content to EntityReference this variable //has been added which would always represent the loading status of document. private bool actualLoadingStatus; private XmlNodeChangedEventHandler onNodeInsertingDelegate; private XmlNodeChangedEventHandler onNodeInsertedDelegate; private XmlNodeChangedEventHandler onNodeRemovingDelegate; private XmlNodeChangedEventHandler onNodeRemovedDelegate; private XmlNodeChangedEventHandler onNodeChangingDelegate; private XmlNodeChangedEventHandler onNodeChangedDelegate; // false if there are no ent-ref present, true if ent-ref nodes are or were present (i.e. if all ent-ref were removed, the doc will not clear this flag) internal bool fEntRefNodesPresent; internal bool fCDataNodesPresent; private bool preserveWhitespace; private bool isLoading; // special name strings for internal string strDocumentName; internal string strDocumentFragmentName; internal string strCommentName; internal string strTextName; internal string strCDataSectionName; internal string strEntityName; internal string strID; internal string strXmlns; internal string strXml; internal string strSpace; internal string strLang; internal string strEmpty; internal string strNonSignificantWhitespaceName; internal string strSignificantWhitespaceName; internal string strReservedXmlns; internal string strReservedXml; internal String baseURI; internal object objLock; static internal EmptyEnumerator EmptyEnumerator = new EmptyEnumerator(); // Initializes a new instance of the XmlDocument class. public XmlDocument() : this(new XmlImplementation()) { } // Initializes a new instance // of the XmlDocument class with the specified XmlNameTable. public XmlDocument(XmlNameTable nt) : this(new XmlImplementation(nt)) { } protected internal XmlDocument(XmlImplementation imp) : base() { implementation = imp; domNameTable = new DomNameTable(this); // force the following string instances to be default in the nametable XmlNameTable nt = this.NameTable; nt.Add(string.Empty); strDocumentName = nt.Add("#document"); strDocumentFragmentName = nt.Add("#document-fragment"); strCommentName = nt.Add("#comment"); strTextName = nt.Add("#text"); strCDataSectionName = nt.Add("#cdata-section"); strEntityName = nt.Add("#entity"); strID = nt.Add("id"); strNonSignificantWhitespaceName = nt.Add("#whitespace"); strSignificantWhitespaceName = nt.Add("#significant-whitespace"); strXmlns = nt.Add("xmlns"); strXml = nt.Add("xml"); strSpace = nt.Add("space"); strLang = nt.Add("lang"); strReservedXmlns = nt.Add(XmlConst.ReservedNsXmlNs); strReservedXml = nt.Add(XmlConst.ReservedNsXml); strEmpty = nt.Add(String.Empty); baseURI = String.Empty; objLock = new object(); } // NOTE: This does not correctly check start name char, but we cannot change it since it would be a breaking change. internal static void CheckName(String name) { int endPos = ValidateNames.ParseNmtoken(name, 0); if (endPos < name.Length) { throw new XmlException(SR.Format(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(name, endPos))); } } internal XmlName AddXmlName(string prefix, string localName, string namespaceURI) { XmlName n = domNameTable.AddName(prefix, localName, namespaceURI); Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)); Debug.Assert(n.LocalName == localName); Debug.Assert((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)); return n; } internal XmlName GetXmlName(string prefix, string localName, string namespaceURI) { XmlName n = domNameTable.GetName(prefix, localName, namespaceURI); Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix))); Debug.Assert(n == null || n.LocalName == localName); Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI))); return n; } internal XmlName AddAttrXmlName(string prefix, string localName, string namespaceURI) { XmlName xmlName = AddXmlName(prefix, localName, namespaceURI); Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix)); Debug.Assert(xmlName.LocalName == localName); Debug.Assert((namespaceURI == null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI)); if (!this.IsLoading) { // Use atomized versions instead of prefix, localName and nsURI object oPrefix = xmlName.Prefix; object oNamespaceURI = xmlName.NamespaceURI; object oLocalName = xmlName.LocalName; if ((oPrefix == (object)strXmlns || (oPrefix == (object)strEmpty && oLocalName == (object)strXmlns)) ^ (oNamespaceURI == (object)strReservedXmlns)) throw new ArgumentException(SR.Format(SR.Xdom_Attr_Reserved_XmlNS, namespaceURI)); } return xmlName; } // This function returns null because it is implication of removing schema. // If removed more methods would have to be removed as well and it would make adding schema back much harder. internal XmlName GetIDInfoByElement(XmlName eleName) { return null; } private WeakReference<XmlElement> GetElement(List<WeakReference<XmlElement>> elementList, XmlElement elem) { List<WeakReference<XmlElement>> gcElemRefs = new List<WeakReference<XmlElement>>(); foreach (WeakReference<XmlElement> elemRef in elementList) { XmlElement target; if (!elemRef.TryGetTarget(out target)) //take notes on the garbage collected nodes gcElemRefs.Add(elemRef); else { if (target == elem) return elemRef; } } //Clear out the gced elements foreach (WeakReference<XmlElement> elemRef in gcElemRefs) elementList.Remove(elemRef); return null; } internal void AddElementWithId(string id, XmlElement elem) { if (htElementIdMap == null || !htElementIdMap.ContainsKey(id)) { if (htElementIdMap == null) htElementIdMap = new Dictionary<string, List<WeakReference<XmlElement>>>(); List<WeakReference<XmlElement>> elementList = new List<WeakReference<XmlElement>>(); elementList.Add(new WeakReference<XmlElement>(elem)); htElementIdMap.Add(id, elementList); } else { // there are other element(s) that has the same id List<WeakReference<XmlElement>> elementList = htElementIdMap[id]; if (GetElement(elementList, elem) == null) elementList.Add(new WeakReference<XmlElement>(elem)); } } internal void RemoveElementWithId(string id, XmlElement elem) { if (htElementIdMap != null && htElementIdMap.ContainsKey(id)) { List<WeakReference<XmlElement>> elementList = htElementIdMap[id]; WeakReference<XmlElement> elemRef = GetElement(elementList, elem); if (elemRef != null) { elementList.Remove(elemRef); if (elementList.Count == 0) htElementIdMap.Remove(id); } } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { XmlDocument clone = Implementation.CreateDocument(); clone.SetBaseURI(this.baseURI); if (deep) clone.ImportChildren(this, clone, deep); return clone; } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } public override XmlNode ParentNode { get { return null; } } // Gets the node for the DOCTYPE declaration. internal virtual XmlDocumentType DocumentType { get { return (XmlDocumentType)FindChild(XmlNodeType.DocumentType); } } internal virtual XmlDeclaration Declaration { get { if (HasChildNodes) { XmlDeclaration dec = FirstChild as XmlDeclaration; return dec; } return null; } } // Gets the XmlImplementation object for this document. public XmlImplementation Implementation { get { return this.implementation; } } // Gets the name of the node. public override String Name { get { return strDocumentName; } } // Gets the name of the current node without the namespace prefix. public override String LocalName { get { return strDocumentName; } } // Gets the root XmlElement for the document. public XmlElement DocumentElement { get { return (XmlElement)FindChild(XmlNodeType.Element); } } internal override bool IsContainer { get { return true; } } internal override XmlLinkedNode LastNode { get { return lastChild; } set { lastChild = value; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return null; } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.DocumentType: if (DocumentType != null) throw new InvalidOperationException(SR.Xdom_DualDocumentTypeNode); return true; case XmlNodeType.Element: if (DocumentElement != null) throw new InvalidOperationException(SR.Xdom_DualDocumentElementNode); return true; case XmlNodeType.XmlDeclaration: if (Declaration != null) throw new InvalidOperationException(SR.Xdom_DualDeclarationNode); return true; default: return false; } } // the function examines all the siblings before the refNode // if any of the nodes has type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode refNode) { if (refNode == null) return false; XmlNode node = null; if (refNode.ParentNode != null) node = refNode.ParentNode.FirstChild; while (node != null) { if (node.NodeType == nt) return true; if (node == refNode) break; node = node.NextSibling; } return false; } // the function examines all the siblings after the refNode // if any of the nodes has the type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode refNode) { XmlNode node = refNode; while (node != null) { if (node.NodeType == nt) return true; node = node.NextSibling; } return false; } internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild) { if (refChild == null) refChild = FirstChild; if (refChild == null) return true; switch (newChild.NodeType) { case XmlNodeType.XmlDeclaration: return (refChild == FirstChild); case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: return refChild.NodeType != XmlNodeType.XmlDeclaration; case XmlNodeType.DocumentType: { if (refChild.NodeType != XmlNodeType.XmlDeclaration) { //if refChild is not the XmlDeclaration node, only need to go through the sibling before and including refChild to // make sure no Element ( rootElem node ) before the current position return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild.PreviousSibling); } } break; case XmlNodeType.Element: { if (refChild.NodeType != XmlNodeType.XmlDeclaration) { //if refChild is not the XmlDeclaration node, only need to go through the siblings after and including the refChild to // make sure no DocType node and XmlDeclaration node after the current position. return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild); } } break; } return false; } internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild) { if (refChild == null) refChild = LastChild; if (refChild == null) return true; switch (newChild.NodeType) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.DocumentType: { //we will have to go through all the siblings before the refChild just to make sure no Element node ( rootElem ) // before the current position return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild); } case XmlNodeType.Element: { return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild.NextSibling); } } return false; } // Creates an XmlAttribute with the specified name. public XmlAttribute CreateAttribute(String name) { String prefix = String.Empty; String localName = String.Empty; String namespaceURI = String.Empty; SplitName(name, out prefix, out localName); SetDefaultNamespace(prefix, localName, ref namespaceURI); return CreateAttribute(prefix, localName, namespaceURI); } internal void SetDefaultNamespace(String prefix, String localName, ref String namespaceURI) { if (prefix == strXmlns || (prefix.Length == 0 && localName == strXmlns)) { namespaceURI = strReservedXmlns; } else if (prefix == strXml) { namespaceURI = strReservedXml; } } // Creates a XmlCDataSection containing the specified data. public virtual XmlCDataSection CreateCDataSection(String data) { fCDataNodesPresent = true; return new XmlCDataSection(data, this); } // Creates an XmlComment containing the specified data. public virtual XmlComment CreateComment(String data) { return new XmlComment(data, this); } // Returns a new XmlDocumentType object. internal virtual XmlDocumentType CreateDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentType(name, publicId, systemId, internalSubset, this); } // Creates an XmlDocumentFragment. public virtual XmlDocumentFragment CreateDocumentFragment() { return new XmlDocumentFragment(this); } // Creates an element with the specified name. public XmlElement CreateElement(String name) { string prefix = String.Empty; string localName = String.Empty; SplitName(name, out prefix, out localName); return CreateElement(prefix, localName, string.Empty); } // Creates an XmlEntityReference with the specified name. internal virtual XmlEntityReference CreateEntityReference(String name) { return new XmlEntityReference(name, this); } // Creates a XmlProcessingInstruction with the specified name // and data strings. public virtual XmlProcessingInstruction CreateProcessingInstruction(String target, String data) { return new XmlProcessingInstruction(target, data, this); } // Creates a XmlDeclaration node with the specified values. public virtual XmlDeclaration CreateXmlDeclaration(String version, string encoding, string standalone) { return new XmlDeclaration(version, encoding, standalone, this); } // Creates an XmlText with the specified text. public virtual XmlText CreateTextNode(String text) { return new XmlText(text, this); } // Creates a XmlSignificantWhitespace node. public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string text) { return new XmlSignificantWhitespace(text, this); } // Creates a XmlWhitespace node. public virtual XmlWhitespace CreateWhitespace(string text) { return new XmlWhitespace(text, this); } // Returns an XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(String name) { return new XmlElementList(this, name); } // DOM Level 2 // Creates an XmlAttribute with the specified LocalName // and NamespaceURI. public XmlAttribute CreateAttribute(String qualifiedName, String namespaceURI) { string prefix = String.Empty; string localName = String.Empty; SplitName(qualifiedName, out prefix, out localName); return CreateAttribute(prefix, localName, namespaceURI); } // Creates an XmlElement with the specified LocalName and // NamespaceURI. public XmlElement CreateElement(String qualifiedName, String namespaceURI) { string prefix = String.Empty; string localName = String.Empty; SplitName(qualifiedName, out prefix, out localName); return CreateElement(prefix, localName, namespaceURI); } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(String localName, String namespaceURI) { return new XmlElementList(this, localName, namespaceURI); } // Returns the XmlElement with the specified ID. internal virtual XmlElement GetElementById(string elementId) { if (htElementIdMap != null) { List<WeakReference<XmlElement>> elementList; if (htElementIdMap.TryGetValue(elementId, out elementList)) { foreach (WeakReference<XmlElement> elemRef in elementList) { XmlElement elem; if (elemRef.TryGetTarget(out elem)) { if (elem != null && elem.IsConnected()) return elem; } } } } return null; } // Imports a node from another document to this document. public virtual XmlNode ImportNode(XmlNode node, bool deep) { return ImportNodeInternal(node, deep); } private XmlNode ImportNodeInternal(XmlNode node, bool deep) { XmlNode newNode = null; if (node == null) { throw new InvalidOperationException(SR.Xdom_Import_NullNode); } else { switch (node.NodeType) { case XmlNodeType.Element: newNode = CreateElement(node.Prefix, node.LocalName, node.NamespaceURI); ImportAttributes(node, newNode); if (deep) ImportChildren(node, newNode, deep); break; case XmlNodeType.Attribute: Debug.Assert(((XmlAttribute)node).Specified); newNode = CreateAttribute(node.Prefix, node.LocalName, node.NamespaceURI); ImportChildren(node, newNode, true); break; case XmlNodeType.Text: newNode = CreateTextNode(node.Value); break; case XmlNodeType.Comment: newNode = CreateComment(node.Value); break; case XmlNodeType.ProcessingInstruction: newNode = CreateProcessingInstruction(node.Name, node.Value); break; case XmlNodeType.XmlDeclaration: XmlDeclaration decl = (XmlDeclaration)node; newNode = CreateXmlDeclaration(decl.Version, decl.Encoding, decl.Standalone); break; case XmlNodeType.CDATA: newNode = CreateCDataSection(node.Value); break; case XmlNodeType.DocumentType: XmlDocumentType docType = (XmlDocumentType)node; newNode = CreateDocumentType(docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset); break; case XmlNodeType.DocumentFragment: newNode = CreateDocumentFragment(); if (deep) ImportChildren(node, newNode, deep); break; case XmlNodeType.EntityReference: newNode = CreateEntityReference(node.Name); // we don't import the children of entity reference because they might result in different // children nodes given different namespace context in the new document. break; case XmlNodeType.Whitespace: newNode = CreateWhitespace(node.Value); break; case XmlNodeType.SignificantWhitespace: newNode = CreateSignificantWhitespace(node.Value); break; default: throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType.ToString())); } } return newNode; } private void ImportAttributes(XmlNode fromElem, XmlNode toElem) { int cAttr = fromElem.Attributes.Count; for (int iAttr = 0; iAttr < cAttr; iAttr++) { if (fromElem.Attributes[iAttr].Specified) toElem.Attributes.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true)); } } private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep) { Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference); for (XmlNode n = fromNode.FirstChild; n != null; n = n.NextSibling) { toNode.AppendChild(ImportNodeInternal(n, deep)); } } // Microsoft extensions // Gets the XmlNameTable associated with this // implementation. public XmlNameTable NameTable { get { return implementation.NameTable; } } // Creates a XmlAttribute with the specified Prefix, LocalName, // and NamespaceURI. public virtual XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) { return new XmlAttribute(AddAttrXmlName(prefix, localName, namespaceURI), this); } internal virtual XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) { return new XmlUnspecifiedAttribute(prefix, localName, namespaceURI, this); } public virtual XmlElement CreateElement(string prefix, string localName, string namespaceURI) { XmlElement elem = new XmlElement(AddXmlName(prefix, localName, namespaceURI), true, this); return elem; } // Gets or sets a value indicating whether to preserve whitespace. public bool PreserveWhitespace { get { return preserveWhitespace; } set { preserveWhitespace = value; } } // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return false; } } internal XmlNamedNodeMap Entities { get { if (entities == null) entities = new XmlNamedNodeMap(this); return entities; } } internal bool IsLoading { get { return isLoading; } set { isLoading = value; } } internal bool ActualLoadingStatus { get { return actualLoadingStatus; } } // Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI. public virtual XmlNode CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI) { switch (type) { case XmlNodeType.Element: if (prefix != null) return CreateElement(prefix, name, namespaceURI); else return CreateElement(name, namespaceURI); case XmlNodeType.Attribute: if (prefix != null) return CreateAttribute(prefix, name, namespaceURI); else return CreateAttribute(name, namespaceURI); case XmlNodeType.Text: return CreateTextNode(string.Empty); case XmlNodeType.CDATA: return CreateCDataSection(string.Empty); case XmlNodeType.EntityReference: return CreateEntityReference(name); case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction(name, string.Empty); case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration("1.0", null, null); case XmlNodeType.Comment: return CreateComment(string.Empty); case XmlNodeType.DocumentFragment: return CreateDocumentFragment(); case XmlNodeType.DocumentType: return CreateDocumentType(name, string.Empty, string.Empty, string.Empty); case XmlNodeType.Document: return new XmlDocument(); case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace(string.Empty); case XmlNodeType.Whitespace: return CreateWhitespace(string.Empty); default: throw new ArgumentException(SR.Format(SR.Arg_CannotCreateNode, type)); } } // Creates an XmlNode with the specified node type, Name, and // NamespaceURI. public virtual XmlNode CreateNode(string nodeTypeString, string name, string namespaceURI) { return CreateNode(ConvertToNodeType(nodeTypeString), name, namespaceURI); } // Creates an XmlNode with the specified XmlNodeType, Name, and // NamespaceURI. public virtual XmlNode CreateNode(XmlNodeType type, string name, string namespaceURI) { return CreateNode(type, null, name, namespaceURI); } // Creates an XmlNode object based on the information in the XmlReader. // The reader must be positioned on a node or attribute. public virtual XmlNode ReadNode(XmlReader reader) { XmlNode node = null; try { IsLoading = true; XmlLoader loader = new XmlLoader(); node = loader.ReadCurrentNode(this, reader); } finally { IsLoading = false; } return node; } internal XmlNodeType ConvertToNodeType(string nodeTypeString) { if (nodeTypeString == "element") { return XmlNodeType.Element; } else if (nodeTypeString == "attribute") { return XmlNodeType.Attribute; } else if (nodeTypeString == "text") { return XmlNodeType.Text; } else if (nodeTypeString == "cdatasection") { return XmlNodeType.CDATA; } else if (nodeTypeString == "entityreference") { return XmlNodeType.EntityReference; } else if (nodeTypeString == "entity") { return XmlNodeType.Entity; } else if (nodeTypeString == "processinginstruction") { return XmlNodeType.ProcessingInstruction; } else if (nodeTypeString == "comment") { return XmlNodeType.Comment; } else if (nodeTypeString == "document") { return XmlNodeType.Document; } else if (nodeTypeString == "documenttype") { return XmlNodeType.DocumentType; } else if (nodeTypeString == "documentfragment") { return XmlNodeType.DocumentFragment; } else if (nodeTypeString == "notation") { return XmlNodeType.Notation; } else if (nodeTypeString == "significantwhitespace") { return XmlNodeType.SignificantWhitespace; } else if (nodeTypeString == "whitespace") { return XmlNodeType.Whitespace; } throw new ArgumentException(SR.Format(SR.Xdom_Invalid_NT_String, nodeTypeString)); } public virtual void Load(Stream inStream) { XmlReader reader = XmlReader.Create(inStream); try { Load(reader); } finally { reader.Dispose(); } } // Loads the XML document from the specified TextReader. public virtual void Load(TextReader txtReader) { XmlReader reader = XmlReader.Create(txtReader); try { Load(reader); } finally { reader.Dispose(); } } // Loads the XML document from the specified XmlReader. public virtual void Load(XmlReader reader) { try { IsLoading = true; actualLoadingStatus = true; RemoveAll(); fEntRefNodesPresent = false; fCDataNodesPresent = false; XmlLoader loader = new XmlLoader(); loader.Load(this, reader, preserveWhitespace); } finally { IsLoading = false; actualLoadingStatus = false; } } // Loads the XML document from the specified string. public virtual void LoadXml(string xml) { XmlReader reader = XmlReader.Create(new StringReader(xml)); try { Load(reader); } finally { reader.Dispose(); } } //TextEncoding is the one from XmlDeclaration if there is any internal Encoding TextEncoding { get { if (Declaration != null) { string value = Declaration.Encoding; if (value.Length > 0) { return System.Text.Encoding.GetEncoding(value); } } return null; } } public override string InnerText { set { throw new InvalidOperationException(SR.Xdom_Document_Innertext); } } public override string InnerXml { get { return base.InnerXml; } set { LoadXml(value); } } //Saves out the to the file with exact content in the XmlDocument. public virtual void Save(Stream outStream) { XmlDOMTextWriter xw = new XmlDOMTextWriter(outStream, TextEncoding); if (preserveWhitespace == false) xw.Formatting = Formatting.Indented; WriteTo(xw); xw.Flush(); } // Saves the XML document to the specified TextWriter. // //Saves out the file with xmldeclaration which has encoding value equal to //that of textwriter's encoding public virtual void Save(TextWriter writer) { XmlDOMTextWriter xw = new XmlDOMTextWriter(writer); if (preserveWhitespace == false) xw.Formatting = Formatting.Indented; Save(xw); } // Saves the XML document to the specified XmlWriter. // //Saves out the file with xmldeclaration which has encoding value equal to //that of textwriter's encoding public virtual void Save(XmlWriter w) { XmlNode n = this.FirstChild; if (n == null) return; if (w.WriteState == WriteState.Start) { if (n is XmlDeclaration) { if (Standalone.Length == 0) w.WriteStartDocument(); else if (Standalone == "yes") w.WriteStartDocument(true); else if (Standalone == "no") w.WriteStartDocument(false); n = n.NextSibling; } else { w.WriteStartDocument(); } } while (n != null) { n.WriteTo(w); n = n.NextSibling; } w.Flush(); } // Saves the node to the specified XmlWriter. // //Writes out the to the file with exact content in the XmlDocument. public override void WriteTo(XmlWriter w) { WriteContentTo(w); } // Saves all the children of the node to the specified XmlWriter. // //Writes out the to the file with exact content in the XmlDocument. public override void WriteContentTo(XmlWriter xw) { foreach (XmlNode n in this) { n.WriteTo(xw); } } public event XmlNodeChangedEventHandler NodeInserting { add { onNodeInsertingDelegate += value; } remove { onNodeInsertingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeInserted { add { onNodeInsertedDelegate += value; } remove { onNodeInsertedDelegate -= value; } } public event XmlNodeChangedEventHandler NodeRemoving { add { onNodeRemovingDelegate += value; } remove { onNodeRemovingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeRemoved { add { onNodeRemovedDelegate += value; } remove { onNodeRemovedDelegate -= value; } } public event XmlNodeChangedEventHandler NodeChanging { add { onNodeChangingDelegate += value; } remove { onNodeChangingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeChanged { add { onNodeChangedDelegate += value; } remove { onNodeChangedDelegate -= value; } } internal override XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) { switch (action) { case XmlNodeChangedAction.Insert: if (onNodeInsertingDelegate == null && onNodeInsertedDelegate == null) { return null; } break; case XmlNodeChangedAction.Remove: if (onNodeRemovingDelegate == null && onNodeRemovedDelegate == null) { return null; } break; case XmlNodeChangedAction.Change: if (onNodeChangingDelegate == null && onNodeChangedDelegate == null) { return null; } break; } return new XmlNodeChangedEventArgs(node, oldParent, newParent, oldValue, newValue, action); } internal XmlNodeChangedEventArgs GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent) { if (onNodeInsertingDelegate == null && onNodeInsertedDelegate == null) { return null; } string nodeValue = node.Value; return new XmlNodeChangedEventArgs(node, null, newParent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); } internal override void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) { switch (args.Action) { case XmlNodeChangedAction.Insert: if (onNodeInsertingDelegate != null) onNodeInsertingDelegate(this, args); break; case XmlNodeChangedAction.Remove: if (onNodeRemovingDelegate != null) onNodeRemovingDelegate(this, args); break; case XmlNodeChangedAction.Change: if (onNodeChangingDelegate != null) onNodeChangingDelegate(this, args); break; } } } internal override void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) { switch (args.Action) { case XmlNodeChangedAction.Insert: if (onNodeInsertedDelegate != null) onNodeInsertedDelegate(this, args); break; case XmlNodeChangedAction.Remove: if (onNodeRemovedDelegate != null) onNodeRemovedDelegate(this, args); break; case XmlNodeChangedAction.Change: if (onNodeChangedDelegate != null) onNodeChangedDelegate(this, args); break; } } } // The function such through schema info to find out if there exists a default attribute with passed in names in the passed in element // If so, return the newly created default attribute (with children tree); // Otherwise, return null. // This function returns null because it is implication of removing schema. // If removed more methods would have to be removed as well and it would make adding schema back much harder. internal XmlAttribute GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI) { return null; } internal String Standalone { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Standalone; return null; } } internal XmlEntity GetEntityNode(String name) { if (DocumentType != null) { XmlNamedNodeMap entites = DocumentType.Entities; if (entites != null) return (XmlEntity)(entites.GetNamedItem(name)); } return null; } public override String BaseURI { get { return baseURI; } } internal void SetBaseURI(String inBaseURI) { baseURI = inBaseURI; } internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { Debug.Assert(doc == this); if (!IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); XmlNodeChangedEventArgs args = GetInsertEventArgsForLoad(newChild, this); if (args != null) BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (lastChild == null) { newNode.next = newNode; } else { newNode.next = lastChild.next; lastChild.next = newNode; } lastChild = newNode; newNode.SetParentForLoad(this); if (args != null) AfterEvent(args); return newNode; } } }
// Copyright 2017 Google 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 UnityEngine; using System; using System.Collections; using System.ComponentModel; using Gvr.Internal; /// Main entry point for Standalone headset APIs. /// /// To use this API, use the GvrHeadset prefab. There can be only one /// such prefab in a scene. /// /// This is a singleton object. public class GvrHeadset : MonoBehaviour { private static GvrHeadset instance; private IHeadsetProvider headsetProvider; private HeadsetState headsetState; private IEnumerator standaloneUpdate; private WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); // Delegates for GVR events. private OnSafetyRegionEvent safetyRegionDelegate; private OnRecenterEvent recenterDelegate; // Delegate definitions. /// This delegate is called when the headset crosses the safety region boundary. public delegate void OnSafetyRegionEvent(bool enter); /// This delegate is called after the headset is recentered. /// |recenterType| indicates the reason recentering occurred. /// |recenterFlags| are flags related to recentering. See |GvrRecenterFlags|. /// |recenteredPosition| is the positional offset from the session start pose. /// |recenteredOrientation| is the rotational offset from the session start pose. public delegate void OnRecenterEvent(GvrRecenterEventType recenterType, GvrRecenterFlags recenterFlags, Vector3 recenteredPosition, Quaternion recenteredOrientation); #region DELEGATE_HANDLERS public static event OnSafetyRegionEvent OnSafetyRegionChange { add { if (instance != null) { instance.safetyRegionDelegate += value; } } remove { if (instance != null) { instance.safetyRegionDelegate -= value; } } } public static event OnRecenterEvent OnRecenter { add { if (instance != null) { instance.recenterDelegate += value; } } remove { if (instance != null) { instance.recenterDelegate -= value; } } } #endregion // DELEGATE_HANDLERS #region GVR_STANDALONE_PROPERTIES /// Returns |true| if the current headset supports positionally tracked, 6DOF head poses. /// Returns |false| if only rotation-based head poses are supported. public static bool SupportsPositionalTracking { get { if (instance == null) { return false; } try { return instance.headsetProvider.SupportsPositionalTracking; } catch(Exception e) { Debug.LogError("Error reading SupportsPositionalTracking: " + e.Message); return false; } } } /// If a floor is found, populates floorHeight with the detected height. /// Otherwise, leaves the value unchanged. /// Returns true if value retrieval was successful, false otherwise (depends on tracking state). public static bool TryGetFloorHeight(ref float floorHeight) { if (instance == null) { return false; } return instance.headsetProvider.TryGetFloorHeight(ref floorHeight); } /// If the last recentering transform is available, populates position and rotation with that /// transform. /// Returns true if value retrieval was successful, false otherwise (unlikely). public static bool TryGetRecenterTransform(ref Vector3 position, ref Quaternion rotation) { if (instance == null) { return false; } return instance.headsetProvider.TryGetRecenterTransform(ref position, ref rotation); } /// Populates safetyType with the available safety region feature on the /// currently-running device. /// Returns true if value retrieval was successful, false otherwise (unlikely). public static bool TryGetSafetyRegionType(ref GvrSafetyRegionType safetyType) { if (instance == null) { return false; } return instance.headsetProvider.TryGetSafetyRegionType(ref safetyType); } /// If the safety region is of type GvrSafetyRegionType.Cylinder, populates innerRadius with the /// inner radius size (where fog starts appearing) of the safety cylinder in meters. /// Assumes the safety region type has been previously checked by the caller. /// Returns true if value retrieval was successful, false otherwise (if region type is /// GvrSafetyRegionType.Invalid). public static bool TryGetSafetyCylinderInnerRadius(ref float innerRadius) { if (instance == null) { return false; } return instance.headsetProvider.TryGetSafetyCylinderInnerRadius(ref innerRadius); } /// If the safety region is of type GvrSafetyRegionType.Cylinder, populates outerRadius with the /// outer radius size (where fog is 100% opaque) of the safety cylinder in meters. /// Assumes the safety region type has been previously checked by the caller. /// Returns true if value retrieval was successful, false otherwise (if region type is /// GvrSafetyRegionType.Invalid). public static bool TryGetSafetyCylinderOuterRadius(ref float outerRadius) { if (instance == null) { return false; } return instance.headsetProvider.TryGetSafetyCylinderOuterRadius(ref outerRadius); } #endregion // GVR_STANDALONE_PROPERTIES private GvrHeadset() { headsetState.Initialize(); } void Awake() { if (instance != null) { Debug.LogError("More than one GvrHeadset instance was found in your scene. " + "Ensure that there is only one GvrHeadset."); this.enabled = false; return; } instance = this; if (headsetProvider == null) { headsetProvider = HeadsetProviderFactory.CreateProvider(); } } void OnEnable() { if (!SupportsPositionalTracking) { return; } standaloneUpdate = EndOfFrame(); StartCoroutine(standaloneUpdate); } void OnDisable() { if (!SupportsPositionalTracking) { return; } StopCoroutine(standaloneUpdate); } void OnDestroy() { if (!SupportsPositionalTracking) { return; } instance = null; } private void UpdateStandalone() { // Events are stored in a queue, so poll until we get Invalid. headsetProvider.PollEventState(ref headsetState); while (headsetState.eventType != GvrEventType.Invalid) { switch (headsetState.eventType) { case GvrEventType.Recenter: if (recenterDelegate != null) { recenterDelegate(headsetState.recenterEventType, (GvrRecenterFlags) headsetState.recenterEventFlags, headsetState.recenteredPosition, headsetState.recenteredRotation); } break; case GvrEventType.SafetyRegionEnter: if (safetyRegionDelegate != null) { safetyRegionDelegate(true); } break; case GvrEventType.SafetyRegionExit: if (safetyRegionDelegate != null) { safetyRegionDelegate(false); } break; case GvrEventType.Invalid: throw new InvalidEnumArgumentException("Invalid headset event: " + headsetState.eventType); default: // Fallthrough, should never get here. break; } headsetProvider.PollEventState(ref headsetState); } } IEnumerator EndOfFrame() { while (true) { // This must be done at the end of the frame to ensure that all GameObjects had a chance // to read transient state (e.g. events, etc) for the current frame before it gets reset. yield return waitForEndOfFrame; UpdateStandalone(); } } }
//--------------------------------------------------------------------------- // // <copyright file="VectorAnimationUsingKeyFrames.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; namespace System.Windows.Media.Animation { /// <summary> /// This class is used to animate a Vector property value along a set /// of key frames. /// </summary> [ContentProperty("KeyFrames")] public class VectorAnimationUsingKeyFrames : VectorAnimationBase, IKeyFrameAnimation, IAddChild { #region Data private VectorKeyFrameCollection _keyFrames; private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames; private bool _areKeyTimesValid; #endregion #region Constructors /// <Summary> /// Creates a new KeyFrameVectorAnimation. /// </Summary> public VectorAnimationUsingKeyFrames() : base() { _areKeyTimesValid = true; } #endregion #region Freezable /// <summary> /// Creates a copy of this KeyFrameVectorAnimation. /// </summary> /// <returns>The copy</returns> public new VectorAnimationUsingKeyFrames Clone() { return (VectorAnimationUsingKeyFrames)base.Clone(); } /// <summary> /// Returns a version of this class with all its base property values /// set to the current animated values and removes the animations. /// </summary> /// <returns> /// Since this class isn't animated, this method will always just return /// this instance of the class. /// </returns> public new VectorAnimationUsingKeyFrames CloneCurrentValue() { return (VectorAnimationUsingKeyFrames)base.CloneCurrentValue(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); canFreeze &= Freezable.Freeze(_keyFrames, isChecking); if (canFreeze & !_areKeyTimesValid) { ResolveKeyTimes(); } return canFreeze; } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. /// </summary> protected override void OnChanged() { _areKeyTimesValid = false; base.OnChanged(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new VectorAnimationUsingKeyFrames(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { VectorAnimationUsingKeyFrames sourceAnimation = (VectorAnimationUsingKeyFrames) sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { VectorAnimationUsingKeyFrames sourceAnimation = (VectorAnimationUsingKeyFrames) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable source) { VectorAnimationUsingKeyFrames sourceAnimation = (VectorAnimationUsingKeyFrames) source; base.GetAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { VectorAnimationUsingKeyFrames sourceAnimation = (VectorAnimationUsingKeyFrames) source; base.GetCurrentValueAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Helper used by the four Freezable clone methods to copy the resolved key times and /// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core /// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here. /// </summary> /// <param name="sourceAnimation"></param> /// <param name="isCurrentValueClone"></param> private void CopyCommon(VectorAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone) { _areKeyTimesValid = sourceAnimation._areKeyTimesValid; if ( _areKeyTimesValid && sourceAnimation._sortedResolvedKeyFrames != null) { // _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply _sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone(); } if (sourceAnimation._keyFrames != null) { if (isCurrentValueClone) { _keyFrames = (VectorKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue(); } else { _keyFrames = (VectorKeyFrameCollection)sourceAnimation._keyFrames.Clone(); } OnFreezablePropertyChanged(null, _keyFrames); } } #endregion // Freezable #region IAddChild interface /// <summary> /// Adds a child object to this KeyFrameAnimation. /// </summary> /// <param name="child"> /// The child object to add. /// </param> /// <remarks> /// A KeyFrameAnimation only accepts a KeyFrame of the proper type as /// a child. /// </remarks> void IAddChild.AddChild(object child) { WritePreamble(); if (child == null) { throw new ArgumentNullException("child"); } AddChild(child); WritePostscript(); } /// <summary> /// Implemented to allow KeyFrames to be direct children /// of KeyFrameAnimations in markup. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddChild(object child) { VectorKeyFrame keyFrame = child as VectorKeyFrame; if (keyFrame != null) { KeyFrames.Add(keyFrame); } else { throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child"); } } /// <summary> /// Adds a text string as a child of this KeyFrameAnimation. /// </summary> /// <param name="childText"> /// The text to add. /// </param> /// <remarks> /// A KeyFrameAnimation does not accept text as a child, so this method will /// raise an InvalididOperationException unless a derived class has /// overridden the behavior to add text. /// </remarks> /// <exception cref="ArgumentNullException">The childText parameter is /// null.</exception> void IAddChild.AddText(string childText) { if (childText == null) { throw new ArgumentNullException("childText"); } AddText(childText); } /// <summary> /// This method performs the core functionality of the AddText() /// method on the IAddChild interface. For a KeyFrameAnimation this means /// throwing and InvalidOperationException because it doesn't /// support adding text. /// </summary> /// <remarks> /// This method is the only core implementation. It does not call /// WritePreamble() or WritePostscript(). It also doesn't throw an /// ArgumentNullException if the childText parameter is null. These tasks /// are performed by the interface implementation. Therefore, it's OK /// for a derived class to override this method and call the base /// class implementation only if they determine that it's the right /// course of action. The derived class can rely on KeyFrameAnimation's /// implementation of IAddChild.AddChild or implement their own /// following the Freezable pattern since that would be a public /// method. /// </remarks> /// <param name="childText">A string representing the child text that /// should be added. If this is a KeyFrameAnimation an exception will be /// thrown.</param> /// <exception cref="InvalidOperationException">Timelines have no way /// of adding text.</exception> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddText(string childText) { throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren)); } #endregion #region VectorAnimationBase /// <summary> /// Calculates the value this animation believes should be the current value for the property. /// </summary> /// <param name="defaultOriginValue"> /// This value is the suggested origin value provided to the animation /// to be used if the animation does not have its own concept of a /// start value. If this animation is the first in a composition chain /// this value will be the snapshot value if one is available or the /// base property value if it is not; otherise this value will be the /// value returned by the previous animation in the chain with an /// animationClock that is not Stopped. /// </param> /// <param name="defaultDestinationValue"> /// This value is the suggested destination value provided to the animation /// to be used if the animation does not have its own concept of an /// end value. This value will be the base value if the animation is /// in the first composition layer of animations on a property; /// otherwise this value will be the output value from the previous /// composition layer of animations for the property. /// </param> /// <param name="animationClock"> /// This is the animationClock which can generate the CurrentTime or /// CurrentProgress value to be used by the animation to generate its /// output value. /// </param> /// <returns> /// The value this animation believes should be the current value for the property. /// </returns> protected sealed override Vector GetCurrentValueCore( Vector defaultOriginValue, Vector defaultDestinationValue, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); if (_keyFrames == null) { return defaultDestinationValue; } // We resolved our KeyTimes when we froze, but also got notified // of the frozen state and therefore invalidated ourselves. if (!_areKeyTimesValid) { ResolveKeyTimes(); } if (_sortedResolvedKeyFrames == null) { return defaultDestinationValue; } TimeSpan currentTime = animationClock.CurrentTime.Value; Int32 keyFrameCount = _sortedResolvedKeyFrames.Length; Int32 maxKeyFrameIndex = keyFrameCount - 1; Vector currentIterationValue; Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames."); Int32 currentResolvedKeyFrameIndex = 0; // Skip all the key frames with key times lower than the current time. // currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex // if we are past the last key frame. while ( currentResolvedKeyFrameIndex < keyFrameCount && currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } // If there are multiple key frames at the same key time, be sure to go to the last one. while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex && currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } if (currentResolvedKeyFrameIndex == keyFrameCount) { // Past the last key frame. currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex); } else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { // Exactly on a key frame. currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex); } else { // Between two key frames. Double currentSegmentProgress = 0.0; Vector fromValue; if (currentResolvedKeyFrameIndex == 0) { // The current key frame is the first key frame so we have // some special rules for determining the fromValue and an // optimized method of calculating the currentSegmentProgress. // If we're additive we want the base value to be a zero value // so that if there isn't a key frame at time 0.0, we'll use // the zero value for the time 0.0 value and then add that // later to the base value. if (IsAdditive) { fromValue = AnimatedTypeHelpers.GetZeroValueVector(defaultOriginValue); } else { fromValue = defaultOriginValue; } // Current segment time divided by the segment duration. // Note: the reason this works is that we know that we're in // the first segment, so we can assume: // // currentTime.TotalMilliseconds = current segment time // _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration currentSegmentProgress = currentTime.TotalMilliseconds / _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds; } else { Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1; TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime; fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex); TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime; TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime; currentSegmentProgress = segmentCurrentTime.TotalMilliseconds / segmentDuration.TotalMilliseconds; } currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress); } // If we're cumulative, we need to multiply the final key frame // value by the current repeat count and add this to the return // value. if (IsCumulative) { Double currentRepeat = (Double)(animationClock.CurrentIteration - 1); if (currentRepeat > 0.0) { currentIterationValue = AnimatedTypeHelpers.AddVector( currentIterationValue, AnimatedTypeHelpers.ScaleVector(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat)); } } // If we're additive we need to add the base value to the return value. if (IsAdditive) { return AnimatedTypeHelpers.AddVector(defaultOriginValue, currentIterationValue); } return currentIterationValue; } /// <summary> /// Provide a custom natural Duration when the Duration property is set to Automatic. /// </summary> /// <param name="clock"> /// The Clock whose natural duration is desired. /// </param> /// <returns> /// If the last KeyFrame of this animation is a KeyTime, then this will /// be used as the NaturalDuration; otherwise it will be one second. /// </returns> protected override sealed Duration GetNaturalDurationCore(Clock clock) { return new Duration(LargestTimeSpanKeyTime); } #endregion #region IKeyFrameAnimation /// <summary> /// Returns the VectorKeyFrameCollection used by this KeyFrameVectorAnimation. /// </summary> IList IKeyFrameAnimation.KeyFrames { get { return KeyFrames; } set { KeyFrames = (VectorKeyFrameCollection)value; } } /// <summary> /// Returns the VectorKeyFrameCollection used by this KeyFrameVectorAnimation. /// </summary> public VectorKeyFrameCollection KeyFrames { get { ReadPreamble(); // The reason we don't just set _keyFrames to the empty collection // in the first place is that null tells us that the user has not // asked for the collection yet. The first time they ask for the // collection and we're unfrozen, policy dictates that we give // them a new unfrozen collection. All subsequent times they will // get whatever collection is present, whether frozen or unfrozen. if (_keyFrames == null) { if (this.IsFrozen) { _keyFrames = VectorKeyFrameCollection.Empty; } else { WritePreamble(); _keyFrames = new VectorKeyFrameCollection(); OnFreezablePropertyChanged(null, _keyFrames); WritePostscript(); } } return _keyFrames; } set { if (value == null) { throw new ArgumentNullException("value"); } WritePreamble(); if (value != _keyFrames) { OnFreezablePropertyChanged(_keyFrames, value); _keyFrames = value; WritePostscript(); } } } /// <summary> /// Returns true if we should serialize the KeyFrames, property for this Animation. /// </summary> /// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeKeyFrames() { ReadPreamble(); return _keyFrames != null && _keyFrames.Count > 0; } #endregion #region Public Properties /// <summary> /// If this property is set to true, this animation will add its value /// to the base value or the value of the previous animation in the /// composition chain. Another way of saying this is that the units /// specified in the animation are relative to the base value rather /// than absolute units. /// </summary> /// <remarks> /// In the case where the first key frame's resolved key time is not /// 0.0 there is slightly different behavior between KeyFrameVectorAnimations /// with IsAdditive set and without. Animations with the property set to false /// will behave as if there is a key frame at time 0.0 with the value of the /// base value. Animations with the property set to true will behave as if /// there is a key frame at time 0.0 with a zero value appropriate to the type /// of the animation. These behaviors provide the results most commonly expected /// and can be overridden by simply adding a key frame at time 0.0 with the preferred value. /// </remarks> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value)); } } /// <summary> /// If this property is set to true, the value of this animation will /// accumulate over repeat cycles. For example, if this is a point /// animation and your key frames describe something approximating and /// arc, setting this property to true will result in an animation that /// would appear to bounce the point across the screen. /// </summary> /// <remarks> /// This property works along with the IsAdditive property. Setting /// this value to true has no effect unless IsAdditive is also set /// to true. /// </remarks> public bool IsCumulative { get { return (bool)GetValue(IsCumulativeProperty); } set { SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value)); } } #endregion #region Private Methods private struct KeyTimeBlock { public int BeginIndex; public int EndIndex; } private Vector GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue"); return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value; } private VectorKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame"); return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex]; } /// <summary> /// Returns the largest time span specified key time from all of the key frames. /// If there are not time span key times a time span of one second is returned /// to match the default natural duration of the From/To/By animations. /// </summary> private TimeSpan LargestTimeSpanKeyTime { get { bool hasTimeSpanKeyTime = false; TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero; if (_keyFrames != null) { Int32 keyFrameCount = _keyFrames.Count; for (int index = 0; index < keyFrameCount; index++) { KeyTime keyTime = _keyFrames[index].KeyTime; if (keyTime.Type == KeyTimeType.TimeSpan) { hasTimeSpanKeyTime = true; if (keyTime.TimeSpan > largestTimeSpanKeyTime) { largestTimeSpanKeyTime = keyTime.TimeSpan; } } } } if (hasTimeSpanKeyTime) { return largestTimeSpanKeyTime; } else { return TimeSpan.FromSeconds(1.0); } } } private void ResolveKeyTimes() { Debug.Assert(!_areKeyTimesValid, "KeyFrameVectorAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid."); int keyFrameCount = 0; if (_keyFrames != null) { keyFrameCount = _keyFrames.Count; } if (keyFrameCount == 0) { _sortedResolvedKeyFrames = null; _areKeyTimesValid = true; return; } _sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount]; int index = 0; // Initialize the _originalKeyFrameIndex. for ( ; index < keyFrameCount; index++) { _sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index; } // calculationDuration represents the time span we will use to resolve // percent key times. This is defined as the value in the following // precedence order: // 1. The animation's duration, but only if it is a time span, not auto or forever. // 2. The largest time span specified key time of all the key frames. // 3. 1 second, to match the From/To/By animations. TimeSpan calculationDuration = TimeSpan.Zero; Duration duration = Duration; if (duration.HasTimeSpan) { calculationDuration = duration.TimeSpan; } else { calculationDuration = LargestTimeSpanKeyTime; } int maxKeyFrameIndex = keyFrameCount - 1; ArrayList unspecifiedBlocks = new ArrayList(); bool hasPacedKeyTimes = false; // // Pass 1: Resolve Percent and Time key times. // index = 0; while (index < keyFrameCount) { KeyTime keyTime = _keyFrames[index].KeyTime; switch (keyTime.Type) { case KeyTimeType.Percent: _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds( keyTime.Percent * calculationDuration.TotalMilliseconds); index++; break; case KeyTimeType.TimeSpan: _sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan; index++; break; case KeyTimeType.Paced: case KeyTimeType.Uniform: if (index == maxKeyFrameIndex) { // If the last key frame doesn't have a specific time // associated with it its resolved key time will be // set to the calculationDuration, which is the // defined in the comments above where it is set. // Reason: We only want extra time at the end of the // key frames if the user specifically states that // the last key frame ends before the animation ends. _sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration; index++; } else if ( index == 0 && keyTime.Type == KeyTimeType.Paced) { // Note: It's important that this block come after // the previous if block because of rule precendence. // If the first key frame in a multi-frame key frame // collection is paced, we set its resolved key time // to 0.0 for performance reasons. If we didn't, the // resolved key time list would be dependent on the // base value which can change every animation frame // in many cases. _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero; index++; } else { if (keyTime.Type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } KeyTimeBlock block = new KeyTimeBlock(); block.BeginIndex = index; // NOTE: We don't want to go all the way up to the // last frame because if it is Uniform or Paced its // resolved key time will be set to the calculation // duration using the logic above. // // This is why the logic is: // ((++index) < maxKeyFrameIndex) // instead of: // ((++index) < keyFrameCount) while ((++index) < maxKeyFrameIndex) { KeyTimeType type = _keyFrames[index].KeyTime.Type; if ( type == KeyTimeType.Percent || type == KeyTimeType.TimeSpan) { break; } else if (type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } } Debug.Assert(index < keyFrameCount, "The end index for a block of unspecified key frames is out of bounds."); block.EndIndex = index; unspecifiedBlocks.Add(block); } break; } } // // Pass 2: Resolve Uniform key times. // for (int j = 0; j < unspecifiedBlocks.Count; j++) { KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j]; TimeSpan blockBeginTime = TimeSpan.Zero; if (block.BeginIndex > 0) { blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime; } // The number of segments is equal to the number of key // frames we're working on plus 1. Think about the case // where we're working on a single key frame. There's a // segment before it and a segment after it. // // Time known Uniform Time known // ^ ^ ^ // | | | // | (segment 1) | (segment 2) | Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1; TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount); index = block.BeginIndex; TimeSpan resolvedTime = blockBeginTime + uniformTimeStep; while (index < block.EndIndex) { _sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime; resolvedTime += uniformTimeStep; index++; } } // // Pass 3: Resolve Paced key times. // if (hasPacedKeyTimes) { ResolvePacedKeyTimes(); } // // Sort resolved key frame entries. // Array.Sort(_sortedResolvedKeyFrames); _areKeyTimesValid = true; return; } /// <summary> /// This should only be called from ResolveKeyTimes and only at the /// appropriate time. /// </summary> private void ResolvePacedKeyTimes() { Debug.Assert(_keyFrames != null && _keyFrames.Count > 2, "Caller must guard against calling this method when there are insufficient keyframes."); // If the first key frame is paced its key time has already // been resolved, so we start at index 1. int index = 1; int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1; do { if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced) { // // We've found a paced key frame so this is the // beginning of a paced block. // // The first paced key frame in this block. int firstPacedBlockKeyFrameIndex = index; // List of segment lengths for this paced block. List<Double> segmentLengths = new List<Double>(); // The resolved key time for the key frame before this // block which we'll use as our starting point. TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime; // The total of the segment lengths of the paced key // frames in this block. Double totalLength = 0.0; // The key value of the previous key frame which will be // used to determine the segment length of this key frame. Vector prevKeyValue = _keyFrames[index - 1].Value; do { Vector currentKeyValue = _keyFrames[index].Value; // Determine the segment length for this key frame and // add to the total length. totalLength += AnimatedTypeHelpers.GetSegmentLengthVector(prevKeyValue, currentKeyValue); // Temporarily store the distance into the total length // that this key frame represents in the resolved // key times array to be converted to a resolved key // time outside of this loop. segmentLengths.Add(totalLength); // Prepare for the next iteration. prevKeyValue = currentKeyValue; index++; } while ( index < maxKeyFrameIndex && _keyFrames[index].KeyTime.Type == KeyTimeType.Paced); // index is currently set to the index of the key frame // after the last paced key frame. This will always // be a valid index because we limit ourselves with // maxKeyFrameIndex. // We need to add the distance between the last paced key // frame and the next key frame to get the total distance // inside the key frame block. totalLength += AnimatedTypeHelpers.GetSegmentLengthVector(prevKeyValue, _keyFrames[index].Value); // Calculate the time available in the resolved key time space. TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime; // Convert lengths in segmentLengths list to resolved // key times for the paced key frames in this block. for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++) { // The resolved key time for each key frame is: // // The key time of the key frame before this paced block // + ((the percentage of the way through the total length) // * the resolved key time space available for the block) _sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds( (segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds); } } else { index++; } } while (index < maxKeyFrameIndex); } #endregion } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.DisplayManagement; using OrchardCore.Entities; using OrchardCore.Media; using OrchardCore.Mvc.Core.Utilities; using OrchardCore.Seo.Models; using OrchardCore.Settings; namespace OrchardCore.Seo.Drivers { public class SeoMetaSettingsHandler : ContentHandlerBase { private readonly IMediaFileStore _mediaFileStore; private readonly ISiteService _siteService; private readonly IActionContextAccessor _actionContextAccessor; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUrlHelperFactory _urlHelperFactory; private IContentManager _contentManager; public SeoMetaSettingsHandler( IMediaFileStore mediaFileStore, ISiteService siteService, IActionContextAccessor actionContextAccessor, IHttpContextAccessor httpContextAccessor, IUrlHelperFactory urlHelperFactory ) { _mediaFileStore = mediaFileStore; _siteService = siteService; _actionContextAccessor = actionContextAccessor; _httpContextAccessor = httpContextAccessor; _urlHelperFactory = urlHelperFactory; } public override Task GetContentItemAspectAsync(ContentItemAspectContext context) { return context.ForAsync<SeoAspect>(async aspect => { // This handlers provides defaults, either from the Seo Meta Settings, or ensures values by default. (title etc) _contentManager ??= _httpContextAccessor.HttpContext.RequestServices.GetRequiredService<IContentManager>(); var siteSettings = await _siteService.GetSiteSettingsAsync(); var metaSettings = siteSettings.As<ContentItem>("SocialMetaSettings"); var actionContext = _actionContextAccessor.ActionContext; if (actionContext == null) { actionContext = await GetActionContextAsync(_httpContextAccessor.HttpContext); } var urlHelper = _urlHelperFactory.GetUrlHelper(actionContext); var contentItemMetadata = await _contentManager.PopulateAspectAsync<ContentItemMetadata>(context.ContentItem); var relativeUrl = urlHelper.RouteUrl(contentItemMetadata.DisplayRouteValues); var absoluteUrl = urlHelper.ToAbsoluteUrl(relativeUrl); // Logic is this happens last after the part settings. // so if values are not set it is responsible for settings them. string defaultImage = (metaSettings.Content.SocialMetaSettings?.DefaultSocialImage?.Paths as JArray)?.Count > 0 ? metaSettings.Content.SocialMetaSettings.DefaultSocialImage.Paths[0].ToString() : String.Empty; string openGraphImage = (metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.Paths as JArray)?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.Paths[0]?.ToString() : String.Empty; string twitterImage = (metaSettings.Content.SocialMetaSettings?.TwitterImage?.Paths as JArray)?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.TwitterImage?.Paths[0]?.ToString() : String.Empty; string defaultAltText = (metaSettings.Content.SocialMetaSettings?.DefaultSocialImage?.MediaTexts as JArray)?.Count > 0 ? metaSettings.Content.SocialMetaSettings.DefaultSocialImage.MediaTexts[0].ToString() : String.Empty; string openGraphAltText = (metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.MediaTexts as JArray)?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.OpenGraphImage?.MediaTexts[0]?.ToString() : String.Empty; string twitterAltText = (metaSettings.Content.SocialMetaSettings?.TwitterImage?.MediaTexts as JArray)?.Count > 0 ? metaSettings.Content.SocialMetaSettings?.TwitterImage?.MediaTexts[0]?.ToString() : String.Empty; string twitterCard = metaSettings.Content.SocialMetaSettings?.TwitterCard?.Text?.ToString(); string twitterCreator = metaSettings.Content.SocialMetaSettings?.TwitterCreator?.Text?.ToString(); string twitterSite = metaSettings.Content.SocialMetaSettings?.TwitterSite?.Text?.ToString(); string googleSchema = metaSettings.Content.SocialMetaSettings?.GoogleSchema?.Text?.ToString(); // Meta if (String.IsNullOrEmpty(aspect.MetaDescription)) { aspect.MetaDescription = metaSettings.Content.SocialMetaSettings?.DefaultMetaDescription?.Text?.ToString(); } // OpenGraph aspect.OpenGraphUrl = absoluteUrl; if (String.IsNullOrEmpty(aspect.OpenGraphType)) { aspect.OpenGraphType = metaSettings.Content.SocialMetaSettings?.OpenGraphType?.Text?.ToString(); } if (String.IsNullOrEmpty(aspect.OpenGraphTitle)) { aspect.OpenGraphTitle = context.ContentItem.DisplayText; } if (String.IsNullOrEmpty(aspect.OpenGraphDescription)) { aspect.OpenGraphDescription = metaSettings.Content.SocialMetaSettings?.DefaultOpenGraphDescription?.Text?.ToString(); } if (String.IsNullOrEmpty(aspect.OpenGraphSiteName)) { aspect.OpenGraphSiteName = metaSettings.Content.SocialMetaSettings?.OpenGraphSiteName?.Text.ToString(); if (String.IsNullOrEmpty(aspect.OpenGraphSiteName)) { aspect.OpenGraphSiteName = siteSettings.SiteName; } } if (String.IsNullOrEmpty(aspect.OpenGraphAppId)) { aspect.OpenGraphAppId = metaSettings.Content.SocialMetaSettings?.OpenGraphAppId?.Text.ToString(); } if (String.IsNullOrEmpty(aspect.OpenGraphImage)) { if (String.IsNullOrEmpty(openGraphImage)) { if (!String.IsNullOrEmpty(defaultImage)) { aspect.OpenGraphImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(defaultImage)); } } else { aspect.OpenGraphImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(openGraphImage)); } } if (String.IsNullOrEmpty(aspect.OpenGraphImageAlt)) { if (String.IsNullOrEmpty(openGraphAltText)) { aspect.OpenGraphImageAlt = defaultAltText; } else { aspect.OpenGraphImageAlt = openGraphAltText; } } // Twitter aspect.TwitterUrl = absoluteUrl; if (String.IsNullOrEmpty(aspect.TwitterTitle)) { aspect.TwitterTitle = context.ContentItem.DisplayText; } if (String.IsNullOrEmpty(aspect.TwitterDescription)) { aspect.TwitterDescription = metaSettings.Content.SocialMetaSettings?.DefaultTwitterDescription?.Text?.ToString(); } if (String.IsNullOrEmpty(aspect.TwitterCard)) { aspect.TwitterCard = twitterCard; } if (String.IsNullOrEmpty(aspect.TwitterSite)) { aspect.TwitterSite = twitterSite; } if (String.IsNullOrEmpty(aspect.TwitterCreator)) { aspect.TwitterCreator = twitterCreator; } if (String.IsNullOrEmpty(aspect.TwitterImage)) { if (String.IsNullOrEmpty(twitterImage)) { if (!String.IsNullOrEmpty(defaultImage)) { aspect.TwitterImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(defaultImage)); } } else { aspect.TwitterImage = urlHelper.ToAbsoluteUrl(_mediaFileStore.MapPathToPublicUrl(twitterImage)); } } if (String.IsNullOrEmpty(aspect.TwitterImageAlt)) { if (String.IsNullOrEmpty(twitterAltText)) { aspect.TwitterImageAlt = defaultAltText; } else { aspect.TwitterImageAlt = twitterAltText; } } if (String.IsNullOrEmpty(aspect.GoogleSchema)) { aspect.GoogleSchema = googleSchema; } }); } internal static async Task<ActionContext> GetActionContextAsync(HttpContext httpContext) { var routeData = new RouteData(); routeData.Routers.Add(new RouteCollection()); var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor()); var filters = httpContext.RequestServices.GetServices<IAsyncViewActionFilter>(); foreach (var filter in filters) { await filter.OnActionExecutionAsync(actionContext); } return actionContext; } } }
using Signum.Entities; using Signum.Utilities; using System.Collections.Generic; using System.Linq; using System.Text; #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. namespace Signum.Engine.PostgresCatalog { [TableName("pg_catalog.pg_namespace")] public class PgNamespace : IView { [ViewPrimaryKey] public int oid; public string nspname; [AutoExpressionField] public IQueryable<PgClass> Tables() => As.Expression(() => Database.View<PgClass>().Where(t => t.relnamespace == this.oid && t.relkind == RelKind.Table)); } [TableName("pg_catalog.pg_class")] public class PgClass : IView { [ViewPrimaryKey] public int oid; public string relname; public int relnamespace; public char relkind; public int reltuples; [AutoExpressionField] public IQueryable<PgTrigger> Triggers() => As.Expression(() => Database.View<PgTrigger>().Where(t => t.tgrelid == this.oid)); [AutoExpressionField] public IQueryable<PgIndex> Indices() => As.Expression(() => Database.View<PgIndex>().Where(t => t.indrelid == this.oid)); [AutoExpressionField] public IQueryable<PgAttribute> Attributes() => As.Expression(() => Database.View<PgAttribute>().Where(t => t.attrelid == this.oid)); [AutoExpressionField] public IQueryable<PgConstraint> Constraints() => As.Expression(() => Database.View<PgConstraint>().Where(t => t.conrelid == this.oid)); [AutoExpressionField] public PgNamespace Namespace() => As.Expression(() => Database.View<PgNamespace>().SingleOrDefault(t => t.oid == this.relnamespace)); } public static class RelKind { public const char Table = 'r'; public const char Index = 'i'; public const char Sequence = 's'; public const char Toast = 't'; public const char View = 'v'; public const char MaterializedView = 'n'; public const char CompositeType = 'c'; public const char ForeignKey = 'f'; public const char PartitionTable = 'p'; public const char PartitionIndex = 'I'; } [TableName("pg_catalog.pg_attribute")] public class PgAttribute : IView { [ViewPrimaryKey] public int attrelid; [ViewPrimaryKey] public string attname; public int atttypid; public int atttypmod; public short attlen; public short attnum; public bool attnotnull; public char attidentity; [AutoExpressionField] public PgType Type() => As.Expression(() => Database.View<PgType>().SingleOrDefault(t => t.oid == this.atttypid)); [AutoExpressionField] public PgAttributeDef? Default() => As.Expression(() => Database.View<PgAttributeDef>().SingleOrDefault(d => d.adrelid == this.attrelid && d.adnum == this.attnum)); } [TableName("pg_catalog.pg_attrdef")] public class PgAttributeDef : IView { [ViewPrimaryKey] public int oid; public int adrelid; public short adnum; public string /*not really*/ adbin; } [TableName("pg_catalog.pg_type")] public class PgType : IView { [ViewPrimaryKey] public int oid; public string typname; public int typnamespace; public short typlen; public bool typbyval; } [TableName("pg_catalog.pg_trigger")] public class PgTrigger : IView { [ViewPrimaryKey] public int oid; public int tgrelid; public string tgname; public int tgfoid; public byte[] tgargs; [AutoExpressionField] public PgProc Proc() => As.Expression(() => Database.View<PgProc>().SingleOrDefault(p => p.oid == this.tgfoid)); } [TableName("pg_catalog.pg_proc")] public class PgProc : IView { [ViewPrimaryKey] public int oid; public int pronamespace; [AutoExpressionField] public PgNamespace Namespace() => As.Expression(() => Database.View<PgNamespace>().SingleOrDefault(t => t.oid == this.pronamespace)); public string proname; } [TableName("pg_catalog.pg_index")] public class PgIndex : IView { [ViewPrimaryKey] public int indexrelid; public int indrelid; public short indnatts; public short indnkeyatts; public bool indisunique; public bool indisprimary; public short[] indkey; public string? indexprs; public string? indpred; [AutoExpressionField] public PgClass Class() => As.Expression(() => Database.View<PgClass>().Single(t => t.oid == this.indexrelid)); } [TableName("pg_catalog.pg_constraint")] public class PgConstraint : IView { [ViewPrimaryKey] public int oid; public string conname; public int connamespace; public char contype; public int conrelid; public short[] conkey; public int confrelid; public short[] confkey; [AutoExpressionField] public PgClass TargetTable() => As.Expression(() => Database.View<PgClass>().Single(t => t.oid == this.confrelid)); [AutoExpressionField] public PgNamespace Namespace() => As.Expression(() => Database.View<PgNamespace>().SingleOrDefault(t => t.oid == this.connamespace)); } public static class ConstraintType { public const char Check = 'c'; public const char ForeignKey = 'f'; public const char PrimaryKey = 'p'; public const char Unique = 'u'; public const char Trigger= 't'; public const char Exclusion = 'x'; } } #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
/* ==================================================================== 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 TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS.Util; using TestCases.SS; using NPOI.SS.UserModel; /** * @author Yegor Kozlov */ [TestFixture] public abstract class BaseTestWorkbook { private ITestDataProvider _testDataProvider; public BaseTestWorkbook() { _testDataProvider = TestCases.HSSF.HSSFITestDataProvider.Instance; } protected BaseTestWorkbook(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } [Test] public void TestCreateSheet() { IWorkbook wb = _testDataProvider.CreateWorkbook(); Assert.AreEqual(0, wb.NumberOfSheets); //getting a sheet by invalid index or non-existing name Assert.IsNull(wb.GetSheet("Sheet1")); try { wb.GetSheetAt(0); Assert.Fail("should have thrown exceptiuon due to invalid sheet index"); } catch (ArgumentException) { // expected during successful Test } ISheet sheet0 = wb.CreateSheet(); ISheet sheet1 = wb.CreateSheet(); Assert.AreEqual("Sheet0", sheet0.SheetName); Assert.AreEqual("Sheet1", sheet1.SheetName); Assert.AreEqual(2, wb.NumberOfSheets); //fetching sheets by name is case-insensitive ISheet originalSheet = wb.CreateSheet("Sheet3"); ISheet fetchedSheet = wb.GetSheet("sheet3"); if (fetchedSheet == null) { throw new AssertionException("Identified bug 44892"); } Assert.AreEqual("Sheet3", fetchedSheet.SheetName); Assert.AreEqual(3, wb.NumberOfSheets); Assert.AreSame(originalSheet, fetchedSheet); try { wb.CreateSheet("sHeeT3"); Assert.Fail("should have thrown exceptiuon due to duplicate sheet name"); } catch (ArgumentException e) { // expected during successful Test Assert.AreEqual("The workbook already contains a sheet of this name", e.Message); } //names cannot be blank or contain any of /\*?[] String[] invalidNames = {"", "Sheet/", "Sheet\\", "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'", "My:Sheet"}; foreach (String sheetName in invalidNames) { try { wb.CreateSheet(sheetName); Assert.Fail("should have thrown exception due to invalid sheet name: " + sheetName); } catch (ArgumentException) { // expected during successful Test } } //still have 3 sheets Assert.AreEqual(3, wb.NumberOfSheets); //change the name of the 3rd sheet wb.SetSheetName(2, "I Changed!"); //try to assign an invalid name to the 2nd sheet try { wb.SetSheetName(1, "[I'm invalid]"); Assert.Fail("should have thrown exceptiuon due to invalid sheet name"); } catch (ArgumentException) { // expected during successful Test } //try to assign an invalid name to the 2nd sheet try { wb.CreateSheet(null); Assert.Fail("should have thrown exceptiuon due to invalid sheet name"); } catch (ArgumentException) { // expected during successful Test } try { wb.SetSheetName(2, null); Assert.Fail("should have thrown exceptiuon due to invalid sheet name"); } catch (ArgumentException) { // expected during successful Test } //check Assert.AreEqual(0, wb.GetSheetIndex("sheet0")); Assert.AreEqual(1, wb.GetSheetIndex("sheet1")); Assert.AreEqual(2, wb.GetSheetIndex("I Changed!")); Assert.AreSame(sheet0, wb.GetSheet("sheet0")); Assert.AreSame(sheet1, wb.GetSheet("sheet1")); Assert.AreSame(originalSheet, wb.GetSheet("I Changed!")); Assert.IsNull(wb.GetSheet("unknown")); //serialize and read again wb = _testDataProvider.WriteOutAndReadBack(wb); Assert.AreEqual(3, wb.NumberOfSheets); Assert.AreEqual(0, wb.GetSheetIndex("sheet0")); Assert.AreEqual(1, wb.GetSheetIndex("sheet1")); Assert.AreEqual(2, wb.GetSheetIndex("I Changed!")); } /** * POI allows creating sheets with names longer than 31 characters. * * Excel opens files with long sheet names without error or warning. * However, long sheet names are silently tRuncated to 31 chars. In order to * avoid funny duplicate sheet name errors, POI enforces uniqueness on only the first 31 chars. * but for the purpose of uniqueness long sheet names are silently tRuncated to 31 chars. */ [Test] public void TestCreateSheetWithLongNames() { IWorkbook wb = _testDataProvider.CreateWorkbook(); String sheetName1 = "My very long sheet name which is longer than 31 chars"; String tRuncatedSheetName1 = sheetName1.Substring(0, 31); ISheet sh1 = wb.CreateSheet(sheetName1); Assert.AreEqual(tRuncatedSheetName1, sh1.SheetName); Assert.AreSame(sh1, wb.GetSheet(tRuncatedSheetName1)); // now via wb.SetSheetName wb.SetSheetName(0, sheetName1); Assert.AreEqual(tRuncatedSheetName1, sh1.SheetName); Assert.AreSame(sh1, wb.GetSheet(tRuncatedSheetName1)); String sheetName2 = "My very long sheet name which is longer than 31 chars " + "and sheetName2.Substring(0, 31) == sheetName1.Substring(0, 31)"; try { ISheet sh2 = wb.CreateSheet(sheetName2); Assert.Fail("expected exception"); } catch (ArgumentException e) { // expected during successful Test Assert.AreEqual("The workbook already contains a sheet of this name", e.Message); } String sheetName3 = "POI allows creating sheets with names longer than 31 characters"; String tRuncatedSheetName3 = sheetName3.Substring(0, 31); ISheet sh3 = wb.CreateSheet(sheetName3); Assert.AreEqual(tRuncatedSheetName3, sh3.SheetName); Assert.AreSame(sh3, wb.GetSheet(tRuncatedSheetName3)); //serialize and read again wb = _testDataProvider.WriteOutAndReadBack(wb); Assert.AreEqual(2, wb.NumberOfSheets); Assert.AreEqual(0, wb.GetSheetIndex(tRuncatedSheetName1)); Assert.AreEqual(1, wb.GetSheetIndex(tRuncatedSheetName3)); } [Test] public void TestRemoveSheetAt() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("sheet1"); workbook.CreateSheet("sheet2"); workbook.CreateSheet("sheet3"); Assert.AreEqual(3, workbook.NumberOfSheets); workbook.RemoveSheetAt(1); Assert.AreEqual(2, workbook.NumberOfSheets); Assert.AreEqual("sheet3", workbook.GetSheetName(1)); workbook.RemoveSheetAt(0); Assert.AreEqual(1, workbook.NumberOfSheets); Assert.AreEqual("sheet3", workbook.GetSheetName(0)); workbook.RemoveSheetAt(0); Assert.AreEqual(0, workbook.NumberOfSheets); //re-create the sheets workbook.CreateSheet("sheet1"); workbook.CreateSheet("sheet2"); workbook.CreateSheet("sheet3"); Assert.AreEqual(3, workbook.NumberOfSheets); } [Test] public void TestDefaultValues() { IWorkbook b = _testDataProvider.CreateWorkbook(); Assert.AreEqual(0, b.ActiveSheetIndex); Assert.AreEqual(0, b.FirstVisibleTab); Assert.AreEqual(0, b.NumberOfNames); Assert.AreEqual(0, b.NumberOfSheets); } [Test] public void TestSheetSelection() { IWorkbook b = _testDataProvider.CreateWorkbook(); b.CreateSheet("Sheet One"); b.CreateSheet("Sheet Two"); b.SetActiveSheet(1); b.SetSelectedTab(1); b.FirstVisibleTab = (/*setter*/1); Assert.AreEqual(1, b.ActiveSheetIndex); Assert.AreEqual(1, b.FirstVisibleTab); } [Test] public void TestPrintArea() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet1 = workbook.CreateSheet("Test Print Area"); String sheetName1 = sheet1.SheetName; // workbook.SetPrintArea(0, reference); workbook.SetPrintArea(0, 1, 5, 4, 9); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.AreEqual("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea); String reference = "$A$1:$B$1"; workbook.SetPrintArea(0, reference); retrievedPrintArea = workbook.GetPrintArea(0); Assert.AreEqual("'" + sheetName1 + "'!" + reference, retrievedPrintArea); workbook.RemovePrintArea(0); Assert.IsNull(workbook.GetPrintArea(0)); } [Test] public void TestGetSetActiveSheet() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); Assert.AreEqual(0, workbook.ActiveSheetIndex); workbook.CreateSheet("sheet1"); workbook.CreateSheet("sheet2"); workbook.CreateSheet("sheet3"); // Set second sheet workbook.SetActiveSheet(1); // Test if second sheet is Set up Assert.AreEqual(1, workbook.ActiveSheetIndex); workbook.SetActiveSheet(0); // Test if second sheet is Set up Assert.AreEqual(0, workbook.ActiveSheetIndex); } [Test] public void TestSetSheetOrder() { IWorkbook wb = _testDataProvider.CreateWorkbook(); for (int i = 0; i < 10; i++) { wb.CreateSheet("Sheet " + i); } // Check the Initial order Assert.AreEqual(0, wb.GetSheetIndex("Sheet 0")); Assert.AreEqual(1, wb.GetSheetIndex("Sheet 1")); Assert.AreEqual(2, wb.GetSheetIndex("Sheet 2")); Assert.AreEqual(3, wb.GetSheetIndex("Sheet 3")); Assert.AreEqual(4, wb.GetSheetIndex("Sheet 4")); Assert.AreEqual(5, wb.GetSheetIndex("Sheet 5")); Assert.AreEqual(6, wb.GetSheetIndex("Sheet 6")); Assert.AreEqual(7, wb.GetSheetIndex("Sheet 7")); Assert.AreEqual(8, wb.GetSheetIndex("Sheet 8")); Assert.AreEqual(9, wb.GetSheetIndex("Sheet 9")); // Change wb.SetSheetOrder("Sheet 6", 0); wb.SetSheetOrder("Sheet 3", 7); wb.SetSheetOrder("Sheet 1", 9); // Check they're currently right Assert.AreEqual(0, wb.GetSheetIndex("Sheet 6")); Assert.AreEqual(1, wb.GetSheetIndex("Sheet 0")); Assert.AreEqual(2, wb.GetSheetIndex("Sheet 2")); Assert.AreEqual(3, wb.GetSheetIndex("Sheet 4")); Assert.AreEqual(4, wb.GetSheetIndex("Sheet 5")); Assert.AreEqual(5, wb.GetSheetIndex("Sheet 7")); Assert.AreEqual(6, wb.GetSheetIndex("Sheet 3")); Assert.AreEqual(7, wb.GetSheetIndex("Sheet 8")); Assert.AreEqual(8, wb.GetSheetIndex("Sheet 9")); Assert.AreEqual(9, wb.GetSheetIndex("Sheet 1")); IWorkbook wbr = _testDataProvider.WriteOutAndReadBack(wb); Assert.AreEqual(0, wbr.GetSheetIndex("Sheet 6")); Assert.AreEqual(1, wbr.GetSheetIndex("Sheet 0")); Assert.AreEqual(2, wbr.GetSheetIndex("Sheet 2")); Assert.AreEqual(3, wbr.GetSheetIndex("Sheet 4")); Assert.AreEqual(4, wbr.GetSheetIndex("Sheet 5")); Assert.AreEqual(5, wbr.GetSheetIndex("Sheet 7")); Assert.AreEqual(6, wbr.GetSheetIndex("Sheet 3")); Assert.AreEqual(7, wbr.GetSheetIndex("Sheet 8")); Assert.AreEqual(8, wbr.GetSheetIndex("Sheet 9")); Assert.AreEqual(9, wbr.GetSheetIndex("Sheet 1")); // Now Get the index by the sheet, not the name for (int i = 0; i < 10; i++) { ISheet s = wbr.GetSheetAt(i); Assert.AreEqual(i, wbr.GetSheetIndex(s)); } } [Test] public void TestCloneSheet() { IWorkbook book = _testDataProvider.CreateWorkbook(); ISheet sheet = book.CreateSheet("TEST"); sheet.CreateRow(0).CreateCell(0).SetCellValue("Test"); sheet.CreateRow(1).CreateCell(0).SetCellValue(36.6); sheet.AddMergedRegion(new CellRangeAddress(0, 1, 0, 2)); sheet.AddMergedRegion(new CellRangeAddress(1, 2, 0, 2)); Assert.IsTrue(sheet.IsSelected); ISheet ClonedSheet = book.CloneSheet(0); Assert.AreEqual("TEST (2)", ClonedSheet.SheetName); Assert.AreEqual(2, ClonedSheet.PhysicalNumberOfRows); Assert.AreEqual(2, ClonedSheet.NumMergedRegions); Assert.IsFalse(ClonedSheet.IsSelected); //Cloned sheet is a deep copy, Adding rows in the original does not affect the clone sheet.CreateRow(2).CreateCell(0).SetCellValue(1); sheet.AddMergedRegion(new CellRangeAddress(0, 2, 0, 2)); Assert.AreEqual(2, ClonedSheet.PhysicalNumberOfRows); Assert.AreEqual(2, ClonedSheet.PhysicalNumberOfRows); ClonedSheet.CreateRow(2).CreateCell(0).SetCellValue(1); ClonedSheet.AddMergedRegion(new CellRangeAddress(0, 2, 0, 2)); Assert.AreEqual(3, ClonedSheet.PhysicalNumberOfRows); Assert.AreEqual(3, ClonedSheet.PhysicalNumberOfRows); } [Test] public void TestParentReferences() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); Assert.AreSame(workbook, sheet.Workbook); IRow row = sheet.CreateRow(0); Assert.AreSame(sheet, row.Sheet); ICell cell = row.CreateCell(1); Assert.AreSame(sheet, cell.Sheet); Assert.AreSame(row, cell.Row); workbook = _testDataProvider.WriteOutAndReadBack(workbook); sheet = workbook.GetSheetAt(0); Assert.AreSame(workbook, sheet.Workbook); row = sheet.GetRow(0); Assert.AreSame(sheet, row.Sheet); cell = row.GetCell(1); Assert.AreSame(sheet, cell.Sheet); Assert.AreSame(row, cell.Row); } /** * Test is kept to ensure stub for deprecated business method passes test. * * @Deprecated remove this test when * {@link Workbook#setRepeatingRowsAndColumns(int, int, int, int, int)} * */ [Obsolete("remove this test when Workbook#setRepeatingRowsAndColumns(int, int, int, int, int) is removed ")] [Test] public void TestSetRepeatingRowsAnsColumns() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); wb.SetRepeatingRowsAndColumns(wb.GetSheetIndex(sheet1), 0, 0, 0, 3); Assert.AreEqual("1:4", sheet1.RepeatingRows.FormatAsString()); Assert.AreEqual("A:A", sheet1.RepeatingColumns.FormatAsString()); //must handle sheets with quotas, see Bugzilla #47294 ISheet sheet2 = wb.CreateSheet("My' Sheet"); wb.SetRepeatingRowsAndColumns(wb.GetSheetIndex(sheet2), 0, 0, 0, 3); Assert.AreEqual("1:4", sheet2.RepeatingRows.FormatAsString()); Assert.AreEqual("A:A", sheet1.RepeatingColumns.FormatAsString()); } /** * Tests that all of the unicode capable string fields can be Set, written and then read back */ [Test] public void TestUnicodeInAll() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); IWorkbook wb = _testDataProvider.CreateWorkbook(); ICreationHelper factory = wb.GetCreationHelper(/*getter*/); //Create a unicode dataformat (Contains euro symbol) IDataFormat df = wb.CreateDataFormat(); String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)"; short fmt = df.GetFormat(formatStr); //Create a unicode sheet name (euro symbol) ISheet s = wb.CreateSheet("\u20ac"); //Set a unicode header (you guessed it the euro symbol) IHeader h = s.Header; h.Center = (/*setter*/"\u20ac"); h.Left = (/*setter*/"\u20ac"); h.Right = (/*setter*/"\u20ac"); //Set a unicode footer IFooter f = s.Footer; f.Center = (/*setter*/"\u20ac"); f.Left = (/*setter*/"\u20ac"); f.Right = (/*setter*/"\u20ac"); IRow r = s.CreateRow(0); ICell c = r.CreateCell(1); c.SetCellValue(12.34); c.CellStyle.DataFormat = (/*setter*/fmt); ICell c2 = r.CreateCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes Test to fail c.SetCellValue(factory.CreateRichTextString("\u20ac")); ICell c3 = r.CreateCell(3); String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; c3.CellFormula = (/*setter*/formulaString); wb = _testDataProvider.WriteOutAndReadBack(wb); //Test the sheetname s = wb.GetSheet("\u20ac"); Assert.IsNotNull(s); //Test the header h = s.Header; Assert.AreEqual(h.Center, "\u20ac"); Assert.AreEqual(h.Left, "\u20ac"); Assert.AreEqual(h.Right, "\u20ac"); //Test the footer f = s.Footer; Assert.AreEqual(f.Center, "\u20ac"); Assert.AreEqual(f.Left, "\u20ac"); Assert.AreEqual(f.Right, "\u20ac"); //Test the dataformat r = s.GetRow(0); c = r.GetCell(1); df = wb.CreateDataFormat(); Assert.AreEqual(formatStr, df.GetFormat(c.CellStyle.DataFormat)); //Test the cell string value c2 = r.GetCell(2); Assert.AreEqual(c.RichStringCellValue.String, "\u20ac"); //Test the cell formula c3 = r.GetCell(3); Assert.AreEqual(c3.CellFormula, formulaString); } private IWorkbook newSetSheetNameTestingWorkbook() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh1 = wb.CreateSheet("Worksheet"); ISheet sh2 = wb.CreateSheet("Testing 47100"); ISheet sh3 = wb.CreateSheet("To be Renamed"); IName name1 = wb.CreateName(); name1.NameName = (/*setter*/"sale_1"); name1.RefersToFormula = (/*setter*/"Worksheet!$A$1"); IName name2 = wb.CreateName(); name2.NameName = (/*setter*/"sale_2"); name2.RefersToFormula = (/*setter*/"'Testing 47100'!$A$1"); IName name3 = wb.CreateName(); name3.NameName = (/*setter*/"sale_3"); name3.RefersToFormula = (/*setter*/"'Testing 47100'!$B$1"); IName name4 = wb.CreateName(); name4.NameName = (/*setter*/"sale_4"); name4.RefersToFormula = (/*setter*/"'To be Renamed'!$A$3"); sh1.CreateRow(0).CreateCell(0).CellFormula = (/*setter*/"SUM('Testing 47100'!A1:C1)"); sh1.CreateRow(1).CreateCell(0).CellFormula = (/*setter*/"SUM('Testing 47100'!A1:C1,'To be Renamed'!A1:A5)"); sh1.CreateRow(2).CreateCell(0).CellFormula = (/*setter*/"sale_2+sale_3+'Testing 47100'!C1"); sh2.CreateRow(0).CreateCell(0).SetCellValue(1); sh2.GetRow(0).CreateCell(1).SetCellValue(2); sh2.GetRow(0).CreateCell(2).SetCellValue(3); sh3.CreateRow(0).CreateCell(0).SetCellValue(1); sh3.CreateRow(1).CreateCell(0).SetCellValue(2); sh3.CreateRow(2).CreateCell(0).SetCellValue(3); sh3.CreateRow(3).CreateCell(0).SetCellValue(4); sh3.CreateRow(4).CreateCell(0).SetCellValue(5); sh3.CreateRow(5).CreateCell(0).CellFormula = (/*setter*/"sale_3"); sh3.CreateRow(6).CreateCell(0).CellFormula = (/*setter*/"'Testing 47100'!C1"); return wb; } /** * Ensure that Workbook#setSheetName updates all dependent formulas and named ranges * * @see <a href="https://issues.apache.org/bugzilla/Show_bug.cgi?id=47100">Bugzilla 47100</a> */ [Test] public void TestSetSheetName() { IWorkbook wb = newSetSheetNameTestingWorkbook(); ISheet sh1 = wb.GetSheetAt(0); IName sale_2 = wb.GetNameAt(1); IName sale_3 = wb.GetNameAt(2); IName sale_4 = wb.GetNameAt(3); Assert.AreEqual("sale_2", sale_2.NameName); Assert.AreEqual("'Testing 47100'!$A$1", sale_2.RefersToFormula); Assert.AreEqual("sale_3", sale_3.NameName); Assert.AreEqual("'Testing 47100'!$B$1", sale_3.RefersToFormula); Assert.AreEqual("sale_4", sale_4.NameName); Assert.AreEqual("'To be Renamed'!$A$3", sale_4.RefersToFormula); IFormulaEvaluator Evaluator = wb.GetCreationHelper(/*getter*/).CreateFormulaEvaluator(); ICell cell0 = sh1.GetRow(0).GetCell(0); ICell cell1 = sh1.GetRow(1).GetCell(0); ICell cell2 = sh1.GetRow(2).GetCell(0); Assert.AreEqual("SUM('Testing 47100'!A1:C1)", cell0.CellFormula); Assert.AreEqual("SUM('Testing 47100'!A1:C1,'To be Renamed'!A1:A5)", cell1.CellFormula); Assert.AreEqual("sale_2+sale_3+'Testing 47100'!C1", cell2.CellFormula); Assert.AreEqual(6.0, Evaluator.Evaluate(cell0).NumberValue); Assert.AreEqual(21.0, Evaluator.Evaluate(cell1).NumberValue); Assert.AreEqual(6.0, Evaluator.Evaluate(cell2).NumberValue); wb.SetSheetName(1, "47100 - First"); wb.SetSheetName(2, "47100 - Second"); Assert.AreEqual("sale_2", sale_2.NameName); Assert.AreEqual("'47100 - First'!$A$1", sale_2.RefersToFormula); Assert.AreEqual("sale_3", sale_3.NameName); Assert.AreEqual("'47100 - First'!$B$1", sale_3.RefersToFormula); Assert.AreEqual("sale_4", sale_4.NameName); Assert.AreEqual("'47100 - Second'!$A$3", sale_4.RefersToFormula); Assert.AreEqual("SUM('47100 - First'!A1:C1)", cell0.CellFormula); Assert.AreEqual("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.CellFormula); Assert.AreEqual("sale_2+sale_3+'47100 - First'!C1", cell2.CellFormula); Evaluator.ClearAllCachedResultValues(); Assert.AreEqual(6.0, Evaluator.Evaluate(cell0).NumberValue); Assert.AreEqual(21.0, Evaluator.Evaluate(cell1).NumberValue); Assert.AreEqual(6.0, Evaluator.Evaluate(cell2).NumberValue); wb = _testDataProvider.WriteOutAndReadBack(wb); sh1 = wb.GetSheetAt(0); sale_2 = wb.GetNameAt(1); sale_3 = wb.GetNameAt(2); sale_4 = wb.GetNameAt(3); cell0 = sh1.GetRow(0).GetCell(0); cell1 = sh1.GetRow(1).GetCell(0); cell2 = sh1.GetRow(2).GetCell(0); Assert.AreEqual("sale_2", sale_2.NameName); Assert.AreEqual("'47100 - First'!$A$1", sale_2.RefersToFormula); Assert.AreEqual("sale_3", sale_3.NameName); Assert.AreEqual("'47100 - First'!$B$1", sale_3.RefersToFormula); Assert.AreEqual("sale_4", sale_4.NameName); Assert.AreEqual("'47100 - Second'!$A$3", sale_4.RefersToFormula); Assert.AreEqual("SUM('47100 - First'!A1:C1)", cell0.CellFormula); Assert.AreEqual("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.CellFormula); Assert.AreEqual("sale_2+sale_3+'47100 - First'!C1", cell2.CellFormula); Evaluator = wb.GetCreationHelper(/*getter*/).CreateFormulaEvaluator(); Assert.AreEqual(6.0, Evaluator.Evaluate(cell0).NumberValue); Assert.AreEqual(21.0, Evaluator.Evaluate(cell1).NumberValue); Assert.AreEqual(6.0, Evaluator.Evaluate(cell2).NumberValue); } public void ChangeSheetNameWithSharedFormulas(String sampleFile) { IWorkbook wb = _testDataProvider.OpenSampleWorkbook(sampleFile); IFormulaEvaluator Evaluator = wb.GetCreationHelper(/*getter*/).CreateFormulaEvaluator(); ISheet sheet = wb.GetSheetAt(0); for (int rownum = 1; rownum <= 40; rownum++) { ICell cellA = sheet.GetRow(1).GetCell(0); ICell cellB = sheet.GetRow(1).GetCell(1); Assert.AreEqual(cellB.StringCellValue, Evaluator.Evaluate(cellA).StringValue); } wb.SetSheetName(0, "Renamed by POI"); Evaluator.ClearAllCachedResultValues(); for (int rownum = 1; rownum <= 40; rownum++) { ICell cellA = sheet.GetRow(1).GetCell(0); ICell cellB = sheet.GetRow(1).GetCell(1); Assert.AreEqual(cellB.StringCellValue, Evaluator.Evaluate(cellA).StringValue); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // 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.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis { class SaveAnalysis { private List<string> _errors = new List<string>(); private Dictionary<AnalysisValue, string> _classNames = new Dictionary<AnalysisValue, string>(); private List<AnalysisValue> _path = new List<AnalysisValue>(); private Dictionary<string, Dictionary<string, object>> _typeNames = new Dictionary<string, Dictionary<string, object>>(); private Dictionary<string, string> _MemoizedStrings = new Dictionary<string, string>(); private Dictionary<string, object[]> _moduleNames = new Dictionary<string, object[]>(); private static readonly List<object> _EmptyMro = new List<object>(); private PythonAnalyzer _curAnalyzer; private ModuleInfo _curModule; public void Save(PythonAnalyzer state, string outDir) { _curAnalyzer = state; foreach (var modKeyValue in state.Modules) { string name = modKeyValue.Key; ModuleInfo moduleInfo; if ((moduleInfo = modKeyValue.Value.Module as ModuleInfo) != null) { _curModule = moduleInfo; var info = SerializeModule(moduleInfo); WriteModule(outDir, name, info, moduleInfo.Scope.AllVariables.Keys()); } } foreach (var error in _errors) { Console.WriteLine(error); } } private void WriteModule(string outDir, string name, Dictionary<string, object> info, IEnumerable<string> globals) { for (int i = 0; i < 10; i++) { try { using (var writer = new FileStream(Path.Combine(outDir, name + ".idb"), FileMode.Create, FileAccess.ReadWrite)) { new Pickler(writer).Dump(info); } break; } catch (IOException ex) { // race with a reader, retry... http://pytools.codeplex.com/workitem/570 Console.WriteLine("Could not access {0} {1}", name + ".idb", ex); Thread.Sleep(1000); } } for (int i = 0; i < 10; i++) { try { using (var writer = new StreamWriter(new FileStream(Path.Combine(outDir, name + ".idb.$memlist"), FileMode.Create, FileAccess.ReadWrite))) { object membersObj; Dictionary<string, object> members; if (!info.TryGetValue("members", out membersObj) || (members = membersObj as Dictionary<string, object>) == null) { if (globals != null) { members = globals.ToDictionary(k => k, _ => (object)null); } else { members = new Dictionary<string, object>(); } } foreach (var memberName in members.Keys) { writer.WriteLine(memberName); } } break; } catch (IOException ex) { // race with a reader, retry... http://pytools.codeplex.com/workitem/570 Console.WriteLine("Could not access {0} {1}", name + ".idb.$memlist", ex); Thread.Sleep(1000); } } } private Dictionary<string, object> SerializeModule(ModuleInfo moduleInfo) { var children = GenerateChildModules(moduleInfo); return new Dictionary<string, object>() { { "members", GenerateMembers(moduleInfo, children) }, { "doc", MemoizeString(moduleInfo.Documentation) }, { "children", children }, { "filename", moduleInfo.ProjectEntry.FilePath } }; } private List<object> GenerateChildModules(ModuleInfo moduleInfo) { var res = new HashSet<object>(moduleInfo.GetChildrenPackages(null).Select(kv => kv.Key)); // Add any child built-in modules as well. This will include the modules that are part of the package, // but which do not participate in analysis (e.g. native modules). foreach (var child in from moduleName in moduleInfo.ProjectEntry.ProjectState.Interpreter.GetModuleNames() let lastDot = moduleName.LastIndexOf('.') where lastDot >= 0 let packageName = moduleName.Substring(0, lastDot) where packageName == moduleInfo.Name select moduleName.Substring(lastDot + 1) ) { // Only include the child if it is actually importable. As a // side-effect, we really import the child, which means that // GenerateMembers will not exclude it. ModuleReference modTableRef; if (moduleInfo.ProjectEntry.ProjectState.Modules.TryImport(moduleInfo.Name + "." + child, out modTableRef)) { res.Add(child); } } return res.ToList(); } private Dictionary<string, object> GenerateMembers(ModuleInfo moduleInfo, IEnumerable<object> children) { Dictionary<string, object> res = new Dictionary<string, object>(); foreach (var keyValue in moduleInfo.Scope.AllVariables) { if (keyValue.Value.IsEphemeral) { // Never got a value, so leave it out. continue; } res[keyValue.Key] = GenerateMember(keyValue.Value, moduleInfo); } foreach (var child in children.OfType<string>()) { object modRef = null; ModuleReference modTableRef; if (moduleInfo.ProjectEntry.ProjectState.Modules.TryGetImportedModule(moduleInfo.Name + "." + child, out modTableRef) && modTableRef != null && modTableRef.Module != null ) { MultipleMemberInfo mmi; if (modTableRef.Module is ModuleInfo || modTableRef.Module is BuiltinModule) { modRef = new Dictionary<string, object> { { "kind", "moduleref" }, { "value", GetModuleName(moduleInfo.Name + "." + child) } }; } else if ((mmi = modTableRef.Module as MultipleMemberInfo) != null) { modRef = new Dictionary<string, object> { { "kind", "multiple" }, { "value", new Dictionary<string, object> { { "members", mmi.Members .Select(m => m.Name) .Where(n => !string.IsNullOrEmpty(n)) .Select(GetModuleName) .ToArray<object>() } } } }; } } object existing; if (res.TryGetValue(child, out existing) && IsValidMember(existing)) { var members1 = GetMultipleMembersOrDefault(existing) ?? new object[] { existing }; var members2 = GetMultipleMembersOrDefault(modRef) ?? new object[] { modRef }; var members = members1.Concat(members2).Distinct(ModuleReferenceComparer.Instance).ToArray(); if (members.Length > 1) { res[child] = new Dictionary<string, object> { { "kind", "multiple" }, { "value", new Dictionary<string, object> { { "members", members } } } }; } else if (members.Length == 1) { res[child] = members[0]; } } else { res[child] = modRef; } } return res; } private class ModuleReferenceComparer : IEqualityComparer<object> { public static readonly IEqualityComparer<object> Instance = new ModuleReferenceComparer(); private ModuleReferenceComparer() { } public new bool Equals(object x, object y) { if (object.ReferenceEquals(x, y)) { return true; } var asDict1 = x as Dictionary<string, object>; var asDict2 = y as Dictionary<string, object>; if (asDict1 == null || asDict2 == null) { return false; } object obj; if (!asDict1.TryGetValue("kind", out obj) || (obj as string) != "moduleref") { return false; } if (!asDict2.TryGetValue("kind", out obj) || (obj as string) != "moduleref") { return false; } object[] modref1, modref2; if (!asDict1.TryGetValue("value", out obj) || (modref1 = obj as object[]) == null) { return false; } if (!asDict2.TryGetValue("value", out obj) || (modref2 = obj as object[]) == null) { return false; } return modref1.SequenceEqual(modref2); } public int GetHashCode(object obj) { var asDict = obj as Dictionary<string, object>; if (asDict == null) { return 0; } object o; if (!asDict.TryGetValue("kind", out o) || (o as string) != "moduleref") { return 0; } object[] modref; if (!asDict.TryGetValue("value", out o) || (modref = o as object[]) == null) { return 0; } return modref.Aggregate(48527, (a, n) => a ^ (n != null ? n.GetHashCode() : 0)); } } private static bool IsValidMember(object info) { var asDict = info as Dictionary<string, object>; if (asDict == null) { return false; } object obj; string kind; if (!asDict.TryGetValue("kind", out obj) || (kind = obj as string) == null) { return false; } if (!asDict.TryGetValue("value", out obj)) { return false; } if (kind == "data" && (asDict = obj as Dictionary<string, object>) != null) { // { 'data': { 'type': None } } is invalid return asDict.TryGetValue("type", out obj) && obj != null; } return true; } private static object[] GetMultipleMembersOrDefault(object info) { var asDict = info as Dictionary<string, object>; if (asDict == null) { return null; } object obj; string kind; if (!asDict.TryGetValue("kind", out obj) || (kind = obj as string) == null || kind != "multiple") { return null; } if (!asDict.TryGetValue("value", out obj) || (asDict = obj as Dictionary<string, object>) == null) { return null; } if (!asDict.TryGetValue("members", out obj)) { return null; } return obj as object[]; } private object GenerateMember(VariableDef variableDef, ModuleInfo declModule, bool isRef = false) { Dictionary<string, object> memberEntry = new Dictionary<string, object>() { { "kind", GetMemberKind(variableDef, declModule, isRef) }, { "value", GetMemberValue(variableDef, declModule, isRef) } }; return memberEntry; } private object GetMemberValues(VariableDef[] variableDefs, ModuleInfo declModule, bool isRef) { List<object> res = new List<object>(); foreach (var variableDef in variableDefs) { res.Add(GetMemberValue(variableDef, declModule, isRef)); } return res; } private object GetMemberValue(VariableDef variableDef, ModuleInfo declModule, bool isRef) { return GetMemberValue(variableDef.TypesNoCopy, declModule, isRef); } private object GetMemberValue(IAnalysisSet types, ModuleInfo declModule, bool isRef) { if (types.Count == 1) { var type = types.First(); var res = GetMemberValueInternal(type, declModule, isRef); if (res == null) { _errors.Add(String.Format("Cannot save single member: {0}", types.First())); } return res; } else if (types.Count == 0) { return new Dictionary<string, object>() { { "type", null } }; } else { List<object> res = new List<object>(); foreach (var type in types) { res.Add( new Dictionary<string, object>() { { "kind", GetMemberKind(type, declModule, isRef) }, { "value", GetMemberValueInternal(type, declModule, isRef) } } ); } return new Dictionary<string, object>() { { "members", res.ToArray() } }; } } private object GetMemberValueInternal(AnalysisValue type, ModuleInfo declModule, bool isRef) { SpecializedNamespace specialCallable = type as SpecializedNamespace; if (specialCallable != null) { if (specialCallable.Original == null) { return null; } return GetMemberValueInternal(specialCallable.Original, declModule, isRef); } switch (type.MemberType) { case PythonMemberType.Function: FunctionInfo fi = type as FunctionInfo; if (fi != null) { if (fi.DeclaringModule.GetModuleInfo() != declModule) { return GenerateFuncRef(fi); } else { return GenerateFunction(fi); } } BuiltinFunctionInfo bfi = type as BuiltinFunctionInfo; if (bfi != null) { return GenerateFuncRef(bfi); } return "function"; case PythonMemberType.Method: BoundMethodInfo mi = type as BoundMethodInfo; if (mi != null) { return GenerateMethod(mi); } return "method"; case PythonMemberType.Property: FunctionInfo prop = type as FunctionInfo; if (prop != null) { return GenerateProperty(prop); } break; case PythonMemberType.Class: ClassInfo ci = type as ClassInfo; if (ci != null) { if (isRef || ci.DeclaringModule.GetModuleInfo() != declModule) { // TODO: Save qualified name so that classes defined in classes/function can be resolved return GetTypeRef(ci.DeclaringModule.ModuleName, ci.Name); } else { return GenerateClass(ci, declModule); } } BuiltinClassInfo bci = type as BuiltinClassInfo; if (bci != null) { return GetTypeRef(bci.PythonType.DeclaringModule.Name, bci.PythonType.Name); } return "type"; case PythonMemberType.Constant: ConstantInfo constantInfo = type as ConstantInfo; if (constantInfo != null) { return GenerateConstant(constantInfo); } break; case PythonMemberType.Module: if (type is ModuleInfo) { return GetModuleName(((ModuleInfo)type).Name); } else if (type is BuiltinModule) { return GetModuleName(((BuiltinModule)type).Name); } break; case PythonMemberType.Instance: return new Dictionary<string, object> { { "type", GenerateTypeName(type, true) } }; default: return new Dictionary<string, object>() { { "type", GenerateTypeName(type.PythonType) } }; } return null; } private object GenerateFuncRef(FunctionInfo fi) { string name = "."; for (var cd = fi.FunctionDefinition.Parent as ClassDefinition; cd != null; cd = cd.Parent as ClassDefinition) { name = "." + cd.Name + name; } name = fi.DeclaringModule.ModuleName + name + fi.Name; return new Dictionary<string, object>() { { "func_name", MemoizeString(name) } }; } private object GenerateFuncRef(BuiltinFunctionInfo bfi) { string name = bfi.Function.DeclaringModule.Name; if (bfi.Function.DeclaringType != null) { name += "." + bfi.Function.DeclaringType.Name; } name += "." + bfi.Function.Name; return new Dictionary<string, object>() { { "func_name", MemoizeString(name) } }; } private string GetMemberKind(VariableDef variableDef, ModuleInfo declModule, bool isRef) { if (variableDef.Types.Count == 1) { return GetMemberKind(variableDef.Types.First(), declModule, isRef); } else if (variableDef.Types.Count == 0) { // typed to object return "data"; } else { return "multiple"; } } private static string GetMemberKind(AnalysisValue type, ModuleInfo declModule, bool isRef) { SpecializedNamespace specialCallable = type as SpecializedNamespace; if (specialCallable != null) { if (specialCallable.Original == null) { return "data"; } return GetMemberKind(specialCallable.Original, declModule, isRef); } switch (type.MemberType) { case PythonMemberType.Function: if (type is BuiltinFunctionInfo || type.DeclaringModule != declModule.ProjectEntry) { return "funcref"; } return "function"; case PythonMemberType.Method: return "method"; case PythonMemberType.Property: return "property"; case PythonMemberType.Class: if (isRef || type is BuiltinClassInfo || (type is ClassInfo && type.DeclaringModule.GetModuleInfo() != declModule)) { return "typeref"; } return "type"; case PythonMemberType.Module: return "moduleref"; case PythonMemberType.Instance: default: return "data"; } } private object GenerateProperty(FunctionInfo prop) { return new Dictionary<string, object>() { { "doc", MemoizeString(prop.Documentation) }, { "type", GenerateTypeName(GetFunctionReturnTypes(prop), true) }, { "location", GenerateLocation(prop.Locations) } }; } private static IAnalysisSet GetFunctionReturnTypes(FunctionInfo func) { return func.GetReturnValue(); } private Dictionary<string, object> GenerateConstant(ConstantInfo constantInfo) { return new Dictionary<string, object>() { { "type", GenerateTypeName(constantInfo.PythonType) } }; } private Dictionary<string, object> GenerateClass(ClassInfo ci, ModuleInfo declModule) { return new Dictionary<string, object>() { { "mro", GetClassMro(ci) }, { "bases", GetClassBases(ci) }, { "members", GetClassMembers(ci, declModule) }, { "doc", MemoizeString(ci.Documentation) }, { "builtin", false }, { "location", GenerateLocation(ci.Locations) } }; } private object GetTypeRef(string moduleName, string className) { return new List<object> { GetTypeName(moduleName, className) }; } private object GetTypeName(string moduleName, string className) { // memoize types names for a more efficient on disk representation. object typeName; Dictionary<string, object> typeNames; if (!_typeNames.TryGetValue(moduleName, out typeNames)) { _typeNames[moduleName] = typeNames = new Dictionary<string, object>(); } if (!typeNames.TryGetValue(className, out typeName)) { typeNames[className] = typeName = new object[] { MemoizeString(moduleName), MemoizeString(className) }; } return typeName; } private object[] GetModuleName(string moduleName) { // memoize types names for a more efficient on disk representation. object[] name; if (!_moduleNames.TryGetValue(moduleName, out name)) { _moduleNames[moduleName] = name = new object[] { MemoizeString(moduleName), string.Empty }; } return name; } private object GetClassMembers(ClassInfo ci, ModuleInfo declModule) { Dictionary<string, object> memTable = new Dictionary<string, object>(); foreach (var keyValue in ci.Scope.AllVariables) { if (keyValue.Value.IsEphemeral) { continue; } memTable[keyValue.Key] = GenerateMember(keyValue.Value, declModule, true); } if (ci.Instance.InstanceAttributes != null) { foreach (var keyValue in ci.Instance.InstanceAttributes) { if (keyValue.Value.IsEphemeral) { continue; } memTable[keyValue.Key] = GenerateMember(keyValue.Value, declModule, true); } } return memTable; } private List<object> GetClassBases(ClassInfo ci) { List<object> res = new List<object>(); foreach (var baseClassSet in ci.Bases) { foreach (var baseClass in baseClassSet) { var typeName = GenerateTypeName(baseClass, true); if (typeName != null) { res.Add(typeName); } } } return res; } private object GenerateTypeName(IAnalysisSet name, bool isRef) { if (name.Count == 0) { return null; } else if (name.Count == 1) { return GenerateTypeName(name.First(), isRef); } return name.Select(ns => GenerateTypeName(ns, isRef)).Distinct().ToList<object>(); } private object GenerateTypeName(AnalysisValue baseClass, bool isRef) { ClassInfo ci = baseClass as ClassInfo; if (ci != null) { return GetTypeName(((ProjectEntry)ci.DeclaringModule).GetModuleInfo().Name, ci.ClassDefinition.Name); } BuiltinClassInfo bci = baseClass as BuiltinClassInfo; if (bci != null) { return GenerateTypeName(bci._type); } IterableValue iteri = baseClass as IterableValue; if (iteri != null) { return GenerateTypeName(iteri.PythonType, isRef, iteri.IndexTypes); } InstanceInfo ii = baseClass as InstanceInfo; if (ii != null) { return GenerateTypeName(ii.ClassInfo, isRef); } BuiltinInstanceInfo bii = baseClass as BuiltinInstanceInfo; if (bii != null) { return GenerateTypeName(bii.ClassInfo, isRef); } return GenerateTypeName(baseClass.PythonType); } private object GenerateTypeName(IPythonType type) { if (type != null) { return GetTypeName(type.DeclaringModule.Name, type.Name); } return null; } private object GenerateTypeName(IPythonType type, bool isRef, VariableDef[] indexTypes) { if (type != null) { if (indexTypes == null || indexTypes.Length == 0) { return GetTypeName(type.DeclaringModule.Name, type.Name); } var moduleName = type.DeclaringModule.Name; var className = type.Name + "`" + string.Join(",", indexTypes.Select(t => t.TypesNoCopy.ToString())); object typeName; Dictionary<string, object> typeNames; if (!_typeNames.TryGetValue(moduleName, out typeNames)) { _typeNames[moduleName] = typeNames = new Dictionary<string, object>(); } if (!typeNames.TryGetValue(className, out typeName)) { var mModuleName = MemoizeString(moduleName); var mTypeName = MemoizeString(type.Name); // Create a type without the typename that will be used if // the index types recurse. typeNames[className] = typeName = new object[] { mModuleName, mTypeName }; typeNames[className] = typeName = new object[] { mModuleName, mTypeName, indexTypes.Select(vd => GenerateTypeName(vd.TypesNoCopy, isRef)).ToList<object>(), }; } return typeName; } return null; } private object GetClassMro(ClassInfo ci) { List<object> res = new List<object>(); foreach (var mroClassSet in ci.Mro) { foreach (var mroClass in mroClassSet) { var typeName = GenerateTypeName(mroClass, true); if (typeName != null) { res.Add(typeName); } } } return res; } private Dictionary<string, object> GenerateFunction(FunctionInfo fi) { // TODO: Include inner classes/functions var res = new Dictionary<string, object>() { { "doc", fi.Documentation }, { "builtin", false }, { "location", GenerateLocation(fi.Locations) }, { "overloads", GenerateOverloads(fi) } }; if (fi.IsStatic) { res["static"] = fi.IsStatic; } if (fi.IsClassMethod) { res["classmethod"] = true; } return res; } private Dictionary<string, object> GenerateMethod(BoundMethodInfo bmi) { var res = GenerateFunction(bmi.Function); if (bmi.Instance != null && bmi.Instance.TypeId != BuiltinTypeId.NoneType) { res["bound"] = true; } return res; } private static object[] GenerateLocation(LocationInfo location) { return new object[] { location.StartLine, location.StartColumn }; } private static object[] GenerateLocation(IEnumerable<LocationInfo> locations) { // TODO: Support saving and loading multiple locations for a single definition Debug.Assert(locations.Count() == 1); var location = locations.FirstOrDefault(); if (location != null) { return GenerateLocation(location); } return new object[0]; } private List<object> GenerateOverloads(FunctionInfo fi) { var res = new List<object>(); // TODO: Store distinct calls as separate overloads res.Add(new Dictionary<string, object> { { "args", GenerateArgInfo(fi, fi.GetParameterTypes()) }, { "ret_type", GenerateTypeName(fi.GetReturnValue(), true) } }); return res; } private object[] GenerateArgInfo(FunctionInfo fi, IAnalysisSet[] parameters) { var res = new object[Math.Min(fi.FunctionDefinition.Parameters.Count, parameters.Length)]; for (int i = 0; i < res.Length; i++) { res[i] = GenerateParameter(fi.FunctionDefinition.Parameters[i], parameters[i]); } return res; } private string MemoizeString(string input) { if (input == null) { return null; } string res; if (!_MemoizedStrings.TryGetValue(input, out res)) { _MemoizedStrings[input] = res = input; } return res; } private object GenerateParameter(Parameter param, IAnalysisSet typeInfo) { Dictionary<string, object> res = new Dictionary<string, object>(); if (param.Kind == ParameterKind.Dictionary) { res["arg_format"] = "**"; } else if (param.Kind == ParameterKind.List) { res["arg_format"] = "*"; } res["name"] = MemoizeString(param.Name); res["type"] = GenerateTypeName(typeInfo, true); var defaultValue = FunctionInfo.GetDefaultValue(_curAnalyzer, param, _curModule.ProjectEntry.Tree); if (defaultValue != null) { res["default_value"] = defaultValue; } return res; } } }
// 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.IO; using System.Xml; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Globalization; using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Xml { internal class XmlBufferReader { private XmlDictionaryReader _reader; private Stream _stream; private byte[] _streamBuffer; private byte[] _buffer; private int _offsetMin; private int _offsetMax; private IXmlDictionary _dictionary; private XmlBinaryReaderSession _session; private byte[] _guid; private int _offset; private const int maxBytesPerChar = 3; private char[] _chars; private int _windowOffset; private int _windowOffsetMax; private ValueHandle _listValue; private static XmlBufferReader s_empty = new XmlBufferReader(Array.Empty<byte>()); public XmlBufferReader(XmlDictionaryReader reader) { _reader = reader; } public XmlBufferReader(byte[] buffer) { _reader = null; _buffer = buffer; } public static XmlBufferReader Empty { get { return s_empty; } } public byte[] Buffer { get { return _buffer; } } public bool IsStreamed { get { return _stream != null; } } public void SetBuffer(Stream stream, IXmlDictionary dictionary, XmlBinaryReaderSession session) { if (_streamBuffer == null) { _streamBuffer = new byte[128]; } SetBuffer(stream, _streamBuffer, 0, 0, dictionary, session); _windowOffset = 0; _windowOffsetMax = _streamBuffer.Length; } public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) { SetBuffer(null, buffer, offset, count, dictionary, session); } private void SetBuffer(Stream stream, byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) { _stream = stream; _buffer = buffer; _offsetMin = offset; _offset = offset; _offsetMax = offset + count; _dictionary = dictionary; _session = session; } public void Close() { if (_streamBuffer != null && _streamBuffer.Length > 4096) { _streamBuffer = null; } if (_stream != null) { _stream.Dispose(); _stream = null; } _buffer = Array.Empty<byte>(); _offset = 0; _offsetMax = 0; _windowOffset = 0; _windowOffsetMax = 0; _dictionary = null; _session = null; } public bool EndOfFile { get { return _offset == _offsetMax && !TryEnsureByte(); } } public byte GetByte() { int offset = _offset; if (offset < _offsetMax) return _buffer[offset]; else return GetByteHard(); } public void SkipByte() { Advance(1); } private byte GetByteHard() { EnsureByte(); return _buffer[_offset]; } public byte[] GetBuffer(int count, out int offset) { offset = _offset; if (offset <= _offsetMax - count) return _buffer; return GetBufferHard(count, out offset); } public byte[] GetBuffer(int count, out int offset, out int offsetMax) { offset = _offset; if (offset <= _offsetMax - count) { offsetMax = _offset + count; } else { TryEnsureBytes(Math.Min(count, _windowOffsetMax - offset)); offsetMax = _offsetMax; } return _buffer; } public byte[] GetBuffer(out int offset, out int offsetMax) { offset = _offset; offsetMax = _offsetMax; return _buffer; } private byte[] GetBufferHard(int count, out int offset) { offset = _offset; EnsureBytes(count); return _buffer; } private void EnsureByte() { if (!TryEnsureByte()) XmlExceptionHelper.ThrowUnexpectedEndOfFile(_reader); } private bool TryEnsureByte() { if (_stream == null) return false; DiagnosticUtility.DebugAssert(_offsetMax < _windowOffsetMax, ""); if (_offsetMax >= _buffer.Length) return TryEnsureBytes(1); int b = _stream.ReadByte(); if (b == -1) return false; _buffer[_offsetMax++] = (byte)b; return true; } private void EnsureBytes(int count) { if (!TryEnsureBytes(count)) XmlExceptionHelper.ThrowUnexpectedEndOfFile(_reader); } private bool TryEnsureBytes(int count) { if (_stream == null) return false; DiagnosticUtility.DebugAssert(_offset <= int.MaxValue - count, ""); int newOffsetMax = _offset + count; if (newOffsetMax < _offsetMax) return true; DiagnosticUtility.DebugAssert(newOffsetMax <= _windowOffsetMax, ""); if (newOffsetMax > _buffer.Length) { byte[] newBuffer = new byte[Math.Max(newOffsetMax, _buffer.Length * 2)]; System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _offsetMax); _buffer = newBuffer; _streamBuffer = newBuffer; } int needed = newOffsetMax - _offsetMax; while (needed > 0) { int actual = _stream.Read(_buffer, _offsetMax, needed); if (actual == 0) return false; _offsetMax += actual; needed -= actual; } return true; } public void Advance(int count) { DiagnosticUtility.DebugAssert(_offset + count <= _offsetMax, ""); _offset += count; } public void InsertBytes(byte[] buffer, int offset, int count) { DiagnosticUtility.DebugAssert(_stream != null, ""); if (_offsetMax > buffer.Length - count) { byte[] newBuffer = new byte[_offsetMax + count]; System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _offsetMax); _buffer = newBuffer; _streamBuffer = newBuffer; } System.Buffer.BlockCopy(_buffer, _offset, _buffer, _offset + count, _offsetMax - _offset); _offsetMax += count; System.Buffer.BlockCopy(buffer, offset, _buffer, _offset, count); } public void SetWindow(int windowOffset, int windowLength) { // [0...elementOffset-1][elementOffset..offset][offset..offsetMax-1][offsetMax..buffer.Length] // ^--Elements, Attributes in scope // ^-- The node just consumed // ^--Data buffered, not consumed // ^--Unused space if (windowOffset > int.MaxValue - windowLength) windowLength = int.MaxValue - windowOffset; if (_offset != windowOffset) { System.Buffer.BlockCopy(_buffer, _offset, _buffer, windowOffset, _offsetMax - _offset); _offsetMax = windowOffset + (_offsetMax - _offset); _offset = windowOffset; } _windowOffset = windowOffset; _windowOffsetMax = Math.Max(windowOffset + windowLength, _offsetMax); } public int Offset { get { return _offset; } set { DiagnosticUtility.DebugAssert(value >= _offsetMin && value <= _offsetMax, ""); _offset = value; } } public int ReadBytes(int count) { DiagnosticUtility.DebugAssert(count >= 0, ""); int offset = _offset; if (offset > _offsetMax - count) EnsureBytes(count); _offset += count; return offset; } public int ReadMultiByteUInt31() { int i = GetByte(); Advance(1); if ((i & 0x80) == 0) return i; i &= 0x7F; int j = GetByte(); Advance(1); i |= ((j & 0x7F) << 7); if ((j & 0x80) == 0) return i; int k = GetByte(); Advance(1); i |= ((k & 0x7F) << 14); if ((k & 0x80) == 0) return i; int l = GetByte(); Advance(1); i |= ((l & 0x7F) << 21); if ((l & 0x80) == 0) return i; int m = GetByte(); Advance(1); i |= (m << 28); if ((m & 0xF8) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return i; } public int ReadUInt8() { byte b = GetByte(); Advance(1); return b; } public int ReadInt8() { return (sbyte)ReadUInt8(); } public int ReadUInt16() { int offset; byte[] buffer = GetBuffer(2, out offset); int i = buffer[offset + 0] + (buffer[offset + 1] << 8); Advance(2); return i; } public int ReadInt16() { return (Int16)ReadUInt16(); } public int ReadInt32() { int offset; byte[] buffer = GetBuffer(4, out offset); byte b1 = buffer[offset + 0]; byte b2 = buffer[offset + 1]; byte b3 = buffer[offset + 2]; byte b4 = buffer[offset + 3]; Advance(4); return (((((b4 << 8) + b3) << 8) + b2) << 8) + b1; } public int ReadUInt31() { int i = ReadInt32(); if (i < 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return i; } public long ReadInt64() { Int64 lo = (UInt32)ReadInt32(); Int64 hi = (UInt32)ReadInt32(); return (hi << 32) + lo; } public unsafe float ReadSingle() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Single, out offset); float value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(float) == 4, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; Advance(ValueHandleLength.Single); return value; } public unsafe double ReadDouble() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Double, out offset); double value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(double) == 8, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; pb[4] = buffer[offset + 4]; pb[5] = buffer[offset + 5]; pb[6] = buffer[offset + 6]; pb[7] = buffer[offset + 7]; Advance(ValueHandleLength.Double); return value; } public unsafe decimal ReadDecimal() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Decimal, out offset); decimal value; byte* pb = (byte*)&value; for (int i = 0; i < sizeof(decimal); i++) pb[i] = buffer[offset + i]; Advance(ValueHandleLength.Decimal); return value; } public UniqueId ReadUniqueId() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.UniqueId, out offset); UniqueId uniqueId = new UniqueId(buffer, offset); Advance(ValueHandleLength.UniqueId); return uniqueId; } public DateTime ReadDateTime() { long value = 0; try { value = ReadInt64(); return DateTime.FromBinary(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } } public TimeSpan ReadTimeSpan() { long value = 0; try { value = ReadInt64(); return TimeSpan.FromTicks(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } } public Guid ReadGuid() { int offset; byte[] buffer = GetBuffer(ValueHandleLength.Guid, out offset); Guid guid = GetGuid(offset); Advance(ValueHandleLength.Guid); return guid; } public string ReadUTF8String(int length) { int offset; byte[] buffer = GetBuffer(length, out offset); char[] chars = GetCharBuffer(length); int charCount = GetChars(offset, length, chars); string value = new string(chars, 0, charCount); Advance(length); return value; } public unsafe void UnsafeReadArray(byte* dst, byte* dstMax) { UnsafeReadArray(dst, (int)(dstMax - dst)); } private unsafe void UnsafeReadArray(byte* dst, int length) { if (_stream != null) { const int chunk = 256; while (length >= chunk) { byte[] _buffer = GetBuffer(chunk, out _offset); for (int i = 0; i < chunk; i++) { *dst++ = _buffer[_offset + i]; } Advance(chunk); length -= chunk; } } if (length > 0) { byte[] buffer = GetBuffer(length, out _offset); fixed (byte* _src = &buffer[_offset]) { byte* src = _src; byte* dstMax = dst + length; while (dst < dstMax) { *dst = *src; dst++; src++; } } Advance(length); } } private char[] GetCharBuffer(int count) { if (count > 1024) return new char[count]; if (_chars == null || _chars.Length < count) _chars = new char[count]; return _chars; } private int GetChars(int offset, int length, char[] chars) { byte[] buffer = _buffer; for (int i = 0; i < length; i++) { byte b = buffer[offset + i]; if (b >= 0x80) return i + XmlConverter.ToChars(buffer, offset + i, length - i, chars, i); chars[i] = (char)b; } return length; } private int GetChars(int offset, int length, char[] chars, int charOffset) { byte[] buffer = _buffer; for (int i = 0; i < length; i++) { byte b = buffer[offset + i]; if (b >= 0x80) return i + XmlConverter.ToChars(buffer, offset + i, length - i, chars, charOffset + i); chars[charOffset + i] = (char)b; } return length; } public string GetString(int offset, int length) { char[] chars = GetCharBuffer(length); int charCount = GetChars(offset, length, chars); return new string(chars, 0, charCount); } public string GetUnicodeString(int offset, int length) { return XmlConverter.ToStringUnicode(_buffer, offset, length); } public string GetString(int offset, int length, XmlNameTable nameTable) { char[] chars = GetCharBuffer(length); int charCount = GetChars(offset, length, chars); return nameTable.Add(chars, 0, charCount); } public int GetEscapedChars(int offset, int length, char[] chars) { byte[] buffer = _buffer; int charCount = 0; int textOffset = offset; int offsetMax = offset + length; while (true) { while (offset < offsetMax && IsAttrChar(buffer[offset])) offset++; charCount += GetChars(textOffset, offset - textOffset, chars, charCount); if (offset == offsetMax) break; textOffset = offset; if (buffer[offset] == '&') { while (offset < offsetMax && buffer[offset] != ';') offset++; offset++; int ch = GetCharEntity(textOffset, offset - textOffset); textOffset = offset; if (ch > char.MaxValue) { SurrogateChar surrogate = new SurrogateChar(ch); chars[charCount++] = surrogate.HighChar; chars[charCount++] = surrogate.LowChar; } else { chars[charCount++] = (char)ch; } } else if (buffer[offset] == '\n' || buffer[offset] == '\t') { chars[charCount++] = ' '; offset++; textOffset = offset; } else // '\r' { chars[charCount++] = ' '; offset++; if (offset < offsetMax && buffer[offset] == '\n') offset++; textOffset = offset; } } return charCount; } private bool IsAttrChar(int ch) { switch (ch) { case '&': case '\r': case '\t': case '\n': return false; default: return true; } } public string GetEscapedString(int offset, int length) { char[] chars = GetCharBuffer(length); int charCount = GetEscapedChars(offset, length, chars); return new string(chars, 0, charCount); } private int GetLessThanCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 4 || buffer[offset + 1] != (byte)'l' || buffer[offset + 2] != (byte)'t') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'<'; } private int GetGreaterThanCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 4 || buffer[offset + 1] != (byte)'g' || buffer[offset + 2] != (byte)'t') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'>'; } private int GetQuoteCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 6 || buffer[offset + 1] != (byte)'q' || buffer[offset + 2] != (byte)'u' || buffer[offset + 3] != (byte)'o' || buffer[offset + 4] != (byte)'t') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'"'; } private int GetAmpersandCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 5 || buffer[offset + 1] != (byte)'a' || buffer[offset + 2] != (byte)'m' || buffer[offset + 3] != (byte)'p') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'&'; } private int GetApostropheCharEntity(int offset, int length) { byte[] buffer = _buffer; if (length != 6 || buffer[offset + 1] != (byte)'a' || buffer[offset + 2] != (byte)'p' || buffer[offset + 3] != (byte)'o' || buffer[offset + 4] != (byte)'s') { XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return (int)'\''; } private int GetDecimalCharEntity(int offset, int length) { byte[] buffer = _buffer; DiagnosticUtility.DebugAssert(buffer[offset + 0] == '&', ""); DiagnosticUtility.DebugAssert(buffer[offset + 1] == '#', ""); DiagnosticUtility.DebugAssert(buffer[offset + length - 1] == ';', ""); int value = 0; for (int i = 2; i < length - 1; i++) { byte ch = buffer[offset + i]; if (ch < (byte)'0' || ch > (byte)'9') XmlExceptionHelper.ThrowInvalidCharRef(_reader); value = value * 10 + (ch - '0'); if (value > SurrogateChar.MaxValue) XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return value; } private int GetHexCharEntity(int offset, int length) { byte[] buffer = _buffer; DiagnosticUtility.DebugAssert(buffer[offset + 0] == '&', ""); DiagnosticUtility.DebugAssert(buffer[offset + 1] == '#', ""); DiagnosticUtility.DebugAssert(buffer[offset + 2] == 'x', ""); DiagnosticUtility.DebugAssert(buffer[offset + length - 1] == ';', ""); int value = 0; for (int i = 3; i < length - 1; i++) { byte ch = buffer[offset + i]; int digit = 0; if (ch >= '0' && ch <= '9') digit = (ch - '0'); else if (ch >= 'a' && ch <= 'f') digit = 10 + (ch - 'a'); else if (ch >= 'A' && ch <= 'F') digit = 10 + (ch - 'A'); else XmlExceptionHelper.ThrowInvalidCharRef(_reader); DiagnosticUtility.DebugAssert(digit >= 0 && digit < 16, ""); value = value * 16 + digit; if (value > SurrogateChar.MaxValue) XmlExceptionHelper.ThrowInvalidCharRef(_reader); } return value; } public int GetCharEntity(int offset, int length) { if (length < 3) XmlExceptionHelper.ThrowInvalidCharRef(_reader); byte[] buffer = _buffer; DiagnosticUtility.DebugAssert(buffer[offset] == '&', ""); DiagnosticUtility.DebugAssert(buffer[offset + length - 1] == ';', ""); switch (buffer[offset + 1]) { case (byte)'l': return GetLessThanCharEntity(offset, length); case (byte)'g': return GetGreaterThanCharEntity(offset, length); case (byte)'a': if (buffer[offset + 2] == (byte)'m') return GetAmpersandCharEntity(offset, length); else return GetApostropheCharEntity(offset, length); case (byte)'q': return GetQuoteCharEntity(offset, length); case (byte)'#': if (buffer[offset + 2] == (byte)'x') return GetHexCharEntity(offset, length); else return GetDecimalCharEntity(offset, length); default: XmlExceptionHelper.ThrowInvalidCharRef(_reader); return 0; } } public bool IsWhitespaceKey(int key) { string s = GetDictionaryString(key).Value; for (int i = 0; i < s.Length; i++) { if (!XmlConverter.IsWhitespace(s[i])) return false; } return true; } public bool IsWhitespaceUTF8(int offset, int length) { byte[] buffer = _buffer; for (int i = 0; i < length; i++) { if (!XmlConverter.IsWhitespace((char)buffer[offset + i])) return false; } return true; } public bool IsWhitespaceUnicode(int offset, int length) { byte[] buffer = _buffer; for (int i = 0; i < length; i += sizeof(char)) { char ch = (char)GetInt16(offset + i); if (!XmlConverter.IsWhitespace(ch)) return false; } return true; } public bool Equals2(int key1, int key2, XmlBufferReader bufferReader2) { // If the keys aren't from the same dictionary, they still might be the same if (key1 == key2) return true; else return GetDictionaryString(key1).Value == bufferReader2.GetDictionaryString(key2).Value; } public bool Equals2(int key1, XmlDictionaryString xmlString2) { if ((key1 & 1) == 0 && xmlString2.Dictionary == _dictionary) return xmlString2.Key == (key1 >> 1); else return GetDictionaryString(key1).Value == xmlString2.Value; } public bool Equals2(int offset1, int length1, byte[] buffer2) { int length2 = buffer2.Length; if (length1 != length2) return false; byte[] buffer1 = _buffer; for (int i = 0; i < length1; i++) { if (buffer1[offset1 + i] != buffer2[i]) return false; } return true; } public bool Equals2(int offset1, int length1, XmlBufferReader bufferReader2, int offset2, int length2) { if (length1 != length2) return false; byte[] buffer1 = _buffer; byte[] buffer2 = bufferReader2._buffer; for (int i = 0; i < length1; i++) { if (buffer1[offset1 + i] != buffer2[offset2 + i]) return false; } return true; } public bool Equals2(int offset1, int length1, int offset2, int length2) { if (length1 != length2) return false; if (offset1 == offset2) return true; byte[] buffer = _buffer; for (int i = 0; i < length1; i++) { if (buffer[offset1 + i] != buffer[offset2 + i]) return false; } return true; } public unsafe bool Equals2(int offset1, int length1, string s2) { int byteLength = length1; int charLength = s2.Length; // N Unicode chars will be represented in at least N bytes, but // no more than N * 3 bytes. If the byte count falls outside of this // range, then the strings cannot be equal. if (byteLength < charLength || byteLength > charLength * maxBytesPerChar) return false; byte[] buffer = _buffer; if (length1 < 8) { int length = Math.Min(byteLength, charLength); int offset = offset1; for (int i = 0; i < length; i++) { byte b = buffer[offset + i]; if (b >= 0x80) return XmlConverter.ToString(buffer, offset1, length1) == s2; if (s2[i] != (char)b) return false; } return byteLength == charLength; } else { int length = Math.Min(byteLength, charLength); fixed (byte* _pb = &buffer[offset1]) { byte* pb = _pb; byte* pbMax = pb + length; fixed (char* _pch = s2) { char* pch = _pch; // Try to do the fast comparison in ASCII space int t = 0; while (pb < pbMax && *pb < 0x80) { t = *pb - (byte)*pch; // The code generated is better if we break out then return if (t != 0) break; pb++; pch++; } if (t != 0) return false; if (pb == pbMax) return (byteLength == charLength); } } return XmlConverter.ToString(buffer, offset1, length1) == s2; } } public int Compare(int offset1, int length1, int offset2, int length2) { byte[] buffer = _buffer; int length = Math.Min(length1, length2); for (int i = 0; i < length; i++) { int s = buffer[offset1 + i] - buffer[offset2 + i]; if (s != 0) return s; } return length1 - length2; } public byte GetByte(int offset) { return _buffer[offset]; } public int GetInt8(int offset) { return (sbyte)GetByte(offset); } public int GetInt16(int offset) { byte[] buffer = _buffer; return (Int16)(buffer[offset] + (buffer[offset + 1] << 8)); } public int GetInt32(int offset) { byte[] buffer = _buffer; byte b1 = buffer[offset + 0]; byte b2 = buffer[offset + 1]; byte b3 = buffer[offset + 2]; byte b4 = buffer[offset + 3]; return (((((b4 << 8) + b3) << 8) + b2) << 8) + b1; } public long GetInt64(int offset) { byte[] buffer = _buffer; byte b1, b2, b3, b4; b1 = buffer[offset + 0]; b2 = buffer[offset + 1]; b3 = buffer[offset + 2]; b4 = buffer[offset + 3]; Int64 lo = (UInt32)(((((b4 << 8) + b3) << 8) + b2) << 8) + b1; b1 = buffer[offset + 4]; b2 = buffer[offset + 5]; b3 = buffer[offset + 6]; b4 = buffer[offset + 7]; Int64 hi = (UInt32)(((((b4 << 8) + b3) << 8) + b2) << 8) + b1; return (hi << 32) + lo; } public ulong GetUInt64(int offset) { return (ulong)GetInt64(offset); } public unsafe float GetSingle(int offset) { byte[] buffer = _buffer; float value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(float) == 4, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; return value; } public unsafe double GetDouble(int offset) { byte[] buffer = _buffer; double value; byte* pb = (byte*)&value; DiagnosticUtility.DebugAssert(sizeof(double) == 8, ""); pb[0] = buffer[offset + 0]; pb[1] = buffer[offset + 1]; pb[2] = buffer[offset + 2]; pb[3] = buffer[offset + 3]; pb[4] = buffer[offset + 4]; pb[5] = buffer[offset + 5]; pb[6] = buffer[offset + 6]; pb[7] = buffer[offset + 7]; return value; } public unsafe decimal GetDecimal(int offset) { byte[] buffer = _buffer; decimal value; byte* pb = (byte*)&value; for (int i = 0; i < sizeof(decimal); i++) pb[i] = buffer[offset + i]; return value; } public UniqueId GetUniqueId(int offset) { return new UniqueId(_buffer, offset); } public Guid GetGuid(int offset) { if (_guid == null) _guid = new byte[16]; System.Buffer.BlockCopy(_buffer, offset, _guid, 0, _guid.Length); return new Guid(_guid); } public void GetBase64(int srcOffset, byte[] buffer, int dstOffset, int count) { System.Buffer.BlockCopy(_buffer, srcOffset, buffer, dstOffset, count); } public XmlBinaryNodeType GetNodeType() { return (XmlBinaryNodeType)GetByte(); } public void SkipNodeType() { SkipByte(); } public object[] GetList(int offset, int count) { int bufferOffset = this.Offset; this.Offset = offset; try { object[] objects = new object[count]; for (int i = 0; i < count; i++) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); DiagnosticUtility.DebugAssert(nodeType != XmlBinaryNodeType.StartListText, ""); ReadValue(nodeType, _listValue); objects[i] = _listValue.ToObject(); } return objects; } finally { this.Offset = bufferOffset; } } public XmlDictionaryString GetDictionaryString(int key) { IXmlDictionary keyDictionary; if ((key & 1) != 0) { keyDictionary = _session; } else { keyDictionary = _dictionary; } XmlDictionaryString s; if (!keyDictionary.TryLookup(key >> 1, out s)) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return s; } public int ReadDictionaryKey() { int key = ReadMultiByteUInt31(); if ((key & 1) != 0) { if (_session == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int sessionKey = (key >> 1); XmlDictionaryString xmlString; if (!_session.TryLookup(sessionKey, out xmlString)) { if (sessionKey < XmlDictionaryString.MinKey || sessionKey > XmlDictionaryString.MaxKey) XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(_reader); XmlExceptionHelper.ThrowXmlDictionaryStringIDUndefinedSession(_reader, sessionKey); } } else { if (_dictionary == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int staticKey = (key >> 1); XmlDictionaryString xmlString; if (!_dictionary.TryLookup(staticKey, out xmlString)) { if (staticKey < XmlDictionaryString.MinKey || staticKey > XmlDictionaryString.MaxKey) XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(_reader); XmlExceptionHelper.ThrowXmlDictionaryStringIDUndefinedStatic(_reader, staticKey); } } return key; } public void ReadValue(XmlBinaryNodeType nodeType, ValueHandle value) { switch (nodeType) { case XmlBinaryNodeType.EmptyText: value.SetValue(ValueHandleType.Empty); break; case XmlBinaryNodeType.ZeroText: value.SetValue(ValueHandleType.Zero); break; case XmlBinaryNodeType.OneText: value.SetValue(ValueHandleType.One); break; case XmlBinaryNodeType.TrueText: value.SetValue(ValueHandleType.True); break; case XmlBinaryNodeType.FalseText: value.SetValue(ValueHandleType.False); break; case XmlBinaryNodeType.BoolText: value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False); break; case XmlBinaryNodeType.Chars8Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt8()); break; case XmlBinaryNodeType.Chars16Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt16()); break; case XmlBinaryNodeType.Chars32Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt31()); break; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeValue(value, ReadUInt8()); break; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeValue(value, ReadUInt16()); break; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeValue(value, ReadUInt31()); break; case XmlBinaryNodeType.Bytes8Text: ReadValue(value, ValueHandleType.Base64, ReadUInt8()); break; case XmlBinaryNodeType.Bytes16Text: ReadValue(value, ValueHandleType.Base64, ReadUInt16()); break; case XmlBinaryNodeType.Bytes32Text: ReadValue(value, ValueHandleType.Base64, ReadUInt31()); break; case XmlBinaryNodeType.DictionaryText: value.SetDictionaryValue(ReadDictionaryKey()); break; case XmlBinaryNodeType.UniqueIdText: ReadValue(value, ValueHandleType.UniqueId, ValueHandleLength.UniqueId); break; case XmlBinaryNodeType.GuidText: ReadValue(value, ValueHandleType.Guid, ValueHandleLength.Guid); break; case XmlBinaryNodeType.DecimalText: ReadValue(value, ValueHandleType.Decimal, ValueHandleLength.Decimal); break; case XmlBinaryNodeType.Int8Text: ReadValue(value, ValueHandleType.Int8, ValueHandleLength.Int8); break; case XmlBinaryNodeType.Int16Text: ReadValue(value, ValueHandleType.Int16, ValueHandleLength.Int16); break; case XmlBinaryNodeType.Int32Text: ReadValue(value, ValueHandleType.Int32, ValueHandleLength.Int32); break; case XmlBinaryNodeType.Int64Text: ReadValue(value, ValueHandleType.Int64, ValueHandleLength.Int64); break; case XmlBinaryNodeType.UInt64Text: ReadValue(value, ValueHandleType.UInt64, ValueHandleLength.UInt64); break; case XmlBinaryNodeType.FloatText: ReadValue(value, ValueHandleType.Single, ValueHandleLength.Single); break; case XmlBinaryNodeType.DoubleText: ReadValue(value, ValueHandleType.Double, ValueHandleLength.Double); break; case XmlBinaryNodeType.TimeSpanText: ReadValue(value, ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan); break; case XmlBinaryNodeType.DateTimeText: ReadValue(value, ValueHandleType.DateTime, ValueHandleLength.DateTime); break; case XmlBinaryNodeType.StartListText: ReadList(value); break; case XmlBinaryNodeType.QNameDictionaryText: ReadQName(value); break; default: XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); break; } } private void ReadValue(ValueHandle value, ValueHandleType type, int length) { int offset = ReadBytes(length); value.SetValue(type, offset, length); } private void ReadUnicodeValue(ValueHandle value, int length) { if ((length & 1) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); ReadValue(value, ValueHandleType.Unicode, length); } private void ReadList(ValueHandle value) { if (_listValue == null) { _listValue = new ValueHandle(this); } int count = 0; int offset = this.Offset; while (true) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); if (nodeType == XmlBinaryNodeType.StartListText) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); if (nodeType == XmlBinaryNodeType.EndListText) break; ReadValue(nodeType, _listValue); count++; } value.SetValue(ValueHandleType.List, offset, count); } public void ReadQName(ValueHandle value) { int prefix = ReadUInt8(); if (prefix >= 26) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int key = ReadDictionaryKey(); value.SetQNameValue(prefix, key); } public int[] GetRows() { if (_buffer == null) { return new int[1] { 0 }; } List<int> list = new List<int>(); list.Add(_offsetMin); for (int i = _offsetMin; i < _offsetMax; i++) { if (_buffer[i] == (byte)13 || _buffer[i] == (byte)10) { if (i + 1 < _offsetMax && _buffer[i + 1] == (byte)10) i++; list.Add(i + 1); } } return list.ToArray(); } } }
namespace SLeek { partial class frmProfile { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmProfile)); this.tabProfile = new System.Windows.Forms.TabControl(); this.tpgProfile = new System.Windows.Forms.TabPage(); this.btnOfferTeleport = new System.Windows.Forms.Button(); this.btnPay = new System.Windows.Forms.Button(); this.rtbAccountInfo = new System.Windows.Forms.RichTextBox(); this.rtbAbout = new System.Windows.Forms.RichTextBox(); this.proSLImage = new System.Windows.Forms.ProgressBar(); this.txtPartner = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtBornOn = new System.Windows.Forms.TextBox(); this.txtFullName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.picSLImage = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.tpgWeb = new System.Windows.Forms.TabPage(); this.pnlWeb = new System.Windows.Forms.Panel(); this.btnWebOpen = new System.Windows.Forms.Button(); this.btnWebView = new System.Windows.Forms.Button(); this.txtWebURL = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.tpgFirstLife = new System.Windows.Forms.TabPage(); this.rtbAboutFL = new System.Windows.Forms.RichTextBox(); this.proFLImage = new System.Windows.Forms.ProgressBar(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.picFLImage = new System.Windows.Forms.PictureBox(); this.btnClose = new System.Windows.Forms.Button(); this.tabProfile.SuspendLayout(); this.tpgProfile.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picSLImage)).BeginInit(); this.tpgWeb.SuspendLayout(); this.tpgFirstLife.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picFLImage)).BeginInit(); this.SuspendLayout(); // // tabProfile // this.tabProfile.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.tabProfile.Controls.Add(this.tpgProfile); this.tabProfile.Controls.Add(this.tpgWeb); this.tabProfile.Controls.Add(this.tpgFirstLife); this.tabProfile.Location = new System.Drawing.Point(12, 12); this.tabProfile.Name = "tabProfile"; this.tabProfile.SelectedIndex = 0; this.tabProfile.Size = new System.Drawing.Size(468, 483); this.tabProfile.TabIndex = 0; // // tpgProfile // this.tpgProfile.Controls.Add(this.btnOfferTeleport); this.tpgProfile.Controls.Add(this.btnPay); this.tpgProfile.Controls.Add(this.rtbAccountInfo); this.tpgProfile.Controls.Add(this.rtbAbout); this.tpgProfile.Controls.Add(this.proSLImage); this.tpgProfile.Controls.Add(this.txtPartner); this.tpgProfile.Controls.Add(this.label5); this.tpgProfile.Controls.Add(this.label4); this.tpgProfile.Controls.Add(this.label3); this.tpgProfile.Controls.Add(this.txtBornOn); this.tpgProfile.Controls.Add(this.txtFullName); this.tpgProfile.Controls.Add(this.label2); this.tpgProfile.Controls.Add(this.picSLImage); this.tpgProfile.Controls.Add(this.label1); this.tpgProfile.Location = new System.Drawing.Point(4, 22); this.tpgProfile.Name = "tpgProfile"; this.tpgProfile.Padding = new System.Windows.Forms.Padding(3); this.tpgProfile.Size = new System.Drawing.Size(460, 457); this.tpgProfile.TabIndex = 0; this.tpgProfile.Text = "Profile"; this.tpgProfile.UseVisualStyleBackColor = true; // // btnOfferTeleport // this.btnOfferTeleport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnOfferTeleport.Location = new System.Drawing.Point(6, 368); this.btnOfferTeleport.Name = "btnOfferTeleport"; this.btnOfferTeleport.Size = new System.Drawing.Size(108, 23); this.btnOfferTeleport.TabIndex = 16; this.btnOfferTeleport.Text = "Offer Teleport"; this.btnOfferTeleport.UseVisualStyleBackColor = true; this.btnOfferTeleport.Click += new System.EventHandler(this.btnOfferTeleport_Click); // // btnPay // this.btnPay.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnPay.Location = new System.Drawing.Point(120, 368); this.btnPay.Name = "btnPay"; this.btnPay.Size = new System.Drawing.Size(75, 23); this.btnPay.TabIndex = 15; this.btnPay.Text = "Pay..."; this.btnPay.UseVisualStyleBackColor = true; this.btnPay.Click += new System.EventHandler(this.btnPay_Click); // // rtbAccountInfo // this.rtbAccountInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.rtbAccountInfo.Location = new System.Drawing.Point(306, 60); this.rtbAccountInfo.Name = "rtbAccountInfo"; this.rtbAccountInfo.ReadOnly = true; this.rtbAccountInfo.Size = new System.Drawing.Size(148, 133); this.rtbAccountInfo.TabIndex = 14; this.rtbAccountInfo.Text = ""; // // rtbAbout // this.rtbAbout.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.rtbAbout.Location = new System.Drawing.Point(6, 212); this.rtbAbout.Name = "rtbAbout"; this.rtbAbout.ReadOnly = true; this.rtbAbout.Size = new System.Drawing.Size(448, 150); this.rtbAbout.TabIndex = 13; this.rtbAbout.Text = ""; this.rtbAbout.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.rtbAbout_LinkClicked); // // proSLImage // this.proSLImage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.proSLImage.Location = new System.Drawing.Point(6, 33); this.proSLImage.MarqueeAnimationSpeed = 50; this.proSLImage.Name = "proSLImage"; this.proSLImage.Size = new System.Drawing.Size(240, 16); this.proSLImage.Style = System.Windows.Forms.ProgressBarStyle.Marquee; this.proSLImage.TabIndex = 12; // // txtPartner // this.txtPartner.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.txtPartner.Location = new System.Drawing.Point(306, 33); this.txtPartner.Name = "txtPartner"; this.txtPartner.ReadOnly = true; this.txtPartner.Size = new System.Drawing.Size(148, 21); this.txtPartner.TabIndex = 10; // // label5 // this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(252, 36); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(47, 13); this.label5.TabIndex = 9; this.label5.Text = "Partner:"; // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 196); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 13); this.label4.TabIndex = 8; this.label4.Text = "About:"; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(252, 63); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(31, 13); this.label3.TabIndex = 7; this.label3.Text = "Info:"; // // txtBornOn // this.txtBornOn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.txtBornOn.Location = new System.Drawing.Point(306, 6); this.txtBornOn.Name = "txtBornOn"; this.txtBornOn.ReadOnly = true; this.txtBornOn.Size = new System.Drawing.Size(148, 21); this.txtBornOn.TabIndex = 5; // // txtFullName // this.txtFullName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtFullName.Location = new System.Drawing.Point(50, 6); this.txtFullName.Name = "txtFullName"; this.txtFullName.ReadOnly = true; this.txtFullName.Size = new System.Drawing.Size(196, 21); this.txtFullName.TabIndex = 4; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(252, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 13); this.label2.TabIndex = 3; this.label2.Text = "Born on:"; // // picSLImage // this.picSLImage.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.picSLImage.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picSLImage.Location = new System.Drawing.Point(6, 33); this.picSLImage.Name = "picSLImage"; this.picSLImage.Size = new System.Drawing.Size(240, 160); this.picSLImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picSLImage.TabIndex = 2; this.picSLImage.TabStop = false; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 1; this.label1.Text = "Name:"; // // tpgWeb // this.tpgWeb.Controls.Add(this.pnlWeb); this.tpgWeb.Controls.Add(this.btnWebOpen); this.tpgWeb.Controls.Add(this.btnWebView); this.tpgWeb.Controls.Add(this.txtWebURL); this.tpgWeb.Controls.Add(this.label6); this.tpgWeb.Location = new System.Drawing.Point(4, 22); this.tpgWeb.Name = "tpgWeb"; this.tpgWeb.Padding = new System.Windows.Forms.Padding(3); this.tpgWeb.Size = new System.Drawing.Size(460, 457); this.tpgWeb.TabIndex = 1; this.tpgWeb.Text = "Web"; this.tpgWeb.UseVisualStyleBackColor = true; // // pnlWeb // this.pnlWeb.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.pnlWeb.Location = new System.Drawing.Point(6, 33); this.pnlWeb.Name = "pnlWeb"; this.pnlWeb.Size = new System.Drawing.Size(448, 418); this.pnlWeb.TabIndex = 4; // // btnWebOpen // this.btnWebOpen.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnWebOpen.Enabled = false; this.btnWebOpen.Location = new System.Drawing.Point(379, 4); this.btnWebOpen.Name = "btnWebOpen"; this.btnWebOpen.Size = new System.Drawing.Size(75, 23); this.btnWebOpen.TabIndex = 3; this.btnWebOpen.Text = "Open"; this.btnWebOpen.UseVisualStyleBackColor = true; this.btnWebOpen.Click += new System.EventHandler(this.btnWebOpen_Click); // // btnWebView // this.btnWebView.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnWebView.Enabled = false; this.btnWebView.Location = new System.Drawing.Point(298, 4); this.btnWebView.Name = "btnWebView"; this.btnWebView.Size = new System.Drawing.Size(75, 23); this.btnWebView.TabIndex = 2; this.btnWebView.Text = "View"; this.btnWebView.UseVisualStyleBackColor = true; this.btnWebView.Click += new System.EventHandler(this.btnWebView_Click); // // txtWebURL // this.txtWebURL.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtWebURL.Location = new System.Drawing.Point(42, 6); this.txtWebURL.Name = "txtWebURL"; this.txtWebURL.ReadOnly = true; this.txtWebURL.Size = new System.Drawing.Size(250, 21); this.txtWebURL.TabIndex = 1; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(6, 9); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(30, 13); this.label6.TabIndex = 0; this.label6.Text = "URL:"; // // tpgFirstLife // this.tpgFirstLife.Controls.Add(this.rtbAboutFL); this.tpgFirstLife.Controls.Add(this.proFLImage); this.tpgFirstLife.Controls.Add(this.label8); this.tpgFirstLife.Controls.Add(this.label7); this.tpgFirstLife.Controls.Add(this.picFLImage); this.tpgFirstLife.Location = new System.Drawing.Point(4, 22); this.tpgFirstLife.Name = "tpgFirstLife"; this.tpgFirstLife.Padding = new System.Windows.Forms.Padding(3); this.tpgFirstLife.Size = new System.Drawing.Size(460, 457); this.tpgFirstLife.TabIndex = 2; this.tpgFirstLife.Text = "First Life"; this.tpgFirstLife.UseVisualStyleBackColor = true; // // rtbAboutFL // this.rtbAboutFL.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.rtbAboutFL.Location = new System.Drawing.Point(6, 201); this.rtbAboutFL.Name = "rtbAboutFL"; this.rtbAboutFL.ReadOnly = true; this.rtbAboutFL.Size = new System.Drawing.Size(448, 150); this.rtbAboutFL.TabIndex = 14; this.rtbAboutFL.Text = ""; this.rtbAboutFL.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.rtbAboutFL_LinkClicked); // // proFLImage // this.proFLImage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.proFLImage.Location = new System.Drawing.Point(6, 22); this.proFLImage.MarqueeAnimationSpeed = 50; this.proFLImage.Name = "proFLImage"; this.proFLImage.Size = new System.Drawing.Size(240, 16); this.proFLImage.Style = System.Windows.Forms.ProgressBarStyle.Marquee; this.proFLImage.TabIndex = 13; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(6, 6); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(80, 13); this.label8.TabIndex = 6; this.label8.Text = "My first life pic:"; // // label7 // this.label7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(6, 185); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(96, 13); this.label7.TabIndex = 5; this.label7.Text = "About my first life:"; // // picFLImage // this.picFLImage.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.picFLImage.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picFLImage.Location = new System.Drawing.Point(6, 22); this.picFLImage.Name = "picFLImage"; this.picFLImage.Size = new System.Drawing.Size(240, 160); this.picFLImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picFLImage.TabIndex = 3; this.picFLImage.TabStop = false; // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.Location = new System.Drawing.Point(405, 501); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(75, 23); this.btnClose.TabIndex = 1; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // frmProfile // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(492, 536); this.Controls.Add(this.btnClose); this.Controls.Add(this.tabProfile); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "frmProfile"; this.Text = "Profile"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmProfile_FormClosing); this.tabProfile.ResumeLayout(false); this.tpgProfile.ResumeLayout(false); this.tpgProfile.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picSLImage)).EndInit(); this.tpgWeb.ResumeLayout(false); this.tpgWeb.PerformLayout(); this.tpgFirstLife.ResumeLayout(false); this.tpgFirstLife.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picFLImage)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tabProfile; private System.Windows.Forms.TabPage tpgProfile; private System.Windows.Forms.TabPage tpgWeb; private System.Windows.Forms.TabPage tpgFirstLife; private System.Windows.Forms.PictureBox picSLImage; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtFullName; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtBornOn; private System.Windows.Forms.TextBox txtPartner; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Panel pnlWeb; private System.Windows.Forms.Button btnWebOpen; private System.Windows.Forms.Button btnWebView; private System.Windows.Forms.TextBox txtWebURL; private System.Windows.Forms.Label label6; private System.Windows.Forms.PictureBox picFLImage; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.ProgressBar proSLImage; private System.Windows.Forms.ProgressBar proFLImage; private System.Windows.Forms.RichTextBox rtbAbout; private System.Windows.Forms.RichTextBox rtbAboutFL; private System.Windows.Forms.RichTextBox rtbAccountInfo; private System.Windows.Forms.Button btnPay; private System.Windows.Forms.Button btnOfferTeleport; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.MachineLearningCompute { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for OperationalizationClustersOperations. /// </summary> public static partial class OperationalizationClustersOperationsExtensions { /// <summary> /// Create or update an operationalization cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update an Operationalization cluster. /// </param> public static OperationalizationCluster CreateOrUpdate(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, OperationalizationCluster parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, clusterName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create or update an operationalization cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update an Operationalization cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationCluster> CreateOrUpdateAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, OperationalizationCluster parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, clusterName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the operationalization cluster resource view. Note that the /// credentials are not returned by this call. Call ListKeys to get them. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static OperationalizationCluster Get(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.GetAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Gets the operationalization cluster resource view. Note that the /// credentials are not returned by this call. Call ListKeys to get them. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationCluster> GetAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The PATCH operation can be used to update only the tags for a cluster. Use /// PUT operation to update other properties. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='parameters'> /// The parameters supplied to patch the cluster. /// </param> public static OperationalizationCluster Update(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, OperationalizationClusterUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, clusterName, parameters).GetAwaiter().GetResult(); } /// <summary> /// The PATCH operation can be used to update only the tags for a cluster. Use /// PUT operation to update other properties. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='parameters'> /// The parameters supplied to patch the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationCluster> UpdateAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, OperationalizationClusterUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, clusterName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static OperationalizationClustersDeleteHeaders Delete(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.DeleteAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationClustersDeleteHeaders> DeleteAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets the credentials for the specified cluster such as Storage, ACR and ACS /// credentials. This is a long running operation because it fetches keys from /// dependencies. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static OperationalizationClusterCredentials ListKeys(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.ListKeysAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Gets the credentials for the specified cluster such as Storage, ACR and ACS /// credentials. This is a long running operation because it fetches keys from /// dependencies. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationClusterCredentials> ListKeysAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Checks if updates are available for system services in the cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static CheckSystemServicesUpdatesAvailableResponse CheckSystemServicesUpdatesAvailable(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.CheckSystemServicesUpdatesAvailableAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Checks if updates are available for system services in the cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckSystemServicesUpdatesAvailableResponse> CheckSystemServicesUpdatesAvailableAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckSystemServicesUpdatesAvailableWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates system services in a cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static UpdateSystemServicesResponse UpdateSystemServices(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.UpdateSystemServicesAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Updates system services in a cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<UpdateSystemServicesResponse> UpdateSystemServicesAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateSystemServicesWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the clusters in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> public static IPage<OperationalizationCluster> ListByResourceGroup(this IOperationalizationClustersOperations operations, string resourceGroupName, string skiptoken = default(string)) { return operations.ListByResourceGroupAsync(resourceGroupName, skiptoken).GetAwaiter().GetResult(); } /// <summary> /// Gets the clusters in the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<OperationalizationCluster>> ListByResourceGroupAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string skiptoken = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, skiptoken, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the operationalization clusters in the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> public static IPage<OperationalizationCluster> ListBySubscriptionId(this IOperationalizationClustersOperations operations, string skiptoken = default(string)) { return operations.ListBySubscriptionIdAsync(skiptoken).GetAwaiter().GetResult(); } /// <summary> /// Gets the operationalization clusters in the specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='skiptoken'> /// Continuation token for pagination. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<OperationalizationCluster>> ListBySubscriptionIdAsync(this IOperationalizationClustersOperations operations, string skiptoken = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionIdWithHttpMessagesAsync(skiptoken, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create or update an operationalization cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update an Operationalization cluster. /// </param> public static OperationalizationCluster BeginCreateOrUpdate(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, OperationalizationCluster parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, clusterName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create or update an operationalization cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update an Operationalization cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationCluster> BeginCreateOrUpdateAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, OperationalizationCluster parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, clusterName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static OperationalizationClustersDeleteHeaders BeginDelete(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.BeginDeleteAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationalizationClustersDeleteHeaders> BeginDeleteAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Updates system services in a cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> public static UpdateSystemServicesResponse BeginUpdateSystemServices(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName) { return operations.BeginUpdateSystemServicesAsync(resourceGroupName, clusterName).GetAwaiter().GetResult(); } /// <summary> /// Updates system services in a cluster. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group in which the cluster is located. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<UpdateSystemServicesResponse> BeginUpdateSystemServicesAsync(this IOperationalizationClustersOperations operations, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateSystemServicesWithHttpMessagesAsync(resourceGroupName, clusterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the clusters in the specified resource group. /// </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 IPage<OperationalizationCluster> ListByResourceGroupNext(this IOperationalizationClustersOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the clusters in the specified resource group. /// </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<IPage<OperationalizationCluster>> ListByResourceGroupNextAsync(this IOperationalizationClustersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the operationalization clusters in the specified subscription. /// </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 IPage<OperationalizationCluster> ListBySubscriptionIdNext(this IOperationalizationClustersOperations operations, string nextPageLink) { return operations.ListBySubscriptionIdNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the operationalization clusters in the specified subscription. /// </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<IPage<OperationalizationCluster>> ListBySubscriptionIdNextAsync(this IOperationalizationClustersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionIdNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
//--------------------------------------------------------------------------- // // <copyright file="TextAdaptor.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Text Object Models Text pattern provider // Spec for TextPattern at http://team/sites/uiauto/Shared%20Documents/TextPatternSpecM8.doc // Spec for Text Object Model (TOM) at http://avalon/uis/TextBox%20and%20RichTextBox/Text%20Object%20Model.doc // // History: // 03/15/2004 : mmccr - created // 09/07/2004 : vsmirnov - refactored // 01/20/2004 : [....] - refactored // //--------------------------------------------------------------------------- using System; // Exception using System.Collections.Generic; // List<T> using System.Collections.ObjectModel; // ReadOnlyCollection using System.Security; // SecurityCritical, ... using System.Windows; // PresentationSource using System.Windows.Automation; // SupportedTextSelection using System.Windows.Automation.Peers; // AutomationPeer using System.Windows.Automation.Provider; // ITextProvider using System.Windows.Controls.Primitives; // IScrollInfo using System.Windows.Documents; // ITextContainer using System.Windows.Media; // Visual using MS.Internal.Documents; // MultiPageTextView namespace MS.Internal.Automation { /// <summary> /// Represents a text provider that supports the text pattern across Text Object /// Model based Text Controls. /// </summary> internal class TextAdaptor : ITextProvider, IDisposable { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="textPeer">Automation Peer representing element for the ui scope of the text</param> /// <param name="textContainer">ITextContainer</param> internal TextAdaptor(AutomationPeer textPeer, ITextContainer textContainer) { Invariant.Assert(textContainer != null, "Invalid ITextContainer"); Invariant.Assert(textPeer is TextAutomationPeer || textPeer is ContentTextAutomationPeer, "Invalid AutomationPeer"); _textPeer = textPeer; _textContainer = textContainer; _textContainer.Changed += new TextContainerChangedEventHandler(OnTextContainerChanged); if (_textContainer.TextSelection != null) { _textContainer.TextSelection.Changed += new EventHandler(OnTextSelectionChanged); } } /// <summary> /// Dispose. /// </summary> public void Dispose() { if (_textContainer != null && _textContainer.TextSelection != null) { _textContainer.TextSelection.Changed -= new EventHandler(OnTextSelectionChanged); } GC.SuppressFinalize(this); } #endregion Constructors //------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// Retrieves the bounding rectangles for the text lines of a given range. /// </summary> /// <param name="start">Start of range to measure</param> /// <param name="end">End of range to measure</param> /// <param name="clipToView">Specifies whether the caller wants the full bounds (false) or the bounds of visible portions /// of the viewable line only ('true')</param> /// <param name="transformToScreen">Requests the results in screen coordinates</param> /// <returns>An array of bounding rectangles for each line or portion of a line within the client area of the text provider. /// No bounding rectangles will be returned for lines that are empty or scrolled out of view. Note that even though a /// bounding rectangle is returned the corresponding text may not be visible due to overlapping windows. /// This will not return null, but may return an empty array.</returns> internal Rect[] GetBoundingRectangles(ITextPointer start, ITextPointer end, bool clipToView, bool transformToScreen) { ITextView textView = GetUpdatedTextView(); if (textView == null) { return new Rect[0]; } // If start/end positions are not in the visible range, move them to the first/last visible positions. ReadOnlyCollection<TextSegment> textSegments = textView.TextSegments; if (textSegments.Count > 0) { if (!textView.Contains(start) && start.CompareTo(textSegments[0].Start) < 0) { start = textSegments[0].Start.CreatePointer(); ; } if (!textView.Contains(end) && end.CompareTo(textSegments[textSegments.Count-1].End) > 0) { end = textSegments[textSegments.Count - 1].End.CreatePointer(); } } if (!textView.Contains(start) || !textView.Contains(end)) { return new Rect[0]; } TextRangeAdaptor.MoveToInsertionPosition(start, LogicalDirection.Forward); TextRangeAdaptor.MoveToInsertionPosition(end, LogicalDirection.Backward); Rect visibleRect = Rect.Empty; if (clipToView) { visibleRect = GetVisibleRectangle(textView); // If clipping into view and visible rect is empty, return. if (visibleRect.IsEmpty) { return new Rect[0]; } } List<Rect> rectangles = new List<Rect>(); ITextPointer position = start.CreatePointer(); while (position.CompareTo(end) < 0) { TextSegment lineRange = textView.GetLineRange(position); if (!lineRange.IsNull) { // Since range is limited to just one line, GetTightBoundingGeometry will return tight bounding // rectangle for given range. It will also work correctly with bidi text. ITextPointer first = (lineRange.Start.CompareTo(start) <= 0) ? start : lineRange.Start; ITextPointer last = (lineRange.End.CompareTo(end) >= 0) ? end : lineRange.End; Rect lineRect = Rect.Empty; Geometry geometry = textView.GetTightBoundingGeometryFromTextPositions(first, last); if (geometry != null) { lineRect = geometry.Bounds; if (clipToView) { lineRect.Intersect(visibleRect); } if (!lineRect.IsEmpty) { if (transformToScreen) { lineRect = new Rect(ClientToScreen(lineRect.TopLeft, textView.RenderScope), ClientToScreen(lineRect.BottomRight, textView.RenderScope)); } rectangles.Add(lineRect); } } } if (position.MoveToLineBoundary(1) == 0) { position = end; } } return rectangles.ToArray(); } /// <summary> /// Retrieves associated TextView. If TextView is not valid, tries to update its layout. /// </summary> internal ITextView GetUpdatedTextView() { ITextView textView = _textContainer.TextView; if (textView != null) { if (!textView.IsValid) { if (!textView.Validate()) { textView = null; } if (textView != null && !textView.IsValid) { textView = null; } } } return textView; } /// <summary> /// Changes text selection on the element /// </summary> /// <param name="start">Start of range to select</param> /// <param name="end">End of range to select</param> /// <remarks>Automation clients as well as the internal caller of this method (a TextRangeAdapter object) are supposed /// to verify whether the provider supports text selection by calling SupportsTextSelection first. /// The internal caller is responsible for raising an InvalidOperationException upon the Automation client' attempt /// to change selection when it's not supported by the provider</remarks> internal void Select(ITextPointer start, ITextPointer end) { // Update the selection range if (_textContainer.TextSelection != null) { _textContainer.TextSelection.Select(start, end); } } /// <summary> /// This helper method is used by TextRangeAdaptor to bring the range into view /// through multiple nested scroll providers. /// </summary> internal void ScrollIntoView(ITextPointer start, ITextPointer end, bool alignToTop) { // Calculate the bounding rectangle for the range Rect rangeBounds = Rect.Empty; Rect[] lineBounds = GetBoundingRectangles(start, end, false, false); foreach (Rect rect in lineBounds) { rangeBounds.Union(rect); } ITextView textView = GetUpdatedTextView(); if (textView != null && !rangeBounds.IsEmpty) { // Find out the visible portion of the range. Rect visibleRect = GetVisibleRectangle(textView); Rect rangeVisibleBounds = Rect.Intersect(rangeBounds, visibleRect); if (rangeVisibleBounds == rangeBounds) { // The range is already in the view. It's probably not aligned as requested, // but who cares since it's entirely visible anyway. return; } // Ensure the visibility of the range. // BringIntoView will do most of the magic except the very first scroll // in order to satisfy the requested alignment. UIElement renderScope = textView.RenderScope; Visual visual = renderScope; while (visual != null) { IScrollInfo isi = visual as IScrollInfo; if (isi != null) { // Transform the bounding rectangle into the IScrollInfo coordinates. if (visual != renderScope) { GeneralTransform childToParent = renderScope.TransformToAncestor(visual); rangeBounds = childToParent.TransformBounds(rangeBounds); } if (isi.CanHorizontallyScroll) { isi.SetHorizontalOffset(alignToTop ? rangeBounds.Left : (rangeBounds.Right - isi.ViewportWidth)); } if (isi.CanVerticallyScroll) { isi.SetVerticalOffset(alignToTop ? rangeBounds.Top : (rangeBounds.Bottom - isi.ViewportHeight)); } break; } visual = VisualTreeHelper.GetParent(visual) as Visual; } FrameworkElement fe = renderScope as FrameworkElement; if (fe != null) { fe.BringIntoView(rangeVisibleBounds); } } else { // If failed to retrive range bounds, try to Bring into view closes element. ITextPointer pointer = alignToTop ? start.CreatePointer() : end.CreatePointer(); pointer.MoveToElementEdge(alignToTop ? ElementEdge.AfterStart : ElementEdge.AfterEnd); FrameworkContentElement element = pointer.GetAdjacentElement(LogicalDirection.Backward) as FrameworkContentElement; if (element != null) { element.BringIntoView(); } } } #endregion Internal Methods //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods /// <summary> /// Notify about content changes. /// </summary> private void OnTextContainerChanged(object sender, TextContainerChangedEventArgs e) { _textPeer.RaiseAutomationEvent(AutomationEvents.TextPatternOnTextChanged); } /// <summary> /// Notify about selection changes. /// </summary> private void OnTextSelectionChanged(object sender, EventArgs e) { _textPeer.RaiseAutomationEvent(AutomationEvents.TextPatternOnTextSelectionChanged); } /// <summary> /// Computes the bounds of the render scope area visible through all nested scroll areas. /// </summary> private Rect GetVisibleRectangle(ITextView textView) { Rect visibleRect = new Rect(textView.RenderScope.RenderSize); Visual visual = VisualTreeHelper.GetParent(textView.RenderScope) as Visual; while (visual != null && visibleRect != Rect.Empty) { if (VisualTreeHelper.GetClip(visual) != null) { GeneralTransform transform = textView.RenderScope.TransformToAncestor(visual).Inverse; // Safer version of transform to descendent (doing the inverse ourself), // we want the rect inside of our space. (Which is always rectangular and much nicer to work with). if (transform != null) { Rect rectBounds = VisualTreeHelper.GetClip(visual).Bounds; rectBounds = transform.TransformBounds(rectBounds); visibleRect.Intersect(rectBounds); } else { // No visibility if non-invertable transform exists. visibleRect = Rect.Empty; } } visual = VisualTreeHelper.GetParent(visual) as Visual; } return visibleRect; } /// <summary> /// Convert a point from "client" coordinate space of a window into /// the coordinate space of the screen. /// </summary> /// <SecurityNote> /// Critical: This code calls into PresentationSource to get HwndSource /// TreatAsSafe: This code is not exposing any critical information, at the same time /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private Point ClientToScreen(Point point, Visual visual) { PresentationSource presentationSource = PresentationSource.CriticalFromVisual(visual); if (presentationSource != null) { GeneralTransform transform = visual.TransformToAncestor(presentationSource.RootVisual); if (transform != null) { point = transform.Transform(point); } } return PointUtil.ClientToScreen(point, presentationSource); } /// <summary> /// Convert a point from the coordinate space of the screen into /// the "client" coordinate space of a window. /// </summary> /// <SecurityNote> /// Critical: This code calls into PresentationSource to get HwndSource /// TreatAsSafe: This code is not exposing any critical information, at the same time /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private Point ScreenToClient(Point point, Visual visual) { PresentationSource presentationSource = PresentationSource.CriticalFromVisual(visual); point = PointUtil.ScreenToClient(point, presentationSource); if (presentationSource != null) { GeneralTransform transform = visual.TransformToAncestor(presentationSource.RootVisual); if (transform != null) { transform = transform.Inverse; if (transform != null) { point = transform.Transform(point); } } } return point; } #endregion Private Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private fields private AutomationPeer _textPeer; private ITextContainer _textContainer; #endregion Private Fields //------------------------------------------------------------------- // // ITextProvider // //------------------------------------------------------------------- #region ITextProvider implementation /// <summary> /// Retrieves the current selection. For providers that have the concept of /// text selection the provider should implement this method and also return /// true for the SupportsTextSelection property below. Otherwise this method /// should throw an InvalidOperation exception. /// For providers that support multiple disjoint selection, this should return /// an array of all the currently selected ranges. Providers that don't support /// multiple disjoint selection should just return an array containing a single /// range. /// </summary> /// <returns>The range of text that is selected, or possibly null if there is /// no selection.</returns> ITextRangeProvider[] ITextProvider.GetSelection() { ITextRange selection = _textContainer.TextSelection; if (selection == null) { throw new InvalidOperationException(SR.Get(SRID.TextProvider_TextSelectionNotSupported)); } return new ITextRangeProvider[] { new TextRangeAdaptor(this, selection.Start, selection.End, _textPeer) }; } /// <summary> /// Retrieves the visible ranges of text. /// </summary> /// <returns>The ranges of text that are visible, or possibly an empty array if there is /// no visible text whatsoever. Text in the range may still be obscured by an overlapping /// window. Also, portions /// of the range at the beginning, in the middle, or at the end may not be visible /// because they are scrolled off to the side. /// Providers should ensure they return at most a range from the beginning of the first /// line with portions visible through the end of the last line with portions visible.</returns> ITextRangeProvider[] ITextProvider.GetVisibleRanges() { ITextRangeProvider[] ranges = null; ITextView textView = GetUpdatedTextView(); if (textView != null) { List<TextSegment> visibleTextSegments = new List<TextSegment>(); // Get visible portion of the document. // if (textView is MultiPageTextView) { // For MultiPageTextView assume that all current pages are entirely visible. visibleTextSegments.AddRange(textView.TextSegments); } else { // For all others TextViews get visible rectangle and hittest TopLeft and // BottomRight points to retrieve visible range. // Find out the bounds of the area visible through all nested scroll areas Rect visibleRect = GetVisibleRectangle(textView); if (!visibleRect.IsEmpty) { ITextPointer visibleStart = textView.GetTextPositionFromPoint(visibleRect.TopLeft, true); ITextPointer visibleEnd = textView.GetTextPositionFromPoint(visibleRect.BottomRight, true); visibleTextSegments.Add(new TextSegment(visibleStart, visibleEnd, true)); } } // Create collection of TextRangeProviders for visible ranges. if (visibleTextSegments.Count > 0) { ranges = new ITextRangeProvider[visibleTextSegments.Count]; for (int i = 0; i < visibleTextSegments.Count; i++) { ranges[i] = new TextRangeAdaptor(this, visibleTextSegments[i].Start, visibleTextSegments[i].End, _textPeer); } } } // If no text is visible in the control, return the degenerate text range // (empty range) at the beginning of the document. if (ranges == null) { ranges = new ITextRangeProvider[] { new TextRangeAdaptor(this, _textContainer.Start, _textContainer.Start, _textPeer) }; } return ranges; } /// <summary> /// Retrieves the range of a child object. /// </summary> /// <param name="childElementProvider">The child element. A provider should check that the /// passed element is a child of the text container, and should throw an /// InvalidOperationException if it is not.</param> /// <returns>A range that spans the child element.</returns> ITextRangeProvider ITextProvider.RangeFromChild(IRawElementProviderSimple childElementProvider) { if (childElementProvider == null) { throw new ArgumentNullException("childElementProvider"); } // Retrieve DependencyObject from AutomationElement DependencyObject childElement; if (_textPeer is TextAutomationPeer) { childElement = ((TextAutomationPeer)_textPeer).ElementFromProvider(childElementProvider); } else { childElement = ((ContentTextAutomationPeer)_textPeer).ElementFromProvider(childElementProvider); } TextRangeAdaptor range = null; if (childElement != null) { ITextPointer rangeStart = null; ITextPointer rangeEnd = null; // Retrieve start and end positions for given element. // If element is TextElement, retrieve its Element Start and End positions. // If element is UIElement hosted by UIContainer (Inlien of Block), // retrieve content Start and End positions of the container. // Otherwise scan ITextContainer to find a range for given element. if (childElement is TextElement) { rangeStart = ((TextElement)childElement).ElementStart; rangeEnd = ((TextElement)childElement).ElementEnd; } else { DependencyObject parent = LogicalTreeHelper.GetParent(childElement); if (parent is InlineUIContainer || parent is BlockUIContainer) { rangeStart = ((TextElement)parent).ContentStart; rangeEnd = ((TextElement)parent).ContentEnd; } else { ITextPointer position = _textContainer.Start.CreatePointer(); while (position.CompareTo(_textContainer.End) < 0) { TextPointerContext context = position.GetPointerContext(LogicalDirection.Forward); if (context == TextPointerContext.ElementStart) { if (childElement == position.GetAdjacentElement(LogicalDirection.Forward)) { rangeStart = position.CreatePointer(LogicalDirection.Forward); position.MoveToElementEdge(ElementEdge.AfterEnd); rangeEnd = position.CreatePointer(LogicalDirection.Backward); break; } } else if (context == TextPointerContext.EmbeddedElement) { if (childElement == position.GetAdjacentElement(LogicalDirection.Forward)) { rangeStart = position.CreatePointer(LogicalDirection.Forward); position.MoveToNextContextPosition(LogicalDirection.Forward); rangeEnd = position.CreatePointer(LogicalDirection.Backward); break; } } position.MoveToNextContextPosition(LogicalDirection.Forward); } } } // Create range if (rangeStart != null && rangeEnd != null) { range = new TextRangeAdaptor(this, rangeStart, rangeEnd, _textPeer); } } if (range == null) { throw new InvalidOperationException(SR.Get(SRID.TextProvider_InvalidChildElement)); } return range; } /// <summary> /// Finds the degenerate range nearest to a screen coordinate. /// </summary> /// <param name="location">The location in screen coordinates. /// The provider should check that the coordinates are within the client /// area of the provider, and should throw an InvalidOperation exception /// if they are not.</param> /// <returns>A degenerate range nearest the specified location.</returns> ITextRangeProvider ITextProvider.RangeFromPoint(Point location) { TextRangeAdaptor range = null; ITextView textView = GetUpdatedTextView(); if (textView != null) { // Convert the screen point to the element space coordinates. location = ScreenToClient(location, textView.RenderScope); ITextPointer position = textView.GetTextPositionFromPoint(location, true); if (position != null) { range = new TextRangeAdaptor(this, position, position, _textPeer); } } if (range == null) { throw new ArgumentException(SR.Get(SRID.TextProvider_InvalidPoint)); } return range; } /// <summary> /// A text range that encloses the main text of the document. Some auxillary text such as /// headers, footnotes, or annotations may not be included. /// </summary> ITextRangeProvider ITextProvider.DocumentRange { get { return new TextRangeAdaptor(this, _textContainer.Start, _textContainer.End, _textPeer); } } /// <summary> /// True if the text container supports text selection. If the provider returns false then /// it should throw InvalidOperation exceptions for ITextProvider.GetSelection and /// ITextRangeProvider.Select. /// </summary> SupportedTextSelection ITextProvider.SupportedTextSelection { get { return (_textContainer.TextSelection == null) ? SupportedTextSelection.None : SupportedTextSelection.Single; } } #endregion ITextProvider implementation } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.Runtime.InteropServices; /// <summary> /// RopLogon request buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RopLogonRequest : ISerializable { /// <summary> /// This value specifies the type of remote operation. For this operation, this field is set to 0xFE. /// </summary> public byte RopId; /// <summary> /// This value specifies the ID that the client wants associated with the created logon. /// Any value is allowed and the client does not have to use values in a certain numeric order. /// If the client specifies an active logon ID, the current logon is released and replaced with the new one. /// </summary> public byte LogonId; /// <summary> /// This index specifies the location in the Server Object Handle Table where the handle for /// the output Server Object will be stored. /// </summary> public byte OutputHandleIndex; /// <summary> /// The possible values are specified in [MS-OXCSTOR]. This structure contains flags that control the behavior of the logon. /// </summary> public byte LogonFlags; /// <summary> /// The possible values are specified in [MS-OXCSTOR]. This structure contains more flags that control the behavior of the logon. /// </summary> public uint OpenFlags; /// <summary> /// The possible values are specified in [MS-OXCSTOR]. This structure specifies ongoing action on the mailbox or public folder. /// </summary> public uint StoreState; /// <summary> /// This value specifies the size of the Essdn field. /// </summary> public ushort EssdnSize; /// <summary> /// Null terminated ASCII string. The number of characters (including the null) contained in this field is specified by the EssdnSize field. /// This string specifies which mailbox to log on to. /// </summary> public byte[] Essdn; /// <summary> /// Serialize the ROP request buffer. /// </summary> /// <returns>The ROP request buffer serialized.</returns> public byte[] Serialize() { int index = 0; byte[] serializeBuffer = new byte[this.Size()]; serializeBuffer[index++] = this.RopId; serializeBuffer[index++] = this.LogonId; serializeBuffer[index++] = this.OutputHandleIndex; serializeBuffer[index++] = this.LogonFlags; Array.Copy(BitConverter.GetBytes((int)this.OpenFlags), 0, serializeBuffer, index, sizeof(uint)); index += sizeof(uint); Array.Copy(BitConverter.GetBytes((int)this.StoreState), 0, serializeBuffer, index, sizeof(uint)); index += sizeof(uint); Array.Copy(BitConverter.GetBytes((short)this.EssdnSize), 0, serializeBuffer, index, sizeof(ushort)); index += sizeof(ushort); if (this.EssdnSize > 0) { Array.Copy(this.Essdn, 0, serializeBuffer, index, this.EssdnSize); index += this.EssdnSize; } return serializeBuffer; } /// <summary> /// Return the size of this structure. /// </summary> /// <returns>The size of this structure.</returns> public int Size() { int size = (sizeof(byte) * 4) + (2 * sizeof(uint)) + sizeof(ushort); if (this.EssdnSize > 0) { size += this.EssdnSize; } return size; } } /// <summary> /// This structure specifies the time at which the logon occurred. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LogonTime : IDeserializable { /// <summary> /// This value specifies the current second. /// </summary> public byte Seconds; /// <summary> /// This value specifies the current minute. /// </summary> public byte Minutes; /// <summary> /// This value specifies the current hour. /// </summary> public byte Hour; /// <summary> /// This value specifies the current day of the week (Sunday = 0, Monday = 1, and so on). /// </summary> public byte DayOfWeek; /// <summary> /// This value specifies the current day of the month. /// </summary> public byte Day; /// <summary> /// This value specifies the current month (January = 1, February = 2, and so on). /// </summary> public byte Month; /// <summary> /// Unsigned 16-bit integer. This value specifies the current year. /// </summary> public ushort Year; /// <summary> /// Deserialize the ROP response buffer. /// </summary> /// <param name="ropBytes">ROPs bytes in response.</param> /// <param name="startIndex">The start index of this ROP.</param> /// <returns>The size of response buffer structure.</returns> public int Deserialize(byte[] ropBytes, int startIndex) { IntPtr responseBuffer = new IntPtr(); responseBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(this)); try { Marshal.Copy(ropBytes, startIndex, responseBuffer, Marshal.SizeOf(this)); this = (LogonTime)Marshal.PtrToStructure(responseBuffer, typeof(LogonTime)); return Marshal.SizeOf(this); } finally { Marshal.FreeHGlobal(responseBuffer); } } } /// <summary> /// RopLogon response buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RopLogonResponse : IDeserializable { /// <summary> /// This value specifies the type of remote operation. For this operation, this field is set to 0xFE. /// </summary> public byte RopId; /// <summary> /// This index specifies the location in the Server Object Handle Table /// where the handle for the output Server Object will be stored. /// </summary> public byte OutputHandleIndex; /// <summary> /// This value specifies the status of the remote operation. For this response, this field is set to 0x00000000. /// </summary> public uint ReturnValue; /// <summary> /// The possible values are specified in [MS-OXCSTOR]. These flags specify the type of logon. /// </summary> public byte LogonFlags; /// <summary> /// 13 64-bit identifiers. These IDs specify a set of special folders for a mailbox. /// </summary> public ulong[] FolderIds; /// <summary> /// 16-bit identifier. This field specifies a replica ID for the logon. /// </summary> public byte[] ReplId; /// <summary> /// This field is not used and is ignored by the client. The server SHOULD set this field to an empty GUID (all zeroes). /// </summary> public byte[] PerUserGuid; /// <summary> /// 8-bit flags structure. The possible values are specified in [MS-OXCSTOR]. /// These flags provide details about the state of the mailbox. /// </summary> public byte ResponseFlags; /// <summary> /// GUID. This value identifies the mailbox on which the logon was performed. /// </summary> public byte[] MailboxGuid; /// <summary> /// GUID. This field specifies the replica GUID that is associated with the replica ID, /// which is specified in the ReplId field. /// </summary> public byte[] ReplGuid; /// <summary> /// LogonTime structure. The format of this structure is specified in section 2.2.2.1.2.1. /// This structure specifies the time at which the logon occurred. /// </summary> public LogonTime LogonTime; /// <summary> /// Unsigned 64-bit integer. This value represents the number of 100-nanosecond intervals since January 1, 1601. /// This time specifies when the Gateway Address Routing Table last changed. /// </summary> public ulong GwartTime; /// <summary> /// 32-bit flags structure. The possible values are specified in [MS-OXCSTOR]. /// These flags specify ongoing action on the mailbox or public folder. /// </summary> public uint StoreState; /// <summary> /// Unsigned 8-bit integer. This value specifies the length of the ServerName field. /// </summary> public byte ServerNameSize; /// <summary> /// Null terminated ASCII string. The number of characters (including the null) contained in this field /// is specified by the ServerNameSize field. This string specifies a different server for the client to connect to. /// </summary> public byte[] ServerName; /// <summary> /// Deserialize the ROP response buffer. /// </summary> /// <param name="ropBytes">ROPs bytes in response.</param> /// <param name="startIndex">The start index of this ROP.</param> /// <returns>The size of response buffer structure.</returns> public int Deserialize(byte[] ropBytes, int startIndex) { int index = startIndex; this.RopId = ropBytes[index++]; this.OutputHandleIndex = ropBytes[index++]; this.ReturnValue = (uint)BitConverter.ToInt32(ropBytes, index); index += sizeof(uint); // Only success response has below fields if (this.ReturnValue == 0) { this.LogonFlags = ropBytes[index++]; if ((this.LogonFlags & (byte)TestSuites.Common.LogonFlags.Private) != 0x00) { // The length of FolderIds is 13. this.FolderIds = new ulong[13]; for (int i = 0; i < 13; i++) { this.FolderIds[i] = (ulong)BitConverter.ToInt64(ropBytes, index); index += sizeof(ulong); } this.ResponseFlags = ropBytes[index++]; // Guid holds 16 bytes. this.MailboxGuid = new byte[16]; Array.Copy(ropBytes, index, this.MailboxGuid, 0, 16); index += 16; // ReplId holds 16 bits. this.ReplId = new byte[2]; Array.Copy(ropBytes, index, this.ReplId, 0, 2); index += 2; // ReplGuid holds 16 bytes. this.ReplGuid = new byte[16]; Array.Copy(ropBytes, index, this.ReplGuid, 0, 16); index += 16; index += this.LogonTime.Deserialize(ropBytes, index); this.GwartTime = (ulong)BitConverter.ToInt64(ropBytes, index); index += sizeof(ulong); this.StoreState = (uint)BitConverter.ToInt32(ropBytes, index); index += sizeof(uint); } else { // The length of FolderIds is 13. this.FolderIds = new ulong[13]; for (int i = 0; i < 13; i++) { this.FolderIds[i] = (ulong)BitConverter.ToInt64(ropBytes, index); index += sizeof(ulong); } // ReplId holds 16 bits. this.ReplId = new byte[2]; Array.Copy(ropBytes, index, this.ReplId, 0, 2); index += 2; // ReplGuid holds 16 bytes. this.ReplGuid = new byte[16]; Array.Copy(ropBytes, index, this.ReplGuid, 0, 16); index += 16; // PerUserGuid holds 16 bytes. this.PerUserGuid = new byte[16]; Array.Copy(ropBytes, index, this.PerUserGuid, 0, 16); index += 16; } } else if (this.ReturnValue == 0x00000478) { // Redirect response 0x00000478. this.LogonFlags = ropBytes[index++]; this.ServerNameSize = ropBytes[index++]; if (this.ServerNameSize > 0) { this.ServerName = new byte[this.ServerNameSize]; Array.Copy(ropBytes, index, this.ServerName, 0, this.ServerNameSize); index += this.ServerNameSize; } } return index - startIndex; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial // processing queue, and using just the concurrent scheduler with a specified // MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across // a bunch of tasks, parallel loops, dataflow blocks, etc. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Threading.Tasks { /// <summary> /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair { /// <summary>A processing mode to denote what kinds of tasks are currently being processed on this thread.</summary> private readonly ThreadLocal<ProcessingMode> m_threadProcessingMode = new ThreadLocal<ProcessingMode>(); /// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary> private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; /// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary> private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; /// <summary>The underlying task scheduler to which all work should be scheduled.</summary> private readonly TaskScheduler m_underlyingTaskScheduler; /// <summary> /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, /// since exclusive tasks are inherently limited to 1. /// </summary> private readonly int m_maxConcurrencyLevel; /// <summary>The maximum number of tasks we can process before recycling our runner tasks.</summary> private readonly int m_maxItemsPerTask; /// <summary> /// If positive, it represents the number of concurrently running concurrent tasks. /// If negative, it means an exclusive task has been scheduled. /// If 0, nothing has been scheduled. /// </summary> private int m_processingCount; /// <summary>Completion state for a task representing the completion of this pair.</summary> /// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks> private CompletionState m_completionState; /// <summary>Lazily-initialized work item for processing when targeting the default scheduler.</summary> private SchedulerWorkItem m_threadPoolWorkItem; /// <summary>A constant value used to signal unlimited processing.</summary> private const int UNLIMITED_PROCESSING = -1; /// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary> private const int EXCLUSIVE_PROCESSING_SENTINEL = -1; /// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary> private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary> private static int DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// <summary>Gets the sync obj used to protect all state on this instance.</summary> private object ValueLock { get { return m_threadProcessingMode; } } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum /// concurrency level and a maximum number of scheduled tasks that may be processed as a unit. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> /// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); // Store configuration m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; // Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level int mcl = taskScheduler.MaximumConcurrencyLevel; if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl; // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = int.MaxValue; if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = int.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } /// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary> /// <remarks> /// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/> /// will be relied on for notification of all processing being completed. /// </remarks> public void Complete() { lock (ValueLock) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized(); } } /// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); } /// <summary>Gets whether completion has been requested.</summary> private bool CompletionRequested { // ValueLock not needed, but it's ok if it's held get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); } } /// <summary>Sets that completion has been requested.</summary> private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; } /// <summary> /// Cleans up state if and only if there's no processing currently happening /// and no more to be done later. /// </summary> private void CleanupStateIfCompletingAndQuiesced() { ContractAssertMonitorStatus(ValueLock, held: true); if (ReadyToComplete) CompleteTaskAsync(); } /// <summary>Gets whether the pair is ready to complete.</summary> private bool ReadyToComplete { get { ContractAssertMonitorStatus(ValueLock, held: true); // We can only complete if completion has been requested and no processing is currently happening. if (!CompletionRequested || m_processingCount != 0) return false; // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } /// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Debug.Assert(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context var cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { var localThis = (ConcurrentExclusiveSchedulerPair)state; Debug.Assert(!localThis.m_completionState.IsCompleted, "Completion should only happen once."); List<Exception> exceptions = localThis.m_completionState.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localThis.m_completionState.TrySetException(exceptions) : localThis.m_completionState.TrySetResult(); Debug.Assert(success, "Expected to complete completion task."); localThis.m_threadProcessingMode.Dispose(); }, this); } } /// <summary>Initiates scheduler shutdown due to a worker task faulting.</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Debug.Assert(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that may run concurrently with other tasks on this pair. /// </summary> public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that must run exclusively with regards to other tasks on this pair. /// </summary> public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } } /// <summary>Notifies the pair that new work has arrived to be processed.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <remarks>Must only be called while holding the lock.</remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary(bool fairly = false) { ContractAssertMonitorStatus(ValueLock, held: true); // If the current processing count is >= 0, we can potentially launch further processing. if (m_processingCount >= 0) { // We snap whether there are any exclusive tasks or concurrent tasks waiting. // (We grab the concurrent count below only once we know we need it.) // With processing happening concurrent to this operation, this data may // immediately be out of date, but it can only go from non-empty // to empty and not the other way around. As such, this is safe, // as worst case is we'll schedule an extra task when we didn't // otherwise need to, and we'll just eat its overhead. bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; // If there's no processing currently happening but there are waiting exclusive tasks, // let's start processing those exclusive tasks. Task processingTask = null; if (m_processingCount == 0 && exclusiveTasksAreWaiting) { // Launch exclusive task processing m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1 if (!TryQueueThreadPoolWorkItem(fairly)) { try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, default, GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. // Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask. } catch { m_processingCount = 0; FaultWithTask(processingTask); } } } // If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum // concurrency level for processing, let's start processing more concurrent tasks. else { int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count; if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel) { // Launch concurrent task processing, up to the allowed limit for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i) { ++m_processingCount; if (!TryQueueThreadPoolWorkItem(fairly)) { try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, default, GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch { --m_processingCount; FaultWithTask(processingTask); } } } } } // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary>Queues concurrent or exclusive task processing to the ThreadPool if the underlying scheduler is the default.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <returns>true if we're targeting the thread pool such that a worker could be queued; otherwise, false.</returns> private bool TryQueueThreadPoolWorkItem(bool fairly) { if (TaskScheduler.Default == m_underlyingTaskScheduler) { IThreadPoolWorkItem workItem = m_threadPoolWorkItem ?? (m_threadPoolWorkItem = new SchedulerWorkItem(this)); ThreadPool.UnsafeQueueUserWorkItemInternal(workItem, preferLocal: !fairly); return true; } return false; } /// <summary> /// Processes exclusive tasks serially until either there are no more to process /// or we've reached our user-specified maximum limit. /// </summary> private void ProcessExclusiveTasks() { Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); Debug.Assert(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing exclusive tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.NotCurrentlyProcessing, "This thread should not yet be involved in this pair's processing."); m_threadProcessingMode.Value = ProcessingMode.ProcessingExclusiveTask; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available exclusive task. If we can't find one, bail. Task exclusiveTask; if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask); } } finally { // We're no longer processing exclusive tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; lock (ValueLock) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Processes concurrent tasks serially until either there are no more to process, /// we've reached our user-specified maximum limit, or exclusive tasks have arrived. /// </summary> private void ProcessConcurrentTasks() { Debug.Assert(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing concurrent tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.NotCurrentlyProcessing, "This thread should not yet be involved in this pair's processing."); m_threadProcessingMode.Value = ProcessingMode.ProcessingConcurrentTasks; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available concurrent task. If we can't find one, bail. Task concurrentTask; if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask); // Now check to see if exclusive tasks have arrived; if any have, they take priority // so we'll bail out here. Note that we could have checked this condition // in the for loop's condition, but that could lead to extra overhead // in the case where a concurrent task arrives, this task is launched, and then // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent // race condition here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } } finally { // We're no longer processing concurrent tasks on the current thread Debug.Assert(m_threadProcessingMode.Value == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; lock (ValueLock) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Holder for lazily-initialized state about the completion of a scheduler pair. /// Completion is only triggered either by rare exceptional conditions or by /// the user calling Complete, and as such we only lazily initialize this /// state in one of those conditions or if the user explicitly asks for /// the Completion. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class CompletionState : Task { /// <summary>Whether the scheduler has had completion requested.</summary> /// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks> internal bool m_completionRequested; /// <summary>Whether completion processing has been queued.</summary> internal bool m_completionQueued; /// <summary>Unrecoverable exceptions incurred while processing.</summary> internal List<Exception> m_exceptions; } /// <summary>Reusable immutable work item that can be scheduled to the thread pool to run processing.</summary> private sealed class SchedulerWorkItem : IThreadPoolWorkItem { private readonly ConcurrentExclusiveSchedulerPair _pair; internal SchedulerWorkItem(ConcurrentExclusiveSchedulerPair pair) => _pair = pair; void IThreadPoolWorkItem.Execute() { if (_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) { _pair.ProcessExclusiveTasks(); } else { _pair.ProcessConcurrentTasks(); } } } /// <summary> /// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair. /// </summary> [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { /// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary> private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim); /// <summary>The parent pair.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int m_maxConcurrencyLevel; /// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary> private readonly ProcessingMode m_processingMode; /// <summary>Gets the queue of tasks for this scheduler.</summary> internal readonly IProducerConsumerQueue<Task> m_tasks; /// <summary>Initializes the scheduler.</summary> /// <param name="pair">The parent pair.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param> /// <param name="processingMode">The processing mode of this scheduler.</param> internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { Debug.Assert(pair != null, "Scheduler must be associated with a valid pair."); Debug.Assert(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Debug.Assert( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ? (IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() : (IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>(); } /// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary> public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected internal override void QueueTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().ToString()); // Queue the task, and then let the pair know that more work is now available to be scheduled m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> internal void ExecuteTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } /// <summary>Tries to execute the task synchronously on this scheduler.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: // a) we don't need to be exact... a Complete call could come in later in the function anyway // b) this is only a fast path escape hatch. To actually inline the task, // we need to be inside of an already executing task, and in such a case, // while completion may have been requested, we can't have shutdown yet. if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false; // We know the implementation of the default scheduler and how it will behave. // As it's the most common underlying scheduler, we optimize for it. bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; // If we're targeting the default scheduler and taskWasPreviouslyQueued is true, // we know that the default scheduler will only allow it to be inlined // if we're on a thread pool thread (but it won't always allow it in that case, // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } else { // If a task is already running on this thread, allow inline execution to proceed. // If there's already a task from this scheduler running on the current thread, we know it's safe // to run this task, in effect temporarily taking that task's count allocation. if (m_pair.m_threadProcessingMode.Value == m_processingMode) { // If we're targeting the default scheduler and taskWasPreviouslyQueued is false, // we know the default scheduler will allow it, so we can just execute it here. // Otherwise, delegate to the target scheduler's inlining. return (isDefaultScheduler && !taskWasPreviouslyQueued) ? TryExecuteTask(task) : TryExecuteTaskInlineOnTargetScheduler(task); } } // We're not in the context of a task already executing on this scheduler. Bail. return false; } /// <summary> /// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler, /// which we can't call directly on the underlying scheduler. /// </summary> /// <param name="task">The task to execute inline if possible.</param> /// <returns>true if the task was inlined successfully; otherwise, false.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { // We'd like to simply call TryExecuteTaskInline here, but we can't. // As there's no built-in API for this, a workaround is to create a new task that, // when executed, will simply call TryExecuteTask to run the real task, and then // we run our new shim task synchronously on the target scheduler. If all goes well, // our synchronous invocation will succeed in running the shim task on the current thread, // which will in turn run the real task on the current thread. If the scheduler // doesn't allow that execution, RunSynchronously will block until the underlying scheduler // is able to invoke the task, which might account for an additional but unavoidable delay. // Once it's done, we can return whether the task executed by returning the // shim task's Result, which is in turn the result of TryExecuteTask. var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task)); try { t.RunSynchronously(m_pair.m_underlyingTaskScheduler); return t.Result; } catch { Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } finally { t.Dispose(); } } /// <summary>Shim used to invoke this.TryExecuteTask(task).</summary> /// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param> /// <returns>true if the task was successfully inlined; otherwise, false.</returns> /// <remarks> /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; return tuple.Item1.TryExecuteTask(tuple.Item2); } /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int CountForDebugger { get { return m_tasks.Count; } } /// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary> private sealed class DebugView { /// <summary>The scheduler being debugged.</summary> private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler being debugged.</param> public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { Debug.Assert(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } /// <summary>Gets this pair's maximum allowed concurrency level.</summary> public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } } /// <summary>Gets the scheduler pair with which this scheduler is associated.</summary> public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } } } } /// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary> private sealed class DebugView { /// <summary>The pair being debugged.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>Initializes the debug view.</summary> /// <param name="pair">The pair being debugged.</param> public DebugView(ConcurrentExclusiveSchedulerPair pair) { Debug.Assert(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } /// <summary>Gets a representation of the execution state of the pair.</summary> public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks currently being executed.</summary> public int CurrentlyExecutingTaskCount { get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; } } /// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary> public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } } } /// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary> /// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks> private ProcessingMode ModeForDebugger { get { // If our completion task is done, so are we. if (m_completionState != null && m_completionState.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. var mode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask; if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks; if (CompletionRequested) mode |= ProcessingMode.Completing; return mode; } } /// <summary>Asserts that a given synchronization object is either held or not held.</summary> /// <param name="syncObj">The monitor to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> [Conditional("DEBUG")] private static void ContractAssertMonitorStatus(object syncObj, bool held) { Debug.Assert(syncObj != null, "The monitor object to check must be provided."); Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); } /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> /// These options should be used for all tasks that have the potential to run user code or /// that are repeatedly spawned and thus need a modicum of fair treatment. /// </remarks> /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions options = TaskCreationOptions.DenyChildAttach; if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary> [Flags] private enum ProcessingMode : byte { /// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary> NotCurrentlyProcessing = 0x0, /// <summary>The scheduler pair has queued processing for exclusive tasks.</summary> ProcessingExclusiveTask = 0x1, /// <summary>The scheduler pair has queued processing for concurrent tasks.</summary> ProcessingConcurrentTasks = 0x2, /// <summary>Completion has been requested.</summary> Completing = 0x4, /// <summary>The scheduler pair is finished processing.</summary> Completed = 0x8 } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/10/2009 9:25:51 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { /// <summary> /// LambertAzimuthalEqualArea /// </summary> public class LambertAzimuthalEqualArea : EllipticalTransform { #region Private Variables private double[] _apa; private double _cosb1; private double _dd; private Modes _mode; private double _qp; private double _rq; private double _sinb1; private double _xmf; private double _ymf; #endregion #region Constructors /// <summary> /// Creates a new instance of LambertAzimuthalEqualArea /// </summary> public LambertAzimuthalEqualArea() { Name = "Lambert_Azimuthal_Equal_Area"; Proj4Name = "laea"; } #endregion #region Methods /// <inheritdoc /> protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinb = 0, cosb = 0, b = 0; double coslam = Math.Cos(lp[lam]); double sinlam = Math.Sin(lp[lam]); double sinphi = Math.Sin(lp[phi]); double q = Proj.Qsfn(sinphi, E, OneEs); if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { sinb = q / _qp; cosb = Math.Sqrt(1 - sinb * sinb); } switch (_mode) { case Modes.Oblique: b = 1 + _sinb1 * sinb + _cosb1 * cosb * coslam; break; case Modes.Equitorial: b = 1 + cosb * coslam; break; case Modes.NorthPole: b = HALF_PI + lp[phi]; q = _qp - q; break; case Modes.SouthPole: b = lp[phi] - HALF_PI; q = _qp + q; break; } if (Math.Abs(b) < EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } switch (_mode) { case Modes.Oblique: xy[y] = _ymf * (b = Math.Sqrt(2 / b)) * (_cosb1 * sinb - _sinb1 * cosb * coslam); xy[x] = _xmf * b * cosb * sinlam; break; case Modes.Equitorial: xy[y] = (b = Math.Sqrt(2 / (1 + cosb * coslam))) * sinb * _ymf; xy[x] = _xmf * b * cosb * sinlam; break; case Modes.NorthPole: case Modes.SouthPole: if (q >= 0) { xy[x] = (b = Math.Sqrt(q)) * sinlam; xy[y] = coslam * (_mode == Modes.SouthPole ? b : -b); } else { xy[x] = xy[y] = 0; } break; } } } /// <inheritdoc /> protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinphi = Math.Sin(lp[phi]); double cosphi = Math.Cos(lp[phi]); double coslam = Math.Cos(lp[lam]); if (_mode == Modes.Equitorial || _mode == Modes.Oblique) { if (_mode == Modes.Equitorial) xy[x] = 1 + cosphi * coslam; if (_mode == Modes.Oblique) xy[y] = 1 + _sinb1 * sinphi + _cosb1 * cosphi * coslam; if (xy[y] <= EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[x] = (xy[y] = Math.Sqrt(2 / xy[y])) * cosphi * Math.Sin(lp[lam]); xy[y] *= _mode == Modes.Equitorial ? sinphi : _cosb1 * sinphi - _sinb1 * cosphi * coslam; } else { if (_mode == Modes.NorthPole) coslam = -coslam; if (Math.Abs(lp[phi] + Phi0) < EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[y] = FORT_PI - lp[phi] * .5; xy[y] = 2 * (_mode == Modes.SouthPole ? Math.Cos(xy[y]) : Math.Sin(xy[y])); xy[x] = xy[y] * Math.Sin(lp[lam]); xy[y] *= coslam; } } } /// <inheritdoc /> protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double ab; double cx = xy[x]; double cy = xy[y]; if (_mode == Modes.Equitorial || _mode == Modes.Oblique) { double rho = Proj.Hypot(cx /= _dd, cy * _dd); if (rho < EPS10) { lp[lam] = 0; lp[phi] = Phi0; return; } double sCe; double cCe = Math.Cos(sCe = 2 * Math.Asin(.5 * rho / _rq)); cx *= (sCe = Math.Sin(sCe)); if (_mode == Modes.Oblique) { ab = cCe * _sinb1 + y * sCe * _cosb1 / rho; //q = _qp*(ab); cy = rho * _cosb1 * cCe - cy * _sinb1 * sCe; } else { ab = cy * sCe / rho; //q = _qp*(ab); cy = rho * cCe; } } else { if (_mode == Modes.NorthPole) cy = -cy; double q; if ((q = (cx * cx + cy * cy)) == 0) { lp[lam] = 0; lp[phi] = Phi0; return; } ab = 1 - q / _qp; if (_mode == Modes.SouthPole) ab = -ab; } lp[lam] = Math.Atan2(cx, cy); lp[phi] = Proj.AuthLat(Math.Asin(ab), _apa); } } /// <inheritdoc /> protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cosz = 0, sinz = 0; double cx = xy[x]; double cy = xy[y]; double rh = Proj.Hypot(cx, cy); if ((lp[phi] = rh * .5) > 1) { lp[lam] = double.NaN; lp[phi] = double.NaN; continue; //throw new ProjectionException(20); } lp[phi] = 2 * Math.Asin(lp[phi]); if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { sinz = Math.Sin(lp[phi]); cosz = Math.Cos(lp[phi]); } switch (_mode) { case Modes.Equitorial: lp[phi] = Math.Abs(rh) <= EPS10 ? 0 : Math.Asin(cy * sinz / rh); cx *= sinz; cy = cosz * rh; break; case Modes.Oblique: lp[phi] = Math.Abs(rh) <= EPS10 ? Phi0 : Math.Asin(cosz * _sinb1 + cy * sinz * _sinb1 / rh); cx *= sinz * _cosb1; cy = (cosz - Math.Sin(lp[phi]) * _sinb1) * rh; break; case Modes.NorthPole: cy = -cy; lp[phi] = HALF_PI - lp[phi]; break; case Modes.SouthPole: lp[phi] -= HALF_PI; break; } lp[lam] = (cy == 0 && (_mode == Modes.Equitorial || _mode == Modes.Oblique)) ? 0 : Math.Atan2(cx, cy); } } /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { double t = Math.Abs(Phi0); if (Math.Abs(t - HALF_PI) < EPS10) { _mode = Phi0 < 0 ? Modes.SouthPole : Modes.NorthPole; } else if (Math.Abs(t) < EPS10) { _mode = Modes.Equitorial; } else { _mode = Modes.Oblique; } if (Es == 0) { IsElliptical = false; _mode = Modes.Oblique; _sinb1 = Math.Sin(Phi0); _cosb1 = Math.Cos(Phi0); return; } IsElliptical = true; _qp = Proj.Qsfn(1, E, OneEs); _apa = Proj.Authset(Es); switch (_mode) { case Modes.NorthPole: case Modes.SouthPole: _dd = 1; break; case Modes.Equitorial: _dd = 1 / (_rq = Math.Sqrt(.5 * _qp)); _xmf = 1; _ymf = .5 * _qp; break; case Modes.Oblique: _rq = Math.Sqrt(.5 * _qp); double sinphi = Math.Sin(Phi0); _sinb1 = Proj.Qsfn(sinphi, E, OneEs)/_qp; _cosb1 = Math.Sqrt(1 - _sinb1 * _sinb1); _dd = Math.Cos(Phi0) / (Math.Sqrt(1 - Es * sinphi * sinphi) * _rq * _cosb1); _ymf = _xmf = _rq / _dd; _xmf *= _dd; break; } } #endregion } }
//--------------------------------------------------------------------- // <copyright file="MultipartIdentifier.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Diagnostics; using System.Text; using System.Collections.Generic; namespace System.Data.Common.Internal { /// <summary> /// Copied from System.Data.dll /// </summary> internal static class MultipartIdentifier { private const int MaxParts = 4; internal const int ServerIndex = 0; internal const int CatalogIndex = 1; internal const int SchemaIndex = 2; internal const int TableIndex = 3; private enum MPIState { MPI_Value, MPI_ParseNonQuote, MPI_LookForSeparator, MPI_LookForNextCharOrSeparator, MPI_ParseQuote, MPI_RightQuote, } private static void IncrementStringCount(List<string> ary, ref int position) { ++position; ary.Add(string.Empty); } private static bool IsWhitespace(char ch) { return Char.IsWhiteSpace(ch); } /// <summary> /// Core function for parsing the multipart identifer string. /// Note: Left quote strings need to correspond 1 to 1 with the right quote strings /// example: "ab" "cd", passed in for the left and the right quote /// would set a or b as a starting quote character. /// If a is the starting quote char then c would be the ending quote char /// otherwise if b is the starting quote char then d would be the ending quote character. /// </summary> /// <param name="name">string to parse</param> /// <param name="leftQuote">set of characters which are valid quoteing characters to initiate a quote</param> /// <param name="rightQuote">set of characters which are valid to stop a quote, array index's correspond to the the leftquote array.</param> /// <param name="separator">separator to use</param> /// <returns></returns> internal static List<string> ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, char separator) { Debug.Assert(-1 == leftQuote.IndexOf(separator) && -1 == rightQuote.IndexOf(separator) && leftQuote.Length == rightQuote.Length, "Incorrect usage of quotes"); List<string> parsedNames = new List<string>(); parsedNames.Add(null); int stringCount = 0; // index of current string in the list MPIState state = MPIState.MPI_Value; // Initalize the starting state StringBuilder sb = new StringBuilder(name.Length); // String buffer to hold the string being currently built, init the string builder so it will never be resized StringBuilder whitespaceSB = null; // String buffer to hold white space used when parsing nonquoted strings 'a b . c d' = 'a b' and 'c d' char rightQuoteChar = ' '; // Right quote character to use given the left quote character found. for (int index = 0; index < name.Length; ++index) { char testchar = name[index]; switch (state) { case MPIState.MPI_Value: { int quoteIndex; if (IsWhitespace(testchar)) { // Is White Space then skip the whitespace continue; } else if (testchar == separator) { // If we found a separator, no string was found, initalize the string we are parsing to Empty and the next one to Empty. // This is NOT a redundent setting of string.Empty it solves the case where we are parsing ".foo" and we should be returning null, null, empty, foo parsedNames[stringCount] = string.Empty; IncrementStringCount(parsedNames, ref stringCount); } else if (-1 != (quoteIndex = leftQuote.IndexOf(testchar))) { // If we are a left quote rightQuoteChar = rightQuote[quoteIndex]; // record the corresponding right quote for the left quote sb.Length = 0; state = MPIState.MPI_ParseQuote; } else if (-1 != rightQuote.IndexOf(testchar)) { // If we shouldn't see a right quote throw EntityUtil.ADP_InvalidMultipartNameDelimiterUsage(); } else { sb.Length = 0; sb.Append(testchar); state = MPIState.MPI_ParseNonQuote; } break; } case MPIState.MPI_ParseNonQuote: { if (testchar == separator) { parsedNames[stringCount] = sb.ToString(); // set the currently parsed string IncrementStringCount(parsedNames, ref stringCount); state = MPIState.MPI_Value; } else // Quotes are not valid inside a non-quoted name if (-1 != rightQuote.IndexOf(testchar)) { throw EntityUtil.ADP_InvalidMultipartNameDelimiterUsage(); } else if (-1 != leftQuote.IndexOf(testchar)) { throw EntityUtil.ADP_InvalidMultipartNameDelimiterUsage(); } else if (IsWhitespace(testchar)) { // If it is Whitespace parsedNames[stringCount] = sb.ToString(); // Set the currently parsed string if (null == whitespaceSB) { whitespaceSB = new StringBuilder(); } whitespaceSB.Length = 0; whitespaceSB.Append(testchar); // start to record the white space, if we are parsing a name like "name with space" we should return "name with space" state = MPIState.MPI_LookForNextCharOrSeparator; } else { sb.Append(testchar); } break; } case MPIState.MPI_LookForNextCharOrSeparator: { if (!IsWhitespace(testchar)) { // If it is not whitespace if (testchar == separator) { IncrementStringCount(parsedNames, ref stringCount); state = MPIState.MPI_Value; } else { // If its not a separator and not whitespace sb.Append(whitespaceSB); sb.Append(testchar); parsedNames[stringCount] = sb.ToString(); // Need to set the name here in case the string ends here. state = MPIState.MPI_ParseNonQuote; } } else { whitespaceSB.Append(testchar); } break; } case MPIState.MPI_ParseQuote: { if (testchar == rightQuoteChar) { // if se are on a right quote see if we are escapeing the right quote or ending the quoted string state = MPIState.MPI_RightQuote; } else { sb.Append(testchar); // Append what we are currently parsing } break; } case MPIState.MPI_RightQuote: { if (testchar == rightQuoteChar) { // If the next char is a another right quote then we were escapeing the right quote sb.Append(testchar); state = MPIState.MPI_ParseQuote; } else if (testchar == separator) { // If its a separator then record what we've parsed parsedNames[stringCount] = sb.ToString(); IncrementStringCount(parsedNames, ref stringCount); state = MPIState.MPI_Value; } else if (!IsWhitespace(testchar)) { // If it is not white space we got problems throw EntityUtil.ADP_InvalidMultipartNameDelimiterUsage(); } else { // It is a whitespace character so the following char should be whitespace, separator, or end of string anything else is bad parsedNames[stringCount] = sb.ToString(); state = MPIState.MPI_LookForSeparator; } break; } case MPIState.MPI_LookForSeparator: { if (!IsWhitespace(testchar)) { // If it is not whitespace if (testchar == separator) { // If it is a separator IncrementStringCount(parsedNames, ref stringCount); state = MPIState.MPI_Value; } else { // Othewise not a separator throw EntityUtil.ADP_InvalidMultipartNameDelimiterUsage(); } } break; } } } // Resolve final states after parsing the string switch (state) { case MPIState.MPI_Value: // These states require no extra action case MPIState.MPI_LookForSeparator: case MPIState.MPI_LookForNextCharOrSeparator: break; case MPIState.MPI_ParseNonQuote: // Dump what ever was parsed case MPIState.MPI_RightQuote: parsedNames[stringCount] = sb.ToString(); break; case MPIState.MPI_ParseQuote: // Invalid Ending States default: throw EntityUtil.ADP_InvalidMultipartNameDelimiterUsage(); } return parsedNames; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Management.Sql.Models { /// <summary> /// Represents the properties of an Azure SQL Database security policy. /// </summary> public partial class DatabaseSecurityPolicyProperties { private bool _isAuditingEnabled; /// <summary> /// Optional. Gets or sets whether auditing is enabled. /// </summary> public bool IsAuditingEnabled { get { return this._isAuditingEnabled; } set { this._isAuditingEnabled = value; } } private bool _isBlockDirectAccessEnabled; /// <summary> /// Optional. Gets or sets a value indicating whether block direct /// access is enabled. /// </summary> public bool IsBlockDirectAccessEnabled { get { return this._isBlockDirectAccessEnabled; } set { this._isBlockDirectAccessEnabled = value; } } private bool _isEventTypeDataAccessEnabled; /// <summary> /// Optional. Gets or sets whether auditing data access events. /// </summary> public bool IsEventTypeDataAccessEnabled { get { return this._isEventTypeDataAccessEnabled; } set { this._isEventTypeDataAccessEnabled = value; } } private bool _isEventTypeDataChangesEnabled; /// <summary> /// Optional. Gets or sets whether auditing data changes events. /// </summary> public bool IsEventTypeDataChangesEnabled { get { return this._isEventTypeDataChangesEnabled; } set { this._isEventTypeDataChangesEnabled = value; } } private bool _isEventTypeGrantRevokePermissionsEnabled; /// <summary> /// Optional. Gets or sets whether auditing grant/revoke permissions /// events. /// </summary> public bool IsEventTypeGrantRevokePermissionsEnabled { get { return this._isEventTypeGrantRevokePermissionsEnabled; } set { this._isEventTypeGrantRevokePermissionsEnabled = value; } } private bool _isEventTypeSchemaChangeEnabled; /// <summary> /// Optional. Gets or sets whether auditing schema changes events. /// </summary> public bool IsEventTypeSchemaChangeEnabled { get { return this._isEventTypeSchemaChangeEnabled; } set { this._isEventTypeSchemaChangeEnabled = value; } } private bool _isEventTypeSecurityExceptionsEnabled; /// <summary> /// Optional. Gets or sets whether auditing security exceptions events. /// </summary> public bool IsEventTypeSecurityExceptionsEnabled { get { return this._isEventTypeSecurityExceptionsEnabled; } set { this._isEventTypeSecurityExceptionsEnabled = value; } } private string _proxyDnsName; /// <summary> /// Optional. Gets or sets the proxy DNS Name. /// </summary> public string ProxyDnsName { get { return this._proxyDnsName; } set { this._proxyDnsName = value; } } private string _proxyPort; /// <summary> /// Optional. Gets or sets the proxy port. /// </summary> public string ProxyPort { get { return this._proxyPort; } set { this._proxyPort = value; } } private int _retentionDays; /// <summary> /// Optional. Gets or sets the number of retention days. /// </summary> public int RetentionDays { get { return this._retentionDays; } set { this._retentionDays = value; } } private string _secondaryStorageAccountKey; /// <summary> /// Optional. Gets or sets the secondary storage account key. /// </summary> public string SecondaryStorageAccountKey { get { return this._secondaryStorageAccountKey; } set { this._secondaryStorageAccountKey = value; } } private string _storageAccountKey; /// <summary> /// Optional. Gets or sets the storage account key. /// </summary> public string StorageAccountKey { get { return this._storageAccountKey; } set { this._storageAccountKey = value; } } private string _storageAccountName; /// <summary> /// Optional. Gets or sets auditing Storage account name. /// </summary> public string StorageAccountName { get { return this._storageAccountName; } set { this._storageAccountName = value; } } private string _storageAccountResourceGroupName; /// <summary> /// Optional. Gets or sets the resource group name of the audit storage /// account. /// </summary> public string StorageAccountResourceGroupName { get { return this._storageAccountResourceGroupName; } set { this._storageAccountResourceGroupName = value; } } private string _storageAccountSubscriptionId; /// <summary> /// Optional. Gets or sets the subscription Id of the audit storage /// account. /// </summary> public string StorageAccountSubscriptionId { get { return this._storageAccountSubscriptionId; } set { this._storageAccountSubscriptionId = value; } } private string _storageTableEndpoint; /// <summary> /// Optional. Gets or sets the storage table end point. /// </summary> public string StorageTableEndpoint { get { return this._storageTableEndpoint; } set { this._storageTableEndpoint = value; } } private bool _useServerDefault; /// <summary> /// Optional. Gets or sets whether server default policy is used. /// </summary> public bool UseServerDefault { get { return this._useServerDefault; } set { this._useServerDefault = value; } } /// <summary> /// Initializes a new instance of the DatabaseSecurityPolicyProperties /// class. /// </summary> public DatabaseSecurityPolicyProperties() { } } }
// // AppleDeviceTrackInfo.cs // // Author: // Alan McGovern <amcgovern@novell.com> // // Copyright (c) 2010 Moonlight Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Banshee.Base; using Banshee.Streaming; using Banshee.Collection; using Banshee.Collection.Database; using Hyena; namespace Banshee.Dap.AppleDevice { public class AppleDeviceTrackInfo : DatabaseTrackInfo { internal GPod.Track IpodTrack { get; set; } // libgpod stores rating as stars*ITDB_RATING_STEP which is 20. private const int ITDB_RATING_STEP = 20; private string mimetype; private string description; // Only used for podcasts. public AppleDeviceTrackInfo (GPod.Track track) { IpodTrack = track; LoadFromIpodTrack (); CanSaveToDatabase = true; } public AppleDeviceTrackInfo (TrackInfo track) { CanSaveToDatabase = true; if (track is AppleDeviceTrackInfo) { IpodTrack = ((AppleDeviceTrackInfo)track).IpodTrack; LoadFromIpodTrack (); } else { UpdateInfo (track); } } public void UpdateInfo (TrackInfo track) { if (track is AppleDeviceTrackInfo) { throw new ArgumentException ("Shouldn't update an AppleDeviceTrackInfo from an AppleDeviceTrackInfo"); } IsCompilation = track.IsCompilation ; AlbumArtist = track.AlbumArtist; AlbumTitle = track.AlbumTitle; ArtistName = track.ArtistName; BitRate = track.BitRate; SampleRate = track.SampleRate; Bpm = track.Bpm; Comment = track.Comment; Composer = track.Composer; Conductor = track.Conductor; Copyright = track.Copyright; DateAdded = track.DateAdded; DiscCount = track.DiscCount; DiscNumber = track.DiscNumber; Duration = track.Duration; FileSize = track.FileSize; Genre = track.Genre; Grouping = track.Grouping; LastPlayed = track.LastPlayed; LastSkipped = track.LastSkipped; PlayCount = track.PlayCount; Rating = track.Rating; ReleaseDate = track.ReleaseDate; SkipCount = track.SkipCount; TrackCount = track.TrackCount; TrackNumber = track.TrackNumber; TrackTitle = track.TrackTitle; Year = track.Year; MediaAttributes = track.MediaAttributes; ArtistNameSort = track.ArtistNameSort; AlbumTitleSort = track.AlbumTitleSort; AlbumArtistSort = track.AlbumArtistSort; TrackTitleSort = track.TrackTitleSort; var podcast_info = track.ExternalObject as IPodcastInfo; if (podcast_info != null) { description = podcast_info.Description; ReleaseDate = podcast_info.ReleaseDate; } mimetype = track.MimeType; } private void LoadFromIpodTrack () { var track = IpodTrack; try { Uri = new SafeUri (System.IO.Path.Combine (track.ITDB.Mountpoint, track.IpodPath.Replace (":", System.IO.Path.DirectorySeparatorChar.ToString ()).Substring (1))); } catch (Exception ex) { Log.Exception (ex); Uri = null; } ExternalId = (long) track.DBID; IsCompilation = track.Compilation; AlbumArtist = track.AlbumArtist; AlbumTitle = String.IsNullOrEmpty (track.Album) ? null : track.Album; ArtistName = String.IsNullOrEmpty (track.Artist) ? null : track.Artist; BitRate = track.Bitrate; SampleRate = track.Samplerate; Bpm = (int)track.BPM; Comment = track.Comment; Composer = track.Composer; DateAdded = track.TimeAdded; DiscCount = track.CDs; DiscNumber = track.CDNumber; Duration = TimeSpan.FromMilliseconds (track.TrackLength); FileSize = track.Size; Genre = String.IsNullOrEmpty (track.Genre) ? null : track.Genre; Grouping = track.Grouping; LastPlayed = track.TimePlayed; PlayCount = (int) track.PlayCount; TrackCount = track.Tracks; TrackNumber = track.TrackNumber; TrackTitle = String.IsNullOrEmpty (track.Title) ? null : track.Title; Year = track.Year; description = track.Description; ReleaseDate = track.TimeReleased; ArtistNameSort = track.SortArtist; AlbumTitleSort = track.SortAlbum; AlbumArtistSort = track.SortAlbumArtist; TrackTitleSort = track.SortTitle; rating = track.Rating > 100 ? 0 : (int) track.Rating / ITDB_RATING_STEP; if (track.DRMUserID > 0) { PlaybackError = StreamPlaybackError.Drm; } MediaAttributes = TrackMediaAttributes.AudioStream; switch (track.MediaType) { case GPod.MediaType.Audio: MediaAttributes |= TrackMediaAttributes.Music; break; // This seems to cause audio files to show up in Banshee in the Videos section /*case GPod.MediaType.AudioVideo: MediaAttributes |= TrackMediaAttributes.VideoStream; break;*/ case GPod.MediaType.MusicVideo: MediaAttributes |= TrackMediaAttributes.Music | TrackMediaAttributes.VideoStream; break; case GPod.MediaType.Movie: MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.Movie; break; case GPod.MediaType.TVShow: MediaAttributes |= TrackMediaAttributes.VideoStream | TrackMediaAttributes.TvShow; break; case GPod.MediaType.Podcast: MediaAttributes |= TrackMediaAttributes.Podcast; // FIXME: persist URL on the track (track.PodcastUrl) break; case GPod.MediaType.Audiobook: MediaAttributes |= TrackMediaAttributes.AudioBook; break; case GPod.MediaType.MusicTVShow: MediaAttributes |= TrackMediaAttributes.Music | TrackMediaAttributes.VideoStream | TrackMediaAttributes.TvShow; break; } // If it's just AudioStream, add Music to it as well so it'll show up in Music if (MediaAttributes == TrackMediaAttributes.AudioStream) { MediaAttributes |= TrackMediaAttributes.Music; } } public void CommitToIpod (GPod.ITDB database) { bool addTrack = IpodTrack == null; if (IpodTrack == null) { IpodTrack = new GPod.Track (); } var track = IpodTrack; track.Compilation = IsCompilation; track.AlbumArtist = AlbumArtist; track.Bitrate = BitRate; track.Samplerate= (ushort)SampleRate; track.BPM = (short)Bpm; track.Comment = Comment; track.Composer = Composer; track.TimeAdded = DateTime.Now; track.CDs = DiscCount; track.CDNumber = DiscNumber; track.TrackLength = (int) Duration.TotalMilliseconds; track.Size = (uint)FileSize; track.Grouping = Grouping; try { track.TimePlayed = LastPlayed; } catch { Hyena.Log.InformationFormat ("Couldn't set TimePlayed to '{0}'", LastPlayed); } track.PlayCount = (uint) PlayCount; track.Tracks = TrackCount; track.TrackNumber = TrackNumber; track.Year = Year; try { track.TimeReleased = ReleaseDate; } catch { Hyena.Log.InformationFormat ("Couldn't set TimeReleased to '{0}'", ReleaseDate); } track.Album = AlbumTitle; track.Artist = ArtistName; track.Title = TrackTitle; track.Genre = Genre; track.SortArtist = ArtistNameSort; track.SortAlbum = AlbumTitleSort; track.SortAlbumArtist = AlbumArtistSort; track.SortTitle = TrackTitleSort; track.Rating = ((Rating >= 1) && (Rating <= 5)) ? (uint)Rating * ITDB_RATING_STEP : 0; if (HasAttribute (TrackMediaAttributes.Podcast)) { track.Description = description; track.RememberPlaybackPosition = true; track.SkipWhenShuffling = true; track.Flag4 = (byte)1; track.MarkUnplayed = (track.PlayCount == 0); } track.MediaType = GPod.MediaType.Audio; if (HasAttribute (TrackMediaAttributes.VideoStream)) { if (HasAttribute (TrackMediaAttributes.Podcast)) { track.MediaType = GPod.MediaType.Podcast | GPod.MediaType.Movie; } else if (HasAttribute (TrackMediaAttributes.Music)) { if (HasAttribute (TrackMediaAttributes.TvShow)) { track.MediaType = GPod.MediaType.MusicTVShow; } else { track.MediaType = GPod.MediaType.MusicVideo; } } else if (HasAttribute (TrackMediaAttributes.Movie)) { track.MediaType = GPod.MediaType.Movie; } else if (HasAttribute (TrackMediaAttributes.TvShow)) { track.MediaType = GPod.MediaType.TVShow; } else { // I dont' think AudioVideo should be used here; upon loading the tracks // into Banshee, audio files often have AudioVideo (aka MediaType == 0) too. //track.MediaType = GPod.MediaType.AudioVideo; track.MediaType = GPod.MediaType.Movie; } } else { if (HasAttribute (TrackMediaAttributes.Podcast)) { track.MediaType = GPod.MediaType.Podcast; } else if (HasAttribute (TrackMediaAttributes.AudioBook)) { track.MediaType = GPod.MediaType.Audiobook; } else if (HasAttribute (TrackMediaAttributes.Music)) { track.MediaType = GPod.MediaType.Audio; } else { track.MediaType = GPod.MediaType.Audio; } } if (addTrack) { track.Filetype = mimetype; database.Tracks.Add (IpodTrack); database.MasterPlaylist.Tracks.Add (IpodTrack); if (HasAttribute (TrackMediaAttributes.Podcast) && database.Device.SupportsPodcast) { database.PodcastsPlaylist.Tracks.Add (IpodTrack); } database.CopyTrackToIPod (track, Uri.LocalPath); Uri = new SafeUri (GPod.ITDB.GetLocalPath (database.Device, track)); ExternalId = (long) IpodTrack.DBID; } if (CoverArtSpec.CoverExists (ArtworkId)) { string path = CoverArtSpec.GetPath (ArtworkId); if (!track.ThumbnailsSet (path)) { Log.Error (String.Format ("Could not set cover art for {0}.", path)); } } else { track.ThumbnailsRemoveAll (); } } } }
// 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: Helpers for XML input & output ** ===========================================================*/ namespace System.Security.Util { using System; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.IO; using System.Text; using System.Runtime.CompilerServices; using PermissionState = System.Security.Permissions.PermissionState; using BindingFlags = System.Reflection.BindingFlags; using Assembly = System.Reflection.Assembly; using System.Threading; using System.Globalization; using System.Reflection; using System.Diagnostics.Contracts; internal static class XMLUtil { // // Warning: Element constructors have side-effects on their // third argument. // private const String BuiltInPermission = "System.Security.Permissions."; #if FEATURE_CAS_POLICY private const String BuiltInMembershipCondition = "System.Security.Policy."; private const String BuiltInCodeGroup = "System.Security.Policy."; private const String BuiltInApplicationSecurityManager = "System.Security.Policy."; private static readonly char[] sepChar = {',', ' '}; #endif public static SecurityElement NewPermissionElement (IPermission ip) { return NewPermissionElement (ip.GetType ().FullName) ; } public static SecurityElement NewPermissionElement (String name) { SecurityElement ecr = new SecurityElement( "Permission" ); ecr.AddAttribute( "class", name ); return ecr; } public static void AddClassAttribute( SecurityElement element, Type type, String typename ) { // Replace any quotes with apostrophes so that we can include quoted materials // within classnames. Notably the assembly name member 'loc' uses a quoted string. // NOTE: this makes assumptions as to what reflection is expecting for a type string // it will need to be updated if reflection changes what it wants. if ( typename == null ) typename = type.FullName; Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName); element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) ); } internal static bool ParseElementForAssemblyIdentification(SecurityElement el, out String className, out String assemblyName, // for example "WindowsBase" out String assemblyVersion) { className = null; assemblyName = null; assemblyVersion = null; String fullClassName = el.Attribute( "class" ); if (fullClassName == null) { return false; } if (fullClassName.IndexOf('\'') >= 0) { fullClassName = fullClassName.Replace( '\'', '\"' ); } int commaIndex = fullClassName.IndexOf( ',' ); int namespaceClassNameLength; // If the classname is tagged with assembly information, find where // the assembly information begins. if (commaIndex == -1) { return false; } namespaceClassNameLength = commaIndex; className = fullClassName.Substring(0, namespaceClassNameLength); String assemblyFullName = fullClassName.Substring(commaIndex + 1); AssemblyName an = new AssemblyName(assemblyFullName); assemblyName = an.Name; assemblyVersion = an.Version.ToString(); return true; } [System.Security.SecurityCritical] // auto-generated private static bool ParseElementForObjectCreation( SecurityElement el, String requiredNamespace, out String className, out int classNameStart, out int classNameLength ) { className = null; classNameStart = 0; classNameLength = 0; int requiredNamespaceLength = requiredNamespace.Length; String fullClassName = el.Attribute( "class" ); if (fullClassName == null) { throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) ); } if (fullClassName.IndexOf('\'') >= 0) { fullClassName = fullClassName.Replace( '\'', '\"' ); } if (!PermissionToken.IsMscorlibClassName( fullClassName )) { return false; } int commaIndex = fullClassName.IndexOf( ',' ); int namespaceClassNameLength; // If the classname is tagged with assembly information, find where // the assembly information begins. if (commaIndex == -1) { namespaceClassNameLength = fullClassName.Length; } else { namespaceClassNameLength = commaIndex; } // Only if the length of the class name is greater than the namespace info // on our requiredNamespace do we continue // with our check. if (namespaceClassNameLength > requiredNamespaceLength) { // Make sure we are in the required namespace. if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal)) { className = fullClassName; classNameLength = namespaceClassNameLength - requiredNamespaceLength; classNameStart = requiredNamespaceLength; return true; } } return false; } #if FEATURE_CAS_POLICY public static String SecurityObjectToXmlString(Object ob) { if(ob == null) return ""; PermissionSet pset = ob as PermissionSet; if(pset != null) return pset.ToXml().ToString(); return ((IPermission)ob).ToXml().ToString(); } [System.Security.SecurityCritical] // auto-generated public static Object XmlStringToSecurityObject(String s) { if(s == null) return null; if(s.Length < 1) return null; return SecurityElement.FromString(s).ToSecurityObject(); } #endif // FEATURE_CAS_POLICY [SecuritySafeCritical] public static IPermission CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures) { if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) ) throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ; Contract.EndContractBlock(); String className; int classNameLength; int classNameStart; if (!ParseElementForObjectCreation( el, BuiltInPermission, out className, out classNameStart, out classNameLength )) { goto USEREFLECTION; } // We have a built in permission, figure out which it is. // UIPermission // FileIOPermission // SecurityPermission // PrincipalPermission // ReflectionPermission // FileDialogPermission // EnvironmentPermission // GacIdentityPermission // UrlIdentityPermission // SiteIdentityPermission // ZoneIdentityPermission // KeyContainerPermission // UnsafeForHostPermission // HostProtectionPermission // StrongNameIdentityPermission #if !FEATURE_CORECLR // IsolatedStorageFilePermission #endif // RegistryPermission // PublisherIdentityPermission switch (classNameLength) { case 12: // UIPermission if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new UIPermission( permState ); else goto USEREFLECTION; case 16: // FileIOPermission if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new FileIOPermission( permState ); else goto USEREFLECTION; case 18: // RegistryPermission // SecurityPermission if (className[classNameStart] == 'R') { if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new RegistryPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new SecurityPermission( permState ); else goto USEREFLECTION; } #if !FEATURE_CORECLR case 19: // PrincipalPermission if (String.Compare(className, classNameStart, "PrincipalPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new PrincipalPermission( permState ); else goto USEREFLECTION; #endif // !FEATURE_CORECLR case 20: // ReflectionPermission // FileDialogPermission if (className[classNameStart] == 'R') { if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new ReflectionPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new FileDialogPermission( permState ); else goto USEREFLECTION; } case 21: // EnvironmentPermission // UrlIdentityPermission // GacIdentityPermission if (className[classNameStart] == 'E') { if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new EnvironmentPermission( permState ); else goto USEREFLECTION; } else if (className[classNameStart] == 'U') { if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new UrlIdentityPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new GacIdentityPermission( permState ); else goto USEREFLECTION; } case 22: // SiteIdentityPermission // ZoneIdentityPermission // KeyContainerPermission if (className[classNameStart] == 'S') { if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new SiteIdentityPermission( permState ); else goto USEREFLECTION; } else if (className[classNameStart] == 'Z') { if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new ZoneIdentityPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new KeyContainerPermission( permState ); else goto USEREFLECTION; } case 24: // HostProtectionPermission if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new HostProtectionPermission( permState ); else goto USEREFLECTION; #if FEATURE_X509 && FEATURE_CAS_POLICY case 27: // PublisherIdentityPermission if (String.Compare(className, classNameStart, "PublisherIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new PublisherIdentityPermission( permState ); else goto USEREFLECTION; #endif // FEATURE_X509 && FEATURE_CAS_POLICY case 28: // StrongNameIdentityPermission if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new StrongNameIdentityPermission( permState ); else goto USEREFLECTION; #if !FEATURE_CORECLR case 29: // IsolatedStorageFilePermission if (String.Compare(className, classNameStart, "IsolatedStorageFilePermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new IsolatedStorageFilePermission( permState ); else goto USEREFLECTION; #endif default: goto USEREFLECTION; } USEREFLECTION: Object[] objs = new Object[1]; objs[0] = permState; Type permClass = null; IPermission perm = null; new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); permClass = GetClassFromElement(el, ignoreTypeLoadFailures); if (permClass == null) return null; if (!(typeof(IPermission).IsAssignableFrom(permClass))) throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") ); perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null ); return perm; } #if FEATURE_CAS_POLICY #pragma warning disable 618 // CodeGroups are obsolete [System.Security.SecuritySafeCritical] // auto-generated public static CodeGroup CreateCodeGroup (SecurityElement el) { if (el == null || !el.Tag.Equals("CodeGroup")) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<CodeGroup>" ) ) ; Contract.EndContractBlock(); String className; int classNameLength; int classNameStart; if (!ParseElementForObjectCreation( el, BuiltInCodeGroup, out className, out classNameStart, out classNameLength )) { goto USEREFLECTION; } switch (classNameLength) { case 12: // NetCodeGroup if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new NetCodeGroup(); else goto USEREFLECTION; case 13: // FileCodeGroup if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new FileCodeGroup(); else goto USEREFLECTION; case 14: // UnionCodeGroup if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new UnionCodeGroup(); else goto USEREFLECTION; case 19: // FirstMatchCodeGroup if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new FirstMatchCodeGroup(); else goto USEREFLECTION; default: goto USEREFLECTION; } USEREFLECTION: Type groupClass = null; CodeGroup group = null; new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); groupClass = GetClassFromElement(el, true); if (groupClass == null) return null; if (!(typeof(CodeGroup).IsAssignableFrom(groupClass))) throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") ); group = (CodeGroup) Activator.CreateInstance(groupClass, true); Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(), "This path should not get called for mscorlib based classes" ); return group; } #pragma warning restore 618 [System.Security.SecurityCritical] // auto-generated internal static IMembershipCondition CreateMembershipCondition( SecurityElement el ) { if (el == null || !el.Tag.Equals("IMembershipCondition")) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<IMembershipCondition>" ) ) ; Contract.EndContractBlock(); String className; int classNameStart; int classNameLength; if (!ParseElementForObjectCreation( el, BuiltInMembershipCondition, out className, out classNameStart, out classNameLength )) { goto USEREFLECTION; } // We have a built in membership condition, figure out which it is. // Here's the list of built in membership conditions as of 9/17/2002 // System.Security.Policy.AllMembershipCondition // System.Security.Policy.URLMembershipCondition // System.Security.Policy.SHA1MembershipCondition // System.Security.Policy.SiteMembershipCondition // System.Security.Policy.ZoneMembershipCondition // System.Security.Policy.PublisherMembershipCondition // System.Security.Policy.StrongNameMembershipCondition // System.Security.Policy.ApplicationMembershipCondition // System.Security.Policy.DomainApplicationMembershipCondition // System.Security.Policy.ApplicationDirectoryMembershipCondition switch (classNameLength) { case 22: // AllMembershipCondition // URLMembershipCondition if (className[classNameStart] == 'A') { if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new AllMembershipCondition(); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new UrlMembershipCondition(); else goto USEREFLECTION; } case 23: // HashMembershipCondition // SiteMembershipCondition // ZoneMembershipCondition if (className[classNameStart] == 'H') { if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new HashMembershipCondition(); else goto USEREFLECTION; } else if (className[classNameStart] == 'S') { if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new SiteMembershipCondition(); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new ZoneMembershipCondition(); else goto USEREFLECTION; } case 28: // PublisherMembershipCondition if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new PublisherMembershipCondition(); else goto USEREFLECTION; case 29: // StrongNameMembershipCondition if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new StrongNameMembershipCondition(); else goto USEREFLECTION; case 39: // ApplicationDirectoryMembershipCondition if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new ApplicationDirectoryMembershipCondition(); else goto USEREFLECTION; default: goto USEREFLECTION; } USEREFLECTION: Type condClass = null; IMembershipCondition cond = null; new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); condClass = GetClassFromElement(el, true); if (condClass == null) return null; if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass))) throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") ); cond = (IMembershipCondition) Activator.CreateInstance(condClass, true); return cond; } #endif //#if FEATURE_CAS_POLICY internal static Type GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures) { String className = el.Attribute( "class" ); if (className == null) { if (ignoreTypeLoadFailures) return null; else throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") ); } if (ignoreTypeLoadFailures) { try { return Type.GetType(className, false, false); } catch (SecurityException) { return null; } } else return Type.GetType(className, true, false); } public static bool IsPermissionElement (IPermission ip, SecurityElement el) { if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission")) return false; return true; } public static bool IsUnrestricted (SecurityElement el) { String sUnrestricted = el.Attribute( "Unrestricted" ); if (sUnrestricted == null) return false; return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" ); } public static String BitFieldEnumToString( Type type, Object value ) { int iValue = (int)value; if (iValue == 0) return Enum.GetName( type, 0 ); StringBuilder result = StringBuilderCache.Acquire(); bool first = true; int flag = 0x1; for (int i = 1; i < 32; ++i) { if ((flag & iValue) != 0) { String sFlag = Enum.GetName( type, flag ); if (sFlag == null) continue; if (!first) { result.Append( ", " ); } result.Append( sFlag ); first = false; } flag = flag << 1; } return StringBuilderCache.GetStringAndRelease(result); } } }
//------------------------------------------------------------------------------ // <copyright file="_ComImports.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #define AUTOPROXY_MANAGED_JSCRIPT #if !AUTOPROXY_MANAGED_JSCRIPT namespace System.Net.ComImports { using System.Runtime.InteropServices; using EXCEPINFO = System.Runtime.InteropServices.ComTypes.EXCEPINFO; // // HRESULTs // internal enum HRESULT { TYPE_E_ELEMENTNOTFOUND = unchecked((int) 0x8002802B), SCRIPT_E_REPORTED = unchecked((int) 0x80020101), E_NOTIMPL = unchecked((int)0x80004001), E_NOINTERFACE = unchecked((int)0x80004002), S_OK = 0x00000000, S_FALSE = 0x00000001 } // // Scripting Interfaces // internal enum ScriptState : uint { Uninitialized = 0, Started = 1, Connected = 2, Disconnected = 3, Closed = 4, Initialized = 5, } internal enum ScriptThreadState : uint { NotInScript = 0, Running = 1, } [Flags] internal enum ScriptText : uint { None = 0x0000, DelayExecution = 0x0001, IsVisible = 0x0002, IsExpression = 0x0020, IsPersistent = 0x0040, HostManageSource = 0x0080, } [Flags] internal enum ScriptItem : uint { None = 0x0000, IsVisible = 0x0002, IsSource = 0x0004, GlobalMembers = 0x0008, IsPersistent = 0x0040, CodeOnly = 0x0200, NoCode = 0x0400, } [Flags] internal enum ScriptInfo : uint { None = 0x0000, IUnknown = 0x0001, ITypeInfo = 0x0002, } // // A "fake" interface to use to interact with the script itself through IDispatch. // It uses the IDispatch guid. New methods can be added as needed in any order. // [ComImport] [Guid("00020400-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] internal interface IScript { object FindProxyForURL(string url, string host); } [ComImport] [Guid("BB1A2AE1-A4F9-11cf-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IActiveScript { void SetScriptSite(IActiveScriptSite pass); void GetScriptSite(Guid riid, out IntPtr site); void SetScriptState(ScriptState state); void GetScriptState(out ScriptState scriptState); void Close(); void AddNamedItem(string name, ScriptItem flags); void AddTypeLib(Guid typeLib, uint major, uint minor, uint flags); void GetScriptDispatch(string itemName, out IScript dispatch); void GetCurrentScriptThreadID(out uint thread); void GetScriptThreadID(uint win32ThreadId, out uint thread); void GetScriptThreadState(uint thread, out ScriptThreadState state); void InterruptScriptThread(uint thread, out EXCEPINFO exceptionInfo, uint flags); void Clone(out IActiveScript script); } [ComImport] [Guid("DB01A1E3-A42B-11cf-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IActiveScriptSite { void GetLCID(out int lcid); void GetItemInfo( string name, ScriptInfo returnMask, [Out] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown)] object[] item, [Out] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] typeInfo); void GetDocVersionString(out string version); void OnScriptTerminate(object result, EXCEPINFO exceptionInfo); void OnStateChange(ScriptState scriptState); void OnScriptError(IActiveScriptError scriptError); void OnEnterScript(); void OnLeaveScript(); } internal enum UrlPolicy { DisAllow = 0x03 } [ComImport(), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IOleServiceProvider { [PreserveSig] int QueryService([In] ref Guid guidService, [In] ref Guid riid, [Out] out IntPtr ppvObject); } internal static class ComConstants { public const int INTERFACE_USES_SECURITY_MANAGER = 0x00000008; // Object knows to use IInternetHostSecurityManager } [ComImport] [Guid("CB5BDC81-93C1-11cf-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IObjectSafety { [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int GetInterfaceSafetyOptions(ref Guid riid, [Out] out int pdwSupportedOptions, [Out] out int pdwEnabledOptions); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions); } [ComImport] [Guid("3af280b6-cb3f-11d0-891e-00c04fb6bfc4")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IInternetHostSecurityManager { [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int GetSecurityId([Out] byte[] pbSecurityId, [In, Out]ref IntPtr pcbSecurityId, IntPtr dwReserved); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int ProcessUrlAction(int dwAction, [Out] int[] pPolicy, int cbPolicy, [Out] byte[] pContext, int cbContext, int dwFlags, int dwReserved); [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int QueryCustomPolicy(Guid guidKey, [Out] out byte[] ppPolicy, [Out] out int pcbPolicy, byte[] pContext, int cbContext, int dwReserved); } [ComImport] [Guid("EAE1BA61-A4ED-11cf-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IActiveScriptError { void GetExceptionInfo(out EXCEPINFO exceptionInfo); void GetSourcePosition(out uint sourceContext, out uint lineNumber, out int characterPosition); void GetSourceLineText(out string sourceLine); } [ComImport] [Guid("BB1A2AE2-A4F9-11cf-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IActiveScriptParse32 { void InitNew(); void AddScriptlet( string defaultName, string code, string itemName, string subItemName, string eventName, string delimiter, IntPtr sourceContextCookie, uint startingLineNumber, ScriptText flags, out string name, out EXCEPINFO exceptionInfo); void ParseScriptText( string code, string itemName, [MarshalAs(UnmanagedType.IUnknown)] object context, string delimiter, IntPtr sourceContextCookie, uint startingLineNumber, ScriptText flags, [MarshalAs(UnmanagedType.Struct)] out object result, out EXCEPINFO exceptionInfo); } [ComImport] [Guid("C7EF7658-E1EE-480E-97EA-D52CB4D76D17")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IActiveScriptParse64 { void InitNew(); void AddScriptlet( string defaultName, string code, string itemName, string subItemName, string eventName, string delimiter, IntPtr sourceContextCookie, uint startingLineNumber, ScriptText flags, out string name, out EXCEPINFO exceptionInfo); void ParseScriptText( string code, string itemName, [MarshalAs(UnmanagedType.IUnknown)] object context, string delimiter, IntPtr sourceContextCookie, uint startingLineNumber, ScriptText flags, [MarshalAs(UnmanagedType.Struct)] out object result, out EXCEPINFO exceptionInfo); } // Use this helper to deal with the fact that two interfaces with different Guids are required on 32 vs. 64 bit. internal class ActiveScriptParseWrapper { private readonly IActiveScriptParse32 asp32; private readonly IActiveScriptParse64 asp64; internal ActiveScriptParseWrapper(object comObject) { if (IntPtr.Size == 4) { asp32 = (IActiveScriptParse32) comObject; } else { asp64 = (IActiveScriptParse64) comObject; } } internal void InitNew() { if (asp32 != null) { asp32.InitNew(); } else { asp64.InitNew(); } } internal void AddScriptlet( string defaultName, string code, string itemName, string subItemName, string eventName, string delimiter, IntPtr sourceContextCookie, uint startingLineNumber, ScriptText flags, out string name, out EXCEPINFO exceptionInfo) { if (asp32 != null) { asp32.AddScriptlet(defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startingLineNumber, flags, out name, out exceptionInfo); } else { asp64.AddScriptlet(defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startingLineNumber, flags, out name, out exceptionInfo); } } internal void ParseScriptText( string code, string itemName, [MarshalAs(UnmanagedType.IUnknown)] object context, string delimiter, IntPtr sourceContextCookie, uint startingLineNumber, ScriptText flags, [MarshalAs(UnmanagedType.Struct)] out object result, out EXCEPINFO exceptionInfo) { if (asp32 != null) { asp32.ParseScriptText(code, itemName, context, delimiter, sourceContextCookie, startingLineNumber, flags, out result, out exceptionInfo); } else { asp64.ParseScriptText(code, itemName, context, delimiter, sourceContextCookie, startingLineNumber, flags, out result, out exceptionInfo); } } } // // COM Classes // [ComImport] [Guid("f414c260-6ac0-11cf-b6d1-00aa00bbbb58")] internal class JScriptEngine { } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using PolyhydraGames.Extensions.Dice; namespace PolyhydraGames.Extensions { public static class Collections { public static bool ContainsAny<T>(this IEnumerable<T> set1, IEnumerable<T> set2) { if (set2 == null) return false; var set1Array = set1.ToArray(); foreach (var item in set2) { if (set1Array.Contains(item)) return true; } return false; } public static IEnumerable<T> Union<T>(this IEnumerable<T> set1, IEnumerable<T> set2) { var items = set1.ToList(); foreach (var item in set2.Where(item => !items.Contains(item))) items.Add(item); return items; } public static IEnumerable<T> Intersection<T>(this IEnumerable<T> set1, IEnumerable<T> set2) { return set2.Where(set1.Contains).ToList(); } public static IEnumerable<T> SymetricDifference<T>(this IEnumerable<T> set1, IEnumerable<T> set2) { var set1array = set1.ToArray(); var set2array = set2.ToArray(); var union = Union(set1array, set2array); var intersection = Intersection(set1array, set2array); return union.SetComplement(intersection.ToArray()); } public static string[] Add(this string[] array1, string array2) { array1 = array1.Concat(new[] { array2 }).ToArray(); return array1; } public static string[] AddRange(this string[] array1, string[] array2) { array1 = array1.Concat(array2).ToArray(); return array1; } public static int[] MergeArray(this int[] array1, int array2) { array1 = array1.Concat(new[] { array2 }).ToArray(); return array1; } public static T[] MergeArray<T>(this T[] array1, T[] array2) { array1 = array1.Concat(array2).ToArray(); return array1; } public static T[] RangeFrom<T>(this T[] items, T selection) where T : class { if (items.Contains(selection)) { var returnList = new List<T>(); for (var x = items.IndexOf(selection); x < items.Length; x++) returnList.Add(items[x]); return returnList.ToArray(); } return items; } public static T[] RangeUnderIndex<T>(this T[] items, int selection) where T : class { var returnList = new List<T>(); for (var x = 0; x < items.Length && x < selection; x++) returnList.Add(items[x]); return returnList.ToArray(); } public static IEnumerable<T> SetComplement<T>(this IEnumerable<T> universe, IEnumerable<T> setA) { if (universe == null) return new T[0]; return setA == null ? universe : universe.Where(item => !setA.Contains(item)); // var items = from item in universe where (setA.Contains(item) == false) select item; } public static string[] ToSortedArray(this IEnumerable<string> items) { var returnItems = items.ToArray(); Array.Sort(returnItems, StringComparer.CurrentCulture); return returnItems; } public static void AddUnique<T>(this List<T> list, T item) { if (list.Contains(item)) return; list.Add(item); } public static void AddUnique<T>(this ObservableCollection<T> list, T item) { if (list.Contains(item)) return; list.Add(item); } public static void AddUnique<TKey, T>(this Dictionary<TKey, T> list, TKey key, T item) { if (list.ContainsKey(key)) list[key] = item; else list.Add(key, item); } public static void AddRangeUnique<T>(this List<T> list, IEnumerable<T> items) { foreach (var item in items) list.AddUnique(item); } public static void AddRange<T>(this ObservableCollection<T> list, IEnumerable<T> items) { foreach (var item in items) list.Add(item); } public static void AddRangeUnique<T>(this ObservableCollection<T> list, IEnumerable<T> items) { foreach (var item in items) list.AddUnique(item); } public static void RemoveAll<T>(this ObservableCollection<T> list, Predicate<T> rule) { (from item in list where rule(item) select item).ForEach(i=>list.Remove(i)); } public static void Update<T, TE>(this Dictionary<T, TE> dict, T key, TE value) { if (dict.ContainsKey(key)) dict[key] = value; else dict.Add(key, value); } public static bool RemoveTry<T>(this List<T> list, T item) { return list.Remove(item); } public static bool RemoveTry<T>(this ObservableCollection<T> list, T item) { return list.Remove(item); } public static bool RemoveTry<T, TE>(this Dictionary<T, TE> list, T item) { return list.Remove(item); } public static void RemoveRangeTry<T>(this List<T> list, IEnumerable<T> items) { foreach (var item in items) list.RemoveTry(item); } public static void RemoveRangeTry<T>(this ObservableCollection<T> list, IEnumerable<T> items) { foreach (var item in items) list.RemoveTry(item); } public static void Replace<T>(this List<T> currentList, T existing, T replacement) { if (currentList.Contains(existing)) currentList.Remove(existing); currentList.Add(replacement); } public static T MaxBy<T, TK>(this IEnumerable<T> source, Func<T, TK> selector) { return source.MaxBy(selector, Comparer<TK>.Default); } public static T MaxBy<T, TK>(this IEnumerable<T> source, Func<T, TK> selector, IComparer<TK> comparer) { if (source == null) throw new ArgumentNullException("source"); if (selector == null) throw new ArgumentNullException("selector"); if (comparer == null) throw new ArgumentNullException("comparer"); using (var sourceIterator = source.GetEnumerator()) { if (!sourceIterator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } var max = sourceIterator.Current; var maxKey = selector(max); while (sourceIterator.MoveNext()) { var candidate = sourceIterator.Current; var candidateProjected = selector(candidate); if (comparer.Compare(candidateProjected, maxKey) <= 0) continue; max = candidate; maxKey = candidateProjected; } return max; } } public static int IndexOf<T>(this T[] items, T selection) where T : class { return Array.IndexOf(items, selection); } public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) { foreach (var item in items.ToArray()) { action(item); } } public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> items ) { var collection = new ObservableCollection<T>(); foreach (var item in items) { collection.Add(item); } return collection; } public static T RandomItem<T>(this IList<T> items) { if (items == null) return default(T); var length = items.Count(); var index = DiceRoll.RollRandom(0, length - 1); return items[index]; } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\GridPathAIController.h:9 namespace UnrealEngine { [ManageType("ManageGridPathAIController")] public partial class ManageGridPathAIController : AGridPathAIController, IManageWrapper { public ManageGridPathAIController(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_UpdateControlRotation(IntPtr self, float deltaTime, bool bUpdatePawn); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_BeginInactiveState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_CleanupPlayerState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_CurrentLevelUnloaded(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_DetachFromPawn(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_EndInactiveState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_FailedToSpawnPawn(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_InitPlayerState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_Pawn(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_PlayerState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnUnPossess(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ResetIgnoreInputFlags(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ResetIgnoreLookInput(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ResetIgnoreMoveInput(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_SetIgnoreLookInput(IntPtr self, bool bNewLookInput); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_SetIgnoreMoveInput(IntPtr self, bool bNewMoveInput); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_StopMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_UpdateNavigationComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ClearCrossLevelReferences(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_Destroyed(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ForceNetRelevant(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ForceNetUpdate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_GatherCurrentMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_K2_DestroyActor(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_LifeSpanExpired(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_MarkComponentsAsPendingKill(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_NotifyActorBeginCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_NotifyActorEndCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_AttachmentReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_Instigator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_Owner(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_ReplicatedMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnRep_ReplicateMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OutsideWorldBounds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostActorCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostNetInit(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostNetReceiveLocationAndRotation(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostNetReceivePhysicState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostNetReceiveRole(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostUnregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PreInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PreRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_RegisterActorTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_RegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ReregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_RerunConstructionScripts(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_Reset(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_RewindForReplay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_SetActorHiddenInGame(IntPtr self, bool bNewHidden); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_SetLifeSpan(IntPtr self, float inLifespan); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_SetReplicateMovement(IntPtr self, bool bInReplicateMovement); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_TearOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_TeleportSucceeded(IntPtr self, bool bIsATest); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_Tick(IntPtr self, float deltaSeconds); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_TornOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_UnregisterAllComponents(IntPtr self, bool bForReregister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__AGridPathAIController_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// Update direction AI is looking based on FocalPoint /// </summary> public override void UpdateControlRotation(float deltaTime, bool bUpdatePawn) => E__Supper__AGridPathAIController_UpdateControlRotation(this, deltaTime, bUpdatePawn); /// <summary> /// State entered when inactive (no possessed pawn, not spectating, etc). /// </summary> protected override void BeginInactiveState() => E__Supper__AGridPathAIController_BeginInactiveState(this); /// <summary> /// Called from Destroyed(). Cleans up PlayerState. /// </summary> public override void CleanupPlayerState() => E__Supper__AGridPathAIController_CleanupPlayerState(this); /// <summary> /// Called when the level this controller is in is unloaded via streaming. /// </summary> public override void CurrentLevelUnloaded() => E__Supper__AGridPathAIController_CurrentLevelUnloaded(this); /// <summary> /// Detach the RootComponent from its parent, but only if bAttachToPawn is true and it was attached to a Pawn. /// </summary> protected override void DetachFromPawn() => E__Supper__AGridPathAIController_DetachFromPawn(this); /// <summary> /// Called when leaving the inactive state /// </summary> protected override void EndInactiveState() => E__Supper__AGridPathAIController_EndInactiveState(this); /// <summary> /// GameMode failed to spawn pawn for me. /// </summary> public override void FailedToSpawnPawn() => E__Supper__AGridPathAIController_FailedToSpawnPawn(this); /// <summary> /// spawns and initializes the PlayerState for this Controller /// </summary> public override void InitPlayerState() => E__Supper__AGridPathAIController_InitPlayerState(this); public override void OnRep_Pawn() => E__Supper__AGridPathAIController_OnRep_Pawn(this); public override void OnRep_PlayerState() => E__Supper__AGridPathAIController_OnRep_PlayerState(this); /// <summary> /// Overridable native function for when this controller unpossesses its pawn. /// </summary> protected override void OnUnPossess() => E__Supper__AGridPathAIController_OnUnPossess(this); /// <summary> /// Reset move and look input ignore flags. /// </summary> public override void ResetIgnoreInputFlags() => E__Supper__AGridPathAIController_ResetIgnoreInputFlags(this); /// <summary> /// Stops ignoring look input by resetting the ignore look input state. /// </summary> public override void ResetIgnoreLookInput() => E__Supper__AGridPathAIController_ResetIgnoreLookInput(this); /// <summary> /// Stops ignoring move input by resetting the ignore move input state. /// </summary> public override void ResetIgnoreMoveInput() => E__Supper__AGridPathAIController_ResetIgnoreMoveInput(this); /// <summary> /// Locks or unlocks look input, consecutive calls stack up and require the same amount of calls to undo, or can all be undone using ResetIgnoreLookInput. /// </summary> /// <param name="bNewLookInput">If true, look input is ignored. If false, input is not ignored.</param> public override void SetIgnoreLookInput(bool bNewLookInput) => E__Supper__AGridPathAIController_SetIgnoreLookInput(this, bNewLookInput); /// <summary> /// Locks or unlocks movement input, consecutive calls stack up and require the same amount of calls to undo, or can all be undone using ResetIgnoreMoveInput. /// </summary> /// <param name="bNewMoveInput">If true, move input is ignored. If false, input is not ignored.</param> public override void SetIgnoreMoveInput(bool bNewMoveInput) => E__Supper__AGridPathAIController_SetIgnoreMoveInput(this, bNewMoveInput); /// <summary> /// Aborts the move the controller is currently performing /// </summary> public override void StopMovement() => E__Supper__AGridPathAIController_StopMovement(this); /// <summary> /// If controller has any navigation-related components then this function /// <para>makes them update their cached data </para> /// DEPRECATED: this functionality has been taken over by PathFollowingComponent /// <para>by observing newly possessed pawns (via OnNewPawn) </para> /// </summary> public override void UpdateNavigationComponents() => E__Supper__AGridPathAIController_UpdateNavigationComponents(this); /// <summary> /// Overridable native event for when play begins for this actor. /// </summary> protected override void BeginPlay() => E__Supper__AGridPathAIController_BeginPlay(this); /// <summary> /// Do anything needed to clear out cross level references; Called from ULevel::PreSave /// </summary> public override void ClearCrossLevelReferences() => E__Supper__AGridPathAIController_ClearCrossLevelReferences(this); /// <summary> /// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending /// </summary> public override void Destroyed() => E__Supper__AGridPathAIController_Destroyed(this); /// <summary> /// Forces this actor to be net relevant if it is not already by default /// </summary> public override void ForceNetRelevant() => E__Supper__AGridPathAIController_ForceNetRelevant(this); /// <summary> /// Force actor to be updated to clients/demo net drivers /// </summary> public override void ForceNetUpdate() => E__Supper__AGridPathAIController_ForceNetUpdate(this); /// <summary> /// Fills ReplicatedMovement property /// </summary> public override void GatherCurrentMovement() => E__Supper__AGridPathAIController_GatherCurrentMovement(this); /// <summary> /// Invalidates anything produced by the last lighting build. /// </summary> public override void InvalidateLightingCacheDetailed(bool bTranslationOnly) => E__Supper__AGridPathAIController_InvalidateLightingCacheDetailed(this, bTranslationOnly); /// <summary> /// Destroy the actor /// </summary> public override void DestroyActor() => E__Supper__AGridPathAIController_K2_DestroyActor(this); /// <summary> /// Called when the lifespan of an actor expires (if he has one). /// </summary> public override void LifeSpanExpired() => E__Supper__AGridPathAIController_LifeSpanExpired(this); /// <summary> /// Called to mark all components as pending kill when the actor is being destroyed /// </summary> public override void MarkComponentsAsPendingKill() => E__Supper__AGridPathAIController_MarkComponentsAsPendingKill(this); /// <summary> /// Event when this actor has the mouse moved over it with the clickable interface. /// </summary> public override void NotifyActorBeginCursorOver() => E__Supper__AGridPathAIController_NotifyActorBeginCursorOver(this); /// <summary> /// Event when this actor has the mouse moved off of it with the clickable interface. /// </summary> public override void NotifyActorEndCursorOver() => E__Supper__AGridPathAIController_NotifyActorEndCursorOver(this); public override void OnRep_AttachmentReplication() => E__Supper__AGridPathAIController_OnRep_AttachmentReplication(this); public override void OnRep_Instigator() => E__Supper__AGridPathAIController_OnRep_Instigator(this); protected override void OnRep_Owner() => E__Supper__AGridPathAIController_OnRep_Owner(this); public override void OnRep_ReplicatedMovement() => E__Supper__AGridPathAIController_OnRep_ReplicatedMovement(this); public override void OnRep_ReplicateMovement() => E__Supper__AGridPathAIController_OnRep_ReplicateMovement(this); /// <summary> /// Called on the client when the replication paused value is changed /// </summary> public override void OnReplicationPausedChanged(bool bIsReplicationPaused) => E__Supper__AGridPathAIController_OnReplicationPausedChanged(this, bIsReplicationPaused); /// <summary> /// Called when the Actor is outside the hard limit on world bounds /// </summary> public override void OutsideWorldBounds() => E__Supper__AGridPathAIController_OutsideWorldBounds(this); /// <summary> /// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay /// <para>For actors with a root component, the location and rotation will have already been set. </para> /// This is called before calling construction scripts, but after native components have been created /// </summary> public override void PostActorCreated() => E__Supper__AGridPathAIController_PostActorCreated(this); /// <summary> /// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay /// </summary> public override void PostInitializeComponents() => E__Supper__AGridPathAIController_PostInitializeComponents(this); /// <summary> /// Always called immediately after spawning and reading in replicated properties /// </summary> public override void PostNetInit() => E__Supper__AGridPathAIController_PostNetInit(this); /// <summary> /// Update location and rotation from ReplicatedMovement. Not called for simulated physics! /// </summary> public override void PostNetReceiveLocationAndRotation() => E__Supper__AGridPathAIController_PostNetReceiveLocationAndRotation(this); /// <summary> /// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity() /// </summary> public override void PostNetReceivePhysicState() => E__Supper__AGridPathAIController_PostNetReceivePhysicState(this); /// <summary> /// Always called immediately after a new Role is received from the remote. /// </summary> public override void PostNetReceiveRole() => E__Supper__AGridPathAIController_PostNetReceiveRole(this); /// <summary> /// Called after all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PostRegisterAllComponents() => E__Supper__AGridPathAIController_PostRegisterAllComponents(this); /// <summary> /// Called after all currently registered components are cleared /// </summary> public override void PostUnregisterAllComponents() => E__Supper__AGridPathAIController_PostUnregisterAllComponents(this); /// <summary> /// Called right before components are initialized, only called during gameplay /// </summary> public override void PreInitializeComponents() => E__Supper__AGridPathAIController_PreInitializeComponents(this); /// <summary> /// Called before all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PreRegisterAllComponents() => E__Supper__AGridPathAIController_PreRegisterAllComponents(this); /// <summary> /// Calls PrestreamTextures() for all the actor's meshcomponents. /// </summary> /// <param name="seconds">Number of seconds to force all mip-levels to be resident</param> /// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param> /// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param> public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups) => E__Supper__AGridPathAIController_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups); /// <summary> /// Virtual call chain to register all tick functions for the actor class hierarchy /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterActorTickFunctions(bool bRegister) => E__Supper__AGridPathAIController_RegisterActorTickFunctions(this, bRegister); /// <summary> /// Ensure that all the components in the Components array are registered /// </summary> public override void RegisterAllComponents() => E__Supper__AGridPathAIController_RegisterAllComponents(this); /// <summary> /// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty. /// </summary> public override void ReregisterAllComponents() => E__Supper__AGridPathAIController_ReregisterAllComponents(this); /// <summary> /// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location. /// </summary> public override void RerunConstructionScripts() => E__Supper__AGridPathAIController_RerunConstructionScripts(this); /// <summary> /// Reset actor to initial state - used when restarting level without reloading. /// </summary> public override void Reset() => E__Supper__AGridPathAIController_Reset(this); /// <summary> /// Called on the actor before checkpoint data is applied during a replay. /// <para>Only called if bReplayRewindable is set. </para> /// </summary> public override void RewindForReplay() => E__Supper__AGridPathAIController_RewindForReplay(this); /// <summary> /// Sets the actor to be hidden in the game /// </summary> /// <param name="bNewHidden">Whether or not to hide the actor and all its components</param> public override void SetActorHiddenInGame(bool bNewHidden) => E__Supper__AGridPathAIController_SetActorHiddenInGame(this, bNewHidden); /// <summary> /// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed. /// </summary> public override void SetLifeSpan(float inLifespan) => E__Supper__AGridPathAIController_SetLifeSpan(this, inLifespan); /// <summary> /// Set whether this actor's movement replicates to network clients. /// </summary> /// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param> public override void SetReplicateMovement(bool bInReplicateMovement) => E__Supper__AGridPathAIController_SetReplicateMovement(this, bInReplicateMovement); /// <summary> /// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true. /// </summary> public override void TearOff() => E__Supper__AGridPathAIController_TearOff(this); /// <summary> /// Called from TeleportTo() when teleport succeeds /// </summary> public override void TeleportSucceeded(bool bIsATest) => E__Supper__AGridPathAIController_TeleportSucceeded(this, bIsATest); /// <summary> /// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame. /// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para> /// </summary> /// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param> public override void Tick(float deltaSeconds) => E__Supper__AGridPathAIController_Tick(this, deltaSeconds); /// <summary> /// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients. /// <para>@see bTearOff </para> /// </summary> public override void TornOff() => E__Supper__AGridPathAIController_TornOff(this); /// <summary> /// Unregister all currently registered components /// </summary> /// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param> public override void UnregisterAllComponents(bool bForReregister) => E__Supper__AGridPathAIController_UnregisterAllComponents(this, bForReregister); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__AGridPathAIController_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__AGridPathAIController_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__AGridPathAIController_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__AGridPathAIController_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__AGridPathAIController_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__AGridPathAIController_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__AGridPathAIController_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__AGridPathAIController_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__AGridPathAIController_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__AGridPathAIController_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__AGridPathAIController_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__AGridPathAIController_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__AGridPathAIController_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__AGridPathAIController_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__AGridPathAIController_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageGridPathAIController self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageGridPathAIController(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageGridPathAIController>(PtrDesc); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly ITextManagerAdapter _textManagerAdapter; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; _textManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get { return _textManagerAdapter; } } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. If the editor is still alive, dispose it. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = ((VisualStudioWorkspaceImpl)this.State.Workspace).DeferredState?.ProjectTracker.GetProject(_incomingProjectId); if (project == null) { return false; } var hostDocument = project.GetCurrentDocumentFromPath(_incomingFilePath); if (hostDocument == null) { return false; } _documentId = hostDocument.Id; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; documentId = _documentId; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're creating an element with the same node key as an element that's already in the table, just remove // the old element. The old element will continue to function but the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) { _codeElementTable.Remove(nodeKey); } internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = Formatter.FormatAsync(result, Formatter.Annotation).WaitAndGetResult_CodeModel(CancellationToken.None); formatted = Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).WaitAndGetResult_CodeModel(CancellationToken.None); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out var documentId) && _previousDocument != null) { document = _previousDocument; } else { document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument() .GetSyntaxTreeAsync(CancellationToken.None) .WaitAndGetResult_CodeModel(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument() .GetSyntaxRootAsync(CancellationToken.None) .WaitAndGetResult_CodeModel(CancellationToken.None); } internal SemanticModel GetSemanticModel() { return GetDocument() .GetSemanticModelAsync(CancellationToken.None) .WaitAndGetResult_CodeModel(CancellationToken.None); } internal Compilation GetCompilation() { return GetDocument().Project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_CodeModel(CancellationToken.None); } internal ProjectId GetProjectId() { return GetDocumentId().ProjectId; } internal AbstractProject GetAbstractProject() { return ((VisualStudioWorkspaceImpl)Workspace).DeferredState.ProjectTracker.GetProject(GetProjectId()); } internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); } internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) { throw Exceptions.ThrowEFail(); } public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) { throw Exceptions.ThrowEFail(); } public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextAsync(CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position); var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent != null ? parent.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)) : null; if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths = elementAndPaths ?? new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) { throw new NotImplementedException(); } public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() { FireEvents(); } EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() { return CodeElements; } internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, default(CancellationToken)); } } } } }
/* * 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.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Web; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; using OSDArray=OpenMetaverse.StructuredData.OSDArray; using OSDMap=OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.CoreModules.InterGrid { public struct OGPState { public string first_name; public string last_name; public UUID agent_id; public UUID local_agent_id; public UUID region_id; public uint circuit_code; public UUID secure_session_id; public UUID session_id; public bool agent_access; public string sim_access; public uint god_level; public bool god_overide; public bool identified; public bool transacted; public bool age_verified; public bool allow_redirect; public int limited_to_estate; public string inventory_host; public bool src_can_see_mainland; public int src_estate_id; public int src_version; public int src_parent_estate_id; public bool visible_to_parent; public string teleported_into_region; } public class OpenGridProtocolModule : IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_scene = new List<Scene>(); private Dictionary<string, AgentCircuitData> CapsLoginID = new Dictionary<string, AgentCircuitData>(); private Dictionary<UUID, OGPState> m_OGPState = new Dictionary<UUID, OGPState>(); private Dictionary<string, string> m_loginToRegionState = new Dictionary<string, string>(); private string LastNameSuffix = "_EXTERNAL"; private string FirstNamePrefix = ""; private string httpsCN = ""; private bool httpSSL = false; private uint httpsslport = 0; // private bool GridMode = false; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { bool enabled = false; IConfig cfg = null; IConfig httpcfg = null; // IConfig startupcfg = null; try { cfg = config.Configs["OpenGridProtocol"]; } catch (NullReferenceException) { enabled = false; } try { httpcfg = config.Configs["Network"]; } catch (NullReferenceException) { } // try // { // startupcfg = config.Configs["Startup"]; // } // catch (NullReferenceException) // { // // } // if (startupcfg != null) // { // GridMode = enabled = startupcfg.GetBoolean("gridmode", false); // } if (cfg != null) { enabled = cfg.GetBoolean("ogp_enabled", false); LastNameSuffix = cfg.GetString("ogp_lastname_suffix", "_EXTERNAL"); FirstNamePrefix = cfg.GetString("ogp_firstname_prefix", ""); if (enabled) { m_log.Warn("[OGP]: Open Grid Protocol is on, Listening for Clients on /agent/"); lock (m_scene) { if (m_scene.Count == 0) { MainServer.Instance.AddLLSDHandler("/agent/", ProcessAgentDomainMessage); MainServer.Instance.AddLLSDHandler("/", ProcessRegionDomainSeed); try { ServicePointManager.ServerCertificateValidationCallback += customXertificateValidation; } catch (NotImplementedException) { try { #pragma warning disable 0612, 0618 // Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this! ServicePointManager.CertificatePolicy = new MonoCert(); #pragma warning restore 0612, 0618 } catch (Exception) { m_log.Error("[OGP]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions."); } } } // can't pick the region 'agent' because it would conflict with our agent domain handler // a zero length region name would conflict with are base region seed cap if (!SceneListDuplicateCheck(scene.RegionInfo.RegionName) && scene.RegionInfo.RegionName.ToLower() != "agent" && scene.RegionInfo.RegionName.Length > 0) { MainServer.Instance.AddLLSDHandler( "/" + HttpUtility.UrlPathEncode(scene.RegionInfo.RegionName.ToLower()), ProcessRegionDomainSeed); } if (!m_scene.Contains(scene)) m_scene.Add(scene); } } } lock (m_scene) { if (m_scene.Count == 1) { if (httpcfg != null) { httpSSL = httpcfg.GetBoolean("http_listener_ssl", false); httpsCN = httpcfg.GetString("http_listener_cn", scene.RegionInfo.ExternalHostName); if (httpsCN.Length == 0) httpsCN = scene.RegionInfo.ExternalHostName; httpsslport = (uint)httpcfg.GetInt("http_listener_sslport",((int)scene.RegionInfo.HttpPort + 1)); } } } } public void PostInitialise() { } public void Close() { //scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; } public string Name { get { return "OpenGridProtocolModule"; } } public bool IsSharedModule { get { return true; } } #endregion public OSD ProcessRegionDomainSeed(string path, OSD request, string endpoint) { string[] pathSegments = path.Split('/'); if (pathSegments.Length <= 1) { return GenerateNoHandlerMessage(); } return GenerateRezAvatarRequestMessage(pathSegments[1]); //m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}", // path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]); //return new OSDMap(); } public OSD ProcessAgentDomainMessage(string path, OSD request, string endpoint) { // /agent/* string[] pathSegments = path.Split('/'); if (pathSegments.Length <= 1) { return GenerateNoHandlerMessage(); } if (pathSegments[0].Length == 0 && pathSegments[1].Length == 0) { return GenerateRezAvatarRequestMessage(""); } m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}", path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]); switch (pathSegments[pathSegments.Length - 1]) { case "rez_avatar": return RezAvatarMethod(path, request); //break; case "derez_avatar": return DerezAvatarMethod(path, request); //break; } if (path.Length < 2) { return GenerateNoHandlerMessage(); } switch (pathSegments[pathSegments.Length - 2] + "/" + pathSegments[pathSegments.Length - 1]) { case "rez_avatar/rez": return RezAvatarMethod(path, request); //break; case "rez_avatar/request": return RequestRezAvatarMethod(path, request); case "rez_avatar/place": return RequestRezAvatarMethod(path, request); case "rez_avatar/derez": return DerezAvatarMethod(path, request); //break; default: return GenerateNoHandlerMessage(); } //return null; } private OSD GenerateRezAvatarRequestMessage(string regionname) { Scene region = null; bool usedroot = false; if (regionname.Length == 0) { region = GetRootScene(); usedroot = true; } else { region = GetScene(HttpUtility.UrlDecode(regionname).ToLower()); } // this shouldn't happen since we don't listen for a region that is down.. but // it might if the region was taken down or is in the middle of restarting if (region == null) { region = GetRootScene(); usedroot = true; } UUID statekeeper = UUID.Random(); RegionInfo reg = region.RegionInfo; OSDMap responseMap = new OSDMap(); string rezHttpProtocol = "http://"; //string regionCapsHttpProtocol = "http://"; string httpaddr = reg.ExternalHostName; string urlport = reg.HttpPort.ToString(); string requestpath = "/agent/" + statekeeper + "/rez_avatar/request"; if (!usedroot) { lock (m_loginToRegionState) { if (!m_loginToRegionState.ContainsKey(requestpath)) { m_loginToRegionState.Add(requestpath, region.RegionInfo.RegionName.ToLower()); } } } if (httpSSL) { rezHttpProtocol = "https://"; //regionCapsHttpProtocol = "https://"; urlport = httpsslport.ToString(); if (httpsCN.Length > 0) httpaddr = httpsCN; } responseMap["connect"] = OSD.FromBoolean(true); OSDMap capabilitiesMap = new OSDMap(); capabilitiesMap["rez_avatar/request"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + requestpath); responseMap["capabilities"] = capabilitiesMap; return responseMap; } // Using OpenSim.Framework.Capabilities.Caps here one time.. // so the long name is probably better then a using statement public void OnRegisterCaps(UUID agentID, Caps caps) { /* If we ever want to register our own caps here.... * string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("CAPNAME", new RestStreamHandler("POST", capsBase + CAPSPOSTFIX!, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return METHODHANDLER(request, path, param, agentID, caps); })); * */ } public OSD RequestRezAvatarMethod(string path, OSD request) { //m_log.Debug("[REQUESTREZAVATAR]: " + request.ToString()); OSDMap requestMap = (OSDMap)request; Scene homeScene = null; lock (m_loginToRegionState) { if (m_loginToRegionState.ContainsKey(path)) { homeScene = GetScene(m_loginToRegionState[path]); m_loginToRegionState.Remove(path); if (homeScene == null) homeScene = GetRootScene(); } else { homeScene = GetRootScene(); } } // Homescene is still null, we must have no regions that are up if (homeScene == null) return GenerateNoHandlerMessage(); RegionInfo reg = homeScene.RegionInfo; ulong regionhandle = GetOSCompatibleRegionHandle(reg); //string RegionURI = reg.ServerURI; //int RegionPort = (int)reg.HttpPort; UUID RemoteAgentID = requestMap["agent_id"].AsUUID(); // will be used in the future. The client always connects with the aditi agentid currently UUID LocalAgentID = RemoteAgentID; string FirstName = requestMap["first_name"].AsString(); string LastName = requestMap["last_name"].AsString(); FirstName = FirstNamePrefix + FirstName; LastName = LastName + LastNameSuffix; OGPState userState = GetOGPState(LocalAgentID); userState.first_name = requestMap["first_name"].AsString(); userState.last_name = requestMap["last_name"].AsString(); userState.age_verified = requestMap["age_verified"].AsBoolean(); userState.transacted = requestMap["transacted"].AsBoolean(); userState.agent_access = requestMap["agent_access"].AsBoolean(); userState.allow_redirect = requestMap["allow_redirect"].AsBoolean(); userState.identified = requestMap["identified"].AsBoolean(); userState.god_level = (uint)requestMap["god_level"].AsInteger(); userState.sim_access = requestMap["sim_access"].AsString(); userState.agent_id = RemoteAgentID; userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger(); userState.src_can_see_mainland = requestMap["src_can_see_mainland"].AsBoolean(); userState.src_estate_id = requestMap["src_estate_id"].AsInteger(); userState.local_agent_id = LocalAgentID; userState.teleported_into_region = reg.RegionName.ToLower(); UpdateOGPState(LocalAgentID, userState); OSDMap responseMap = new OSDMap(); if (RemoteAgentID == UUID.Zero) { responseMap["connect"] = OSD.FromBoolean(false); responseMap["message"] = OSD.FromString("No agent ID was specified in rez_avatar/request"); m_log.Error("[OGP]: rez_avatar/request failed because no avatar UUID was provided in the request body"); return responseMap; } responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString()); responseMap["connect"] = OSD.FromBoolean(true); responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port); responseMap["region_x"] = OSD.FromInteger(reg.RegionLocX * (uint)Constants.RegionSize); // LLX responseMap["region_y"] = OSD.FromInteger(reg.RegionLocY * (uint)Constants.RegionSize); // LLY responseMap["region_id"] = OSD.FromUUID(reg.originRegionID); if (reg.RegionSettings.Maturity == 1) { responseMap["sim_access"] = OSD.FromString("Mature"); } else if (reg.RegionSettings.Maturity == 2) { responseMap["sim_access"] = OSD.FromString("Adult"); } else { responseMap["sim_access"] = OSD.FromString("PG"); } // Generate a dummy agent for the user so we can get back a CAPS path AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = LocalAgentID; agentData.BaseFolder = UUID.Zero; agentData.CapsPath = CapsUtil.GetRandomCapsObjectPath(); agentData.child = false; agentData.circuitcode = (uint)(Util.RandomClass.Next()); agentData.firstname = FirstName; agentData.lastname = LastName; agentData.SecureSessionID = UUID.Random(); agentData.SessionID = UUID.Random(); agentData.startpos = new Vector3(128f, 128f, 100f); // Pre-Fill our region cache with information on the agent. UserAgentData useragent = new UserAgentData(); useragent.AgentIP = "unknown"; useragent.AgentOnline = true; useragent.AgentPort = (uint)0; useragent.Handle = regionhandle; useragent.InitialRegion = reg.originRegionID; useragent.LoginTime = Util.UnixTimeSinceEpoch(); useragent.LogoutTime = 0; useragent.Position = agentData.startpos; useragent.Region = reg.originRegionID; useragent.SecureSessionID = agentData.SecureSessionID; useragent.SessionID = agentData.SessionID; UserProfileData userProfile = new UserProfileData(); userProfile.AboutText = "OGP User"; userProfile.CanDoMask = (uint)0; userProfile.Created = Util.UnixTimeSinceEpoch(); userProfile.CurrentAgent = useragent; userProfile.CustomType = "OGP"; userProfile.FirstLifeAboutText = "I'm testing OpenGrid Protocol"; userProfile.FirstLifeImage = UUID.Zero; userProfile.FirstName = agentData.firstname; userProfile.GodLevel = 0; userProfile.HomeLocation = agentData.startpos; userProfile.HomeLocationX = agentData.startpos.X; userProfile.HomeLocationY = agentData.startpos.Y; userProfile.HomeLocationZ = agentData.startpos.Z; userProfile.HomeLookAt = Vector3.Zero; userProfile.HomeLookAtX = userProfile.HomeLookAt.X; userProfile.HomeLookAtY = userProfile.HomeLookAt.Y; userProfile.HomeLookAtZ = userProfile.HomeLookAt.Z; userProfile.HomeRegion = reg.RegionHandle; userProfile.HomeRegionID = reg.originRegionID; userProfile.HomeRegionX = reg.RegionLocX; userProfile.HomeRegionY = reg.RegionLocY; userProfile.ID = agentData.AgentID; userProfile.Image = UUID.Zero; userProfile.LastLogin = Util.UnixTimeSinceEpoch(); userProfile.Partner = UUID.Zero; userProfile.PasswordHash = "$1$"; userProfile.PasswordSalt = ""; userProfile.SurName = agentData.lastname; //userProfile.UserAssetURI = homeScene.CommsManager.NetworkServersInfo.AssetURL; userProfile.UserFlags = 0; //userProfile.UserInventoryURI = homeScene.CommsManager.NetworkServersInfo.InventoryURL; userProfile.WantDoMask = 0; userProfile.WebLoginKey = UUID.Random(); // !!! REFACTORING PROBLEM. This needs to be changed for 0.7 // //// Do caps registration //// get seed capagentData.firstname = FirstName;agentData.lastname = LastName; //if (homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID) == null && !GridMode) //{ // homeScene.CommsManager.UserAdminService.AddUser( // agentData.firstname, agentData.lastname, CreateRandomStr(7), "", // homeScene.RegionInfo.RegionLocX, homeScene.RegionInfo.RegionLocY, agentData.AgentID); // UserProfileData userProfile2 = homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID); // if (userProfile2 != null) // { // userProfile = userProfile2; // userProfile.AboutText = "OGP USER"; // userProfile.FirstLifeAboutText = "OGP USER"; // homeScene.CommsManager.UserService.UpdateUserProfile(userProfile); // } //} //// Stick our data in the cache so the region will know something about us //homeScene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile); // Call 'new user' event handler string reason; if (!homeScene.NewUserConnection(agentData, (uint)TeleportFlags.ViaLogin, out reason)) { responseMap["connect"] = OSD.FromBoolean(false); responseMap["message"] = OSD.FromString(String.Format("Connection refused: {0}", reason)); m_log.ErrorFormat("[OGP]: rez_avatar/request failed: {0}", reason); return responseMap; } //string raCap = string.Empty; UUID AvatarRezCapUUID = LocalAgentID; string rezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/rez"; string derezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/derez"; // Get a reference to the user's cap so we can pull out the Caps Object Path Caps userCap = homeScene.CapsModule.GetCapsHandlerForUser(agentData.AgentID); string rezHttpProtocol = "http://"; string regionCapsHttpProtocol = "http://"; string httpaddr = reg.ExternalHostName; string urlport = reg.HttpPort.ToString(); if (httpSSL) { rezHttpProtocol = "https://"; regionCapsHttpProtocol = "https://"; urlport = httpsslport.ToString(); if (httpsCN.Length > 0) httpaddr = httpsCN; } // DEPRECATED responseMap["seed_capability"] = OSD.FromString( regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + "/" + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath)); // REPLACEMENT responseMap["region_seed_capability"] = OSD.FromString( regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + "/" + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath)); responseMap["rez_avatar"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath); responseMap["rez_avatar/rez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath); responseMap["rez_avatar/derez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + derezAvatarPath); // Add the user to the list of CAPS that are outstanding. // well allow the caps hosts in this dictionary lock (CapsLoginID) { if (CapsLoginID.ContainsKey(rezAvatarPath)) { CapsLoginID[rezAvatarPath] = agentData; // This is a joke, if you didn't notice... It's so unlikely to happen, that I'll print this message if it does occur! m_log.Error("[OGP]: Holy anomoly batman! Caps path already existed! All the UUID Duplication worries were founded!"); } else { CapsLoginID.Add(rezAvatarPath, agentData); } } //m_log.Debug("Response:" + responseMap.ToString()); return responseMap; } public OSD RezAvatarMethod(string path, OSD request) { m_log.WarnFormat("[REZAVATAR]: {0}", request.ToString()); OSDMap responseMap = new OSDMap(); AgentCircuitData userData = null; // Only people we've issued a cap can go further if (TryGetAgentCircuitData(path,out userData)) { OSDMap requestMap = (OSDMap)request; // take these values to start. There's a few more UUID SecureSessionID=requestMap["secure_session_id"].AsUUID(); UUID SessionID = requestMap["session_id"].AsUUID(); int circuitcode = requestMap["circuit_code"].AsInteger(); OSDArray Parameter = new OSDArray(); if (requestMap.ContainsKey("parameter")) { Parameter = (OSDArray)requestMap["parameter"]; } //int version = 1; int estateID = 1; int parentEstateID = 1; UUID regionID = UUID.Zero; bool visibleToParent = true; for (int i = 0; i < Parameter.Count; i++) { OSDMap item = (OSDMap)Parameter[i]; // if (item.ContainsKey("version")) // { // version = item["version"].AsInteger(); // } if (item.ContainsKey("estate_id")) { estateID = item["estate_id"].AsInteger(); } if (item.ContainsKey("parent_estate_id")) { parentEstateID = item["parent_estate_id"].AsInteger(); } if (item.ContainsKey("region_id")) { regionID = item["region_id"].AsUUID(); } if (item.ContainsKey("visible_to_parent")) { visibleToParent = item["visible_to_parent"].AsBoolean(); } } //Update our Circuit data with the real values userData.SecureSessionID = SecureSessionID; userData.SessionID = SessionID; OGPState userState = GetOGPState(userData.AgentID); // Locate a home scene suitable for the user. Scene homeScene = null; homeScene = GetScene(userState.teleported_into_region); if (homeScene == null) homeScene = GetRootScene(); if (homeScene != null) { // Get a referenceokay - to their Cap object so we can pull out the capobjectroot Caps userCap = homeScene.CapsModule.GetCapsHandlerForUser(userData.AgentID); //Update the circuit data in the region so this user is authorized homeScene.UpdateCircuitData(userData); homeScene.ChangeCircuitCode(userData.circuitcode,(uint)circuitcode); // Load state // Keep state changes userState.first_name = requestMap["first_name"].AsString(); userState.secure_session_id = requestMap["secure_session_id"].AsUUID(); userState.age_verified = requestMap["age_verified"].AsBoolean(); userState.region_id = homeScene.RegionInfo.originRegionID; // replace 0000000 with our regionid userState.transacted = requestMap["transacted"].AsBoolean(); userState.agent_access = requestMap["agent_access"].AsBoolean(); userState.inventory_host = requestMap["inventory_host"].AsString(); userState.identified = requestMap["identified"].AsBoolean(); userState.session_id = requestMap["session_id"].AsUUID(); userState.god_level = (uint)requestMap["god_level"].AsInteger(); userState.last_name = requestMap["last_name"].AsString(); userState.god_overide = requestMap["god_override"].AsBoolean(); userState.circuit_code = (uint)requestMap["circuit_code"].AsInteger(); userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger(); userState.src_estate_id = estateID; userState.region_id = regionID; userState.src_parent_estate_id = parentEstateID; userState.visible_to_parent = visibleToParent; // Save state changes UpdateOGPState(userData.AgentID, userState); // Get the region information for the home region. RegionInfo reg = homeScene.RegionInfo; // Dummy positional and look at info.. we don't have it. OSDArray PositionArray = new OSDArray(); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(40)); OSDArray LookAtArray = new OSDArray(); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); // Our region's X and Y position in OpenSimulator space. uint fooX = reg.RegionLocX; uint fooY = reg.RegionLocY; m_log.InfoFormat("[OGP]: region x({0}) region y({1})", fooX, fooY); m_log.InfoFormat("[OGP]: region http {0} {1}", reg.ServerURI, reg.HttpPort); m_log.InfoFormat("[OGO]: region UUID {0} ", reg.RegionID); // Convert the X and Y position to LL space responseMap["region_x"] = OSD.FromInteger(fooX * (uint)Constants.RegionSize); // convert it to LL X responseMap["region_y"] = OSD.FromInteger(fooY * (uint)Constants.RegionSize); // convert it to LL Y // Give em a new seed capability responseMap["seed_capability"] = OSD.FromString("http://" + reg.ExternalHostName + ":" + reg.HttpPort + "/CAPS/" + userCap.CapsObjectPath + "0000/"); responseMap["region"] = OSD.FromUUID(reg.originRegionID); responseMap["look_at"] = LookAtArray; responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port); responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName);// + ":" + reg.InternalEndPoint.Port.ToString()); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString()); responseMap["session_id"] = OSD.FromUUID(SessionID); responseMap["secure_session_id"] = OSD.FromUUID(SecureSessionID); responseMap["circuit_code"] = OSD.FromInteger(circuitcode); responseMap["position"] = PositionArray; responseMap["region_id"] = OSD.FromUUID(reg.originRegionID); responseMap["sim_access"] = OSD.FromString("Mature"); responseMap["connect"] = OSD.FromBoolean(true); m_log.InfoFormat("[OGP]: host: {0}, IP {1}", responseMap["sim_host"].ToString(), responseMap["sim_ip"].ToString()); } } return responseMap; } public OSD DerezAvatarMethod(string path, OSD request) { m_log.ErrorFormat("DerezPath: {0}, Request: {1}", path, request.ToString()); //LLSD llsdResponse = null; OSDMap responseMap = new OSDMap(); string[] PathArray = path.Split('/'); m_log.InfoFormat("[OGP]: prefix {0}, uuid {1}, suffix {2}", PathArray[1], PathArray[2], PathArray[3]); string uuidString = PathArray[2]; m_log.InfoFormat("[OGP]: Request to Derez avatar with UUID {0}", uuidString); UUID userUUID = UUID.Zero; if (UUID.TryParse(uuidString, out userUUID)) { UUID RemoteID = (UUID)uuidString; UUID LocalID = RemoteID; // FIXME: TODO: Routine to map RemoteUUIDs to LocalUUIds // would be done already.. but the client connects with the Aditi UUID // regardless over the UDP stack OGPState userState = GetOGPState(LocalID); if (userState.agent_id != UUID.Zero) { //OSDMap outboundRequestMap = new OSDMap(); OSDMap inboundRequestMap = (OSDMap)request; string rezAvatarString = inboundRequestMap["rez_avatar"].AsString(); if (rezAvatarString.Length == 0) { rezAvatarString = inboundRequestMap["rez_avatar/rez"].AsString(); } OSDArray LookAtArray = new OSDArray(); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); OSDArray PositionArray = new OSDArray(); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(40)); OSDArray lookArray = new OSDArray(); lookArray.Add(OSD.FromInteger(128)); lookArray.Add(OSD.FromInteger(128)); lookArray.Add(OSD.FromInteger(40)); responseMap["connect"] = OSD.FromBoolean(true);// it's okay to give this user up responseMap["look_at"] = LookAtArray; m_log.WarnFormat("[OGP]: Invoking rez_avatar on host:{0} for avatar: {1} {2}", rezAvatarString, userState.first_name, userState.last_name); OSDMap rezResponseMap = invokeRezAvatarCap(responseMap, rezAvatarString,userState); // If invoking it returned an error, parse and end if (rezResponseMap.ContainsKey("connect")) { if (rezResponseMap["connect"].AsBoolean() == false) { return responseMap; } } string rezRespSeedCap = ""; // DEPRECATED if (rezResponseMap.ContainsKey("seed_capability")) rezRespSeedCap = rezResponseMap["seed_capability"].AsString(); // REPLACEMENT if (rezResponseMap.ContainsKey("region_seed_capability")) rezRespSeedCap = rezResponseMap["region_seed_capability"].AsString(); // REPLACEMENT if (rezResponseMap.ContainsKey("rez_avatar/rez")) rezRespSeedCap = rezResponseMap["rez_avatar/rez"].AsString(); // DEPRECATED string rezRespSim_ip = rezResponseMap["sim_ip"].AsString(); string rezRespSim_host = rezResponseMap["sim_host"].AsString(); int rrPort = rezResponseMap["sim_port"].AsInteger(); int rrX = rezResponseMap["region_x"].AsInteger(); int rrY = rezResponseMap["region_y"].AsInteger(); m_log.ErrorFormat("X:{0}, Y:{1}", rrX, rrY); UUID rrRID = rezResponseMap["region_id"].AsUUID(); OSDArray RezResponsePositionArray = null; string rrAccess = rezResponseMap["sim_access"].AsString(); if (rezResponseMap.ContainsKey("position")) { RezResponsePositionArray = (OSDArray)rezResponseMap["position"]; } // DEPRECATED responseMap["seed_capability"] = OSD.FromString(rezRespSeedCap); // REPLACEMENT r3 responseMap["region_seed_capability"] = OSD.FromString(rezRespSeedCap); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(rezRespSim_ip).ToString()); responseMap["sim_host"] = OSD.FromString(rezRespSim_host); responseMap["sim_port"] = OSD.FromInteger(rrPort); responseMap["region_x"] = OSD.FromInteger(rrX); responseMap["region_y"] = OSD.FromInteger(rrY); responseMap["region_id"] = OSD.FromUUID(rrRID); responseMap["sim_access"] = OSD.FromString(rrAccess); if (RezResponsePositionArray != null) { responseMap["position"] = RezResponsePositionArray; } responseMap["look_at"] = lookArray; responseMap["connect"] = OSD.FromBoolean(true); ShutdownConnection(LocalID,this); // PLEASE STOP CHANGING THIS TO an M_LOG, M_LOG DOESN'T WORK ON MULTILINE .TOSTRINGS Console.WriteLine("RESPONSEDEREZ: " + responseMap.ToString()); return responseMap; } else { return GenerateNoStateMessage(LocalID); } } else { return GenerateNoHandlerMessage(); } //return responseMap; } private OSDMap invokeRezAvatarCap(OSDMap responseMap, string CapAddress, OGPState userState) { Scene reg = GetRootScene(); WebRequest DeRezRequest = WebRequest.Create(CapAddress); DeRezRequest.Method = "POST"; DeRezRequest.ContentType = "application/xml+llsd"; OSDMap RAMap = new OSDMap(); OSDMap AgentParms = new OSDMap(); OSDMap RegionParms = new OSDMap(); OSDArray Parameter = new OSDArray(2); OSDMap version = new OSDMap(); version["version"] = OSD.FromInteger(userState.src_version); Parameter.Add(version); OSDMap SrcData = new OSDMap(); SrcData["estate_id"] = OSD.FromInteger(reg.RegionInfo.EstateSettings.EstateID); SrcData["parent_estate_id"] = OSD.FromInteger((reg.RegionInfo.EstateSettings.ParentEstateID == 100 ? 1 : reg.RegionInfo.EstateSettings.ParentEstateID)); SrcData["region_id"] = OSD.FromUUID(reg.RegionInfo.originRegionID); SrcData["visible_to_parent"] = OSD.FromBoolean(userState.visible_to_parent); Parameter.Add(SrcData); AgentParms["first_name"] = OSD.FromString(userState.first_name); AgentParms["last_name"] = OSD.FromString(userState.last_name); AgentParms["agent_id"] = OSD.FromUUID(userState.agent_id); RegionParms["region_id"] = OSD.FromUUID(userState.region_id); AgentParms["circuit_code"] = OSD.FromInteger(userState.circuit_code); AgentParms["secure_session_id"] = OSD.FromUUID(userState.secure_session_id); AgentParms["session_id"] = OSD.FromUUID(userState.session_id); AgentParms["agent_access"] = OSD.FromBoolean(userState.agent_access); AgentParms["god_level"] = OSD.FromInteger(userState.god_level); AgentParms["god_overide"] = OSD.FromBoolean(userState.god_overide); AgentParms["identified"] = OSD.FromBoolean(userState.identified); AgentParms["transacted"] = OSD.FromBoolean(userState.transacted); AgentParms["age_verified"] = OSD.FromBoolean(userState.age_verified); AgentParms["limited_to_estate"] = OSD.FromInteger(userState.limited_to_estate); AgentParms["inventory_host"] = OSD.FromString(userState.inventory_host); // version 1 RAMap = AgentParms; // Planned for version 2 // RAMap["agent_params"] = AgentParms; RAMap["region_params"] = RegionParms; RAMap["parameter"] = Parameter; string RAMapString = RAMap.ToString(); m_log.InfoFormat("[OGP] RAMap string {0}", RAMapString); OSD LLSDofRAMap = RAMap; // RENAME if this works m_log.InfoFormat("[OGP]: LLSD of map as string was {0}", LLSDofRAMap.ToString()); //m_log.InfoFormat("[OGP]: LLSD+XML: {0}", LLSDParser.SerializeXmlString(LLSDofRAMap)); byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); //string bufferDump = System.Text.Encoding.ASCII.GetString(buffer); //m_log.InfoFormat("[OGP]: buffer form is {0}",bufferDump); //m_log.InfoFormat("[OGP]: LLSD of map was {0}",buffer.Length); Stream os = null; try { // send the Post DeRezRequest.ContentLength = buffer.Length; //Count bytes to send os = DeRezRequest.GetRequestStream(); os.Write(buffer, 0, buffer.Length); //Send it os.Close(); m_log.InfoFormat("[OGP]: Derez Avatar Posted Rez Avatar request to remote sim {0}", CapAddress); } catch (WebException ex) { m_log.InfoFormat("[OGP] Bad send on de_rez_avatar {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } m_log.Info("[OGP] waiting for a reply after rez avatar send"); string rez_avatar_reply = null; { // get the response try { WebResponse webResponse = DeRezRequest.GetResponse(); if (webResponse == null) { m_log.Info("[OGP:] Null reply on rez_avatar post"); } StreamReader sr = new StreamReader(webResponse.GetResponseStream()); rez_avatar_reply = sr.ReadToEnd().Trim(); m_log.InfoFormat("[OGP]: rez_avatar reply was {0} ", rez_avatar_reply); } catch (WebException ex) { m_log.InfoFormat("[OGP]: exception on read after send of rez avatar {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } OSD rezResponse = null; try { rezResponse = OSDParser.DeserializeLLSDXml(rez_avatar_reply); responseMap = (OSDMap)rezResponse; } catch (Exception ex) { m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } } return responseMap; } public OSD GenerateNoHandlerMessage() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("LLSDRequest"); map["message"] = OSD.FromString("No handler registered for LLSD Requests"); map["login"] = OSD.FromString("false"); map["connect"] = OSD.FromString("false"); return map; } public OSD GenerateNoStateMessage(UUID passedAvatar) { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("derez failed"); map["message"] = OSD.FromString("Unable to locate OGP state for avatar " + passedAvatar.ToString()); map["login"] = OSD.FromString("false"); map["connect"] = OSD.FromString("false"); return map; } private bool TryGetAgentCircuitData(string path, out AgentCircuitData userdata) { userdata = null; lock (CapsLoginID) { if (CapsLoginID.ContainsKey(path)) { userdata = CapsLoginID[path]; DiscardUsedCap(path); return true; } } return false; } private void DiscardUsedCap(string path) { CapsLoginID.Remove(path); } private Scene GetRootScene() { Scene ReturnScene = null; lock (m_scene) { if (m_scene.Count > 0) { ReturnScene = m_scene[0]; } } return ReturnScene; } private Scene GetScene(string scenename) { Scene ReturnScene = null; lock (m_scene) { foreach (Scene s in m_scene) { if (s.RegionInfo.RegionName.ToLower() == scenename) { ReturnScene = s; break; } } } return ReturnScene; } private ulong GetOSCompatibleRegionHandle(RegionInfo reg) { return Util.UIntsToLong(reg.RegionLocX, reg.RegionLocY); } private OGPState InitializeNewState() { OGPState returnState = new OGPState(); returnState.first_name = ""; returnState.last_name = ""; returnState.agent_id = UUID.Zero; returnState.local_agent_id = UUID.Zero; returnState.region_id = UUID.Zero; returnState.circuit_code = 0; returnState.secure_session_id = UUID.Zero; returnState.session_id = UUID.Zero; returnState.agent_access = true; returnState.god_level = 0; returnState.god_overide = false; returnState.identified = false; returnState.transacted = false; returnState.age_verified = false; returnState.limited_to_estate = 1; returnState.inventory_host = "http://inv4.mysql.aditi.lindenlab.com"; returnState.allow_redirect = true; returnState.sim_access = ""; returnState.src_can_see_mainland = true; returnState.src_estate_id = 1; returnState.src_version = 1; returnState.src_parent_estate_id = 1; returnState.visible_to_parent = true; returnState.teleported_into_region = ""; return returnState; } private OGPState GetOGPState(UUID agentId) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) { return m_OGPState[agentId]; } else { return InitializeNewState(); } } } public void DeleteOGPState(UUID agentId) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) m_OGPState.Remove(agentId); } } private void UpdateOGPState(UUID agentId, OGPState state) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) { m_OGPState[agentId] = state; } else { m_OGPState.Add(agentId,state); } } } private bool SceneListDuplicateCheck(string str) { // no lock, called from locked space! bool found = false; foreach (Scene s in m_scene) { if (s.RegionInfo.RegionName == str) { found = true; break; } } return found; } public void ShutdownConnection(UUID avatarId, OpenGridProtocolModule mod) { Scene homeScene = GetRootScene(); ScenePresence avatar = null; if (homeScene.TryGetScenePresence(avatarId,out avatar)) { KillAUser ku = new KillAUser(avatar,mod); Watchdog.StartThread(ku.ShutdownNoLogout, "OGPShutdown", ThreadPriority.Normal, true); } } // private string CreateRandomStr(int len) // { // Random rnd = new Random(Environment.TickCount); // string returnstring = ""; // string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; // // for (int i = 0; i < len; i++) // { // returnstring += chars.Substring(rnd.Next(chars.Length), 1); // } // return returnstring; // } // Temporary hack to allow teleporting to and from Vaak private static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { //if (cert.Subject == "E=root@lindenlab.com, CN=*.vaak.lindenlab.com, O=\"Linden Lab, Inc.\", L=San Francisco, S=California, C=US") //{ return true; //} //return false; } } public class KillAUser { private ScenePresence avToBeKilled = null; private OpenGridProtocolModule m_mod = null; public KillAUser(ScenePresence avatar, OpenGridProtocolModule mod) { avToBeKilled = avatar; m_mod = mod; } public void ShutdownNoLogout() { UUID avUUID = UUID.Zero; if (avToBeKilled != null) { avUUID = avToBeKilled.UUID; avToBeKilled.MakeChildAgent(); avToBeKilled.ControllingClient.SendLogoutPacketWhenClosing = false; int sleepMS = 30000; while (sleepMS > 0) { Watchdog.UpdateThread(); Thread.Sleep(1000); sleepMS -= 1000; } // test for child agent because they might have come back if (avToBeKilled.IsChildAgent) { m_mod.DeleteOGPState(avUUID); avToBeKilled.ControllingClient.Close(); } } Watchdog.RemoveThread(); } } public class MonoCert : ICertificatePolicy { #region ICertificatePolicy Members public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } #endregion } }
using System; using System.Diagnostics; using Telerik.Charting; using Telerik.Core; using Windows.Devices.Input; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; namespace Telerik.UI.Xaml.Controls.Chart { /// <summary> /// Defines the tooltip behavior for RadChart. /// </summary> public class ChartTooltipBehavior : ChartBehavior { /// <summary> /// Identifies the ContentTemplate attached property. /// Usually this property is used by chart series to define different tooltips on a per series basis. /// </summary> public static readonly DependencyProperty ContentTemplateProperty = DependencyProperty.RegisterAttached("ContentTemplate", typeof(DataTemplate), typeof(ChartTooltipBehavior), new PropertyMetadata(null)); private Popup toolTip; private ChartTooltip toolTipContent; private bool snapToClosestPoint; private Point touchOverhang = new Point(0, 24); private Point displayPosition; private Size contentSize = new Size(0, 0); private HorizontalAlignment horizontalAlign; private VerticalAlignment verticalAlign; private DataPointInfo closestDataPointInfo; private DispatcherTimer delayTimer; /// <summary> /// Initializes a new instance of the <see cref="ChartTooltipBehavior"/> class. /// </summary> public ChartTooltipBehavior() { this.toolTip = new Popup(); this.toolTipContent = new ChartTooltip(); this.toolTipContent.SizeChanged += this.OnToolTipContent_SizeChanged; this.toolTip.Child = this.toolTipContent; this.snapToClosestPoint = true; this.horizontalAlign = HorizontalAlignment.Center; this.verticalAlign = VerticalAlignment.Top; } /// <summary> /// Fires before the tool tip of RadChart is shown so that the user can provide /// a custom view model which he/she can bind to in the ToolTipTemplate. /// </summary> public event EventHandler<TooltipContextNeededEventArgs> ContextNeeded; /// <summary> /// Gets or sets the offset to be applied when the tooltip position is calculated. /// </summary> public Point TouchOverhang { get { return this.touchOverhang; } set { this.touchOverhang = value; } } /// <summary> /// Gets or sets the delay to be applied before the tooltip is displayed. /// </summary> public TimeSpan ShowDelay { get { return this.delayTimer.Interval; } set { this.delayTimer.Interval = value; } } /// <summary> /// Gets or sets the alignment of the tooltip according to the touch point along the horizontal axis. /// </summary> public HorizontalAlignment HorizontalAlignment { get { return this.horizontalAlign; } set { this.horizontalAlign = value; } } /// <summary> /// Gets or sets the alignment of the tooltip according to the touch point along the vertical axis. /// </summary> public VerticalAlignment VerticalAlignment { get { return this.verticalAlign; } set { this.verticalAlign = value; } } /// <summary> /// Gets a value indicating whether the tooltip is currently displayed. /// </summary> public bool IsOpen { get { return this.toolTip.IsOpen; } } /// <summary> /// Gets or sets a value indicating whether the tooltip will snap to the closest to the physical location data point. /// </summary> public bool SnapToClosestPoint { get { return this.snapToClosestPoint; } set { this.snapToClosestPoint = value; } } /// <summary> /// Gets a value indicating whether the developer will manually handle when the tooltip will be shown and hidden. /// </summary> public virtual bool HandleTooltipManually { get { return false; } } /// <summary> /// Gets the <see cref="DataTemplate"/> instance associated with the specified dependency object. /// </summary> public static DataTemplate GetContentTemplate(DependencyObject instance) { if (instance == null) { throw new ArgumentNullException(); } return instance.GetValue(ContentTemplateProperty) as DataTemplate; } /// <summary> /// Sets the provided <see cref="DataTemplate"/> instance to the specified dependency object. /// </summary> public static void SetContentTemplate(DependencyObject instance, DataTemplate template) { if (instance == null) { throw new ArgumentNullException(); } instance.SetValue(ContentTemplateProperty, template); } /// <summary> /// Handles the <see cref="E:RadChartBase.PointerEntered"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnPointerEntered(PointerRoutedEventArgs args) { base.OnPointerEntered(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.HandleTooltipManually) { this.SetInteractionPointCore(args.GetCurrentPoint(this.chart).Position); } } /// <summary> /// Handles the <see cref="E:RadChartBase.PointerExited"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnPointerExited(PointerRoutedEventArgs args) { base.OnPointerExited(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.HandleTooltipManually) { this.HideTooltip(); } } /// <summary> /// Handles the <see cref="E:RadChartBase.PointerPressed"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnPointerPressed(PointerRoutedEventArgs args) { base.OnPointerPressed(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.HandleTooltipManually) { this.HideTooltip(); } } /// <summary> /// Handles the <see cref="E:RadChartBase.PointerMoved"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnPointerMoved(PointerRoutedEventArgs args) { base.OnPointerMoved(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (args.Pointer.PointerDeviceType == PointerDeviceType.Touch) { // Touch is handled through manipulation events return; } if (args.Pointer.IsInContact) { // only mouse hover will be handled return; } if (!this.HandleTooltipManually) { this.SetInteractionPointCore(args.GetCurrentPoint(this.chart).Position); } } /// <summary> /// Handles the <see cref="E:RadChartBase.HoldStarted"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnHoldStarted(HoldingRoutedEventArgs args) { base.OnHoldStarted(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.toolTip.IsOpen && !this.HandleTooltipManually) { this.SetInteractionPointCore(args.GetPosition(this.chart)); } } /// <summary> /// Handles the <see cref="E:RadChartBase.HoldCompleted"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnHoldCompleted(HoldingRoutedEventArgs args) { base.OnHoldCompleted(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.HandleTooltipManually) { this.HideTooltip(); } } /// <summary> /// Handles the <see cref="E:RadChartBase.PointerReleased"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnPointerReleased(PointerRoutedEventArgs args) { base.OnPointerReleased(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.HandleTooltipManually) { this.HideTooltip(); } } /// <summary> /// Handles the <see cref="E:RadChartBase.ManipulationDelta"/> event of the owning <see cref="RadChartBase"/> instance. /// </summary> protected internal override void OnManipulationDelta(ManipulationDeltaRoutedEventArgs args) { base.OnManipulationDelta(args); if (args == null) { throw new ArgumentNullException(nameof(args)); } if (!this.chart.isInHold) { return; } if (!this.HandleTooltipManually) { this.SetInteractionPointCore(args.Position); } } /// <summary> /// Updates and opens the tooltip /// </summary> protected void ShowToolTip() { if (this.HandleTooltipManually) { this.ShowTooltipCore(); } } /// <summary> /// Hides the tooltip. /// </summary> protected void HideTooltip() { if (!this.HandleTooltipManually) { this.delayTimer.Stop(); } this.toolTip.IsOpen = false; this.displayPosition = new Point(-1, -1); } /// <summary> /// This method is called when the chart owner is loaded. /// </summary> protected override void OnLoaded() { base.OnLoaded(); if (!this.HandleTooltipManually) { this.InitializeTimer(); } this.InitializeTooltip(); } /// <summary> /// This method is called when the chart owner is removed from the visual tree. /// </summary> protected override void OnUnloaded() { base.OnUnloaded(); if (!this.HandleTooltipManually) { this.StopTimer(); } this.RemoveToolTip(); } /// <summary> /// Gets <see cref="ChartDataContext" /> associated with a gives physical location. /// </summary> /// <param name="physicalOrigin">The relative physical position of the requested data context.</param> /// <param name="findNearestPoints">True to find the nearest points, if no points are found on the requested physical location.</param> /// <returns> /// Returns <see cref="ChartDataContext" /> object holding information for the requested physical location. /// </returns> protected override ChartDataContext GetDataContext(Point physicalOrigin, bool findNearestPoints) { if (this.chart != null) { return this.chart.GetDataContext(physicalOrigin, ChartPointDistanceCalculationMode.TwoDimensional); } return null; } /// <summary> /// Sets the interaction point which will be used to calculate the tooltip's position. /// </summary> /// <param name="position"></param> protected void SetInteractionPoint(Point position) { if (this.HandleTooltipManually) { this.SetInteractionPointCore(position); } } /// <summary> /// Updates and open the tooltip. /// </summary> private void ShowTooltipCore() { object context = this.GetTooltipContext(this.displayPosition); if (context == null || this.closestDataPointInfo == null || (!this.closestDataPointInfo.ContainsTouchLocation && !this.SnapToClosestPoint)) { this.toolTip.IsOpen = false; return; } this.toolTipContent.Content = context; this.toolTip.IsOpen = true; this.UpdateTooltipPosition(this.displayPosition); } private object OnContextNeeded(ChartDataContext defaultContext) { EventHandler<TooltipContextNeededEventArgs> handler = this.ContextNeeded; if (handler == null) { return defaultContext.ClosestDataPoint; } TooltipContextNeededEventArgs args = new TooltipContextNeededEventArgs(defaultContext); handler(this, args); return args.Context != null ? args.Context : defaultContext.ClosestDataPoint; } private void InitializeTimer() { this.delayTimer = new DispatcherTimer(); this.delayTimer.Interval = TimeSpan.FromMilliseconds(300); this.delayTimer.Tick += this.OnDelayTimer_Tick; } private void StopTimer() { if (this.delayTimer.IsEnabled) { this.delayTimer.Stop(); } } private void InitializeTooltip() { if (this.chart.adornerLayer != null && !this.chart.adornerLayer.Children.Contains(this.toolTip)) { this.chart.adornerLayer.Children.Add(this.toolTip); } } private void RemoveToolTip() { this.toolTip.IsOpen = false; if (this.chart.adornerLayer != null && this.chart.adornerLayer.Children.Contains(this.toolTip)) { this.chart.adornerLayer.Children.Remove(this.toolTip); } } private object GetTooltipContext(Point location) { ChartDataContext defaultContext = this.GetDataContext(location, true); this.closestDataPointInfo = defaultContext.ClosestDataPoint; if (this.closestDataPointInfo != null && this.closestDataPointInfo.DataPoint.Presenter != null) { var template = GetContentTemplate(this.closestDataPointInfo.DataPoint.Presenter as ChartSeries); if (template != null) { this.toolTipContent.ContentTemplate = template; } if (template == null) { template = GetContentTemplate(this); this.toolTipContent.ContentTemplate = template; } if (template == null) { this.toolTipContent.ClearValue(ContentControl.ContentTemplateProperty); } } return this.OnContextNeeded(defaultContext); } private void SetInteractionPointCore(Point position) { if (this.displayPosition == position) { return; } if (!this.HandleTooltipManually) { if (!this.IsInPlotArea(position)) { this.HideTooltip(); return; } this.toolTip.IsOpen = false; // reset the timer this.delayTimer.Stop(); this.delayTimer.Start(); } this.displayPosition = position; } private void UpdateTooltipPosition(Point position) { var pointPosition = RadRect.Empty; if (this.closestDataPointInfo != null) { pointPosition = this.closestDataPointInfo.DataPoint.GetPosition(); if (!pointPosition.IsSizeValid()) { pointPosition = RadRect.Empty; } } if (this.snapToClosestPoint && pointPosition.IsSizeValid()) { position = pointPosition.Location.ToPoint(); position.X += this.chart.PlotOrigin.X; position.Y += this.chart.PlotOrigin.Y; } switch (this.horizontalAlign) { case Windows.UI.Xaml.HorizontalAlignment.Left: position.X -= this.contentSize.Width + this.touchOverhang.X; break; case Windows.UI.Xaml.HorizontalAlignment.Center: case Windows.UI.Xaml.HorizontalAlignment.Stretch: position.X += this.snapToClosestPoint ? (pointPosition.Width - this.contentSize.Width) / 2 : -this.contentSize.Width / 2; break; case Windows.UI.Xaml.HorizontalAlignment.Right: position.X = this.snapToClosestPoint ? pointPosition.Right + this.touchOverhang.X : this.touchOverhang.X; break; } switch (this.verticalAlign) { case Windows.UI.Xaml.VerticalAlignment.Top: position.Y -= this.contentSize.Height + this.touchOverhang.Y; break; case Windows.UI.Xaml.VerticalAlignment.Center: case Windows.UI.Xaml.VerticalAlignment.Stretch: position.Y += this.snapToClosestPoint ? (pointPosition.Height - this.contentSize.Height) / 2 : -this.contentSize.Height / 2; break; case Windows.UI.Xaml.VerticalAlignment.Bottom: position.Y += this.snapToClosestPoint ? pointPosition.Height + this.touchOverhang.Y : this.touchOverhang.Y; break; } this.toolTip.HorizontalOffset = position.X; this.toolTip.VerticalOffset = position.Y; } private bool IsInPlotArea(Point position) { if (this.chart == null) { return false; } position.X -= this.chart.PlotOrigin.X; position.Y -= this.chart.PlotOrigin.Y; return this.chart.PlotAreaClip.Contains(position.X, position.Y); } private void OnDelayTimer_Tick(object sender, object e) { this.delayTimer.Stop(); this.ShowTooltipCore(); } private void OnToolTipContent_SizeChanged(object sender, SizeChangedEventArgs e) { this.contentSize = e.NewSize; if (this.toolTip.IsOpen) { this.UpdateTooltipPosition(this.displayPosition); } } } }
/** * Project: emergetk: stateful web framework for the masses * File name: .cs * Description: * * @author Ben Joldersma, All-In-One Creations, Ltd. http://all-in-one-creations.net, Copyright (C) 2006. * * @see The GNU Public License (GPL) */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Collections.Generic; using EmergeTk.Widgets.Html; using EmergeTk.Model; namespace EmergeTk { /// <summary> /// Summary description for WidgetCollection. /// </summary> public class WidgetCollection : IEnumerable { //private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(WidgetCollection)); private List<Widget> ordered; public Widget this[ string key ] { get { if (!initialized){ initialize(); return null; } foreach( Widget w in ordered ) if( w.Id == key ) return w; return null; } // set // { // if (key == null) // { // throw new System.ArgumentNullException("Key", "No valid Id for key. Did you instantiate with Context.CreateWidget<>? If not, you must explicitly set the widget's Id."); // } // Add(value); // } } bool initialized = false; private void initialize() { ordered = new List<Widget>(); initialized = true; } public Widget this[ int index ] { get { try { if (!initialized) { initialize(); return null; } return ordered[ index ] as Widget; } catch( Exception e ) { Debug.Trace("error accessing index: {1}, ordered: {2}, details: {0}, ", Util.BuildExceptionOutput(e),index,ordered ); foreach( Widget w in ordered ) Debug.Trace("widget {0} in list.",w); throw new Exception("error accessing ordinal based WdigetCollection default indexer.", e); } } // set // { // Add(value); // } } public TextBox GetTextBox( string key ) { return Find( key ) as TextBox; } public Label GetLabel( string key ) { return Find( key ) as Label; } public Button GetButton( string key ) { return Find( key ) as Button; } public int Count { get { return ordered.Count; } } public Widget Find( string key ) { Widget theOne = null; foreach( Widget c in this ) { if( c.Id == key ) { return c; } if( c.IsParent ) { theOne = c.Widgets.Find( key ); if( theOne != null ) { return theOne; } } } return theOne; } public T Find<T>() where T : Widget { return Find<T>(null); } public T Find<T>(string k) where T : Widget { foreach( Widget c in this ) { if( c is T && ( k == null || c.Id == k ) ) { return (T)c; } if( c.IsParent ) { T c2 = c.Widgets.Find<T>(k); if( c2 != null ) return c2; } } return null; } public T Find<T,R>(string k, R r) where T : Widget where R : AbstractRecord { foreach( Widget c in this ) { if( c is T && ( k == null || c.Id == k ) && c.Record is R && ( r == null || c.Record == r ) ) { return c as T; } if( c.IsParent ) { T c2 = c.Widgets.Find<T,R>(k,r); if( c2 != null ) return c2; } } return null; } public Widget Find(Type type, string k) { foreach( Widget c in this ) { if( c.GetType() == type && ( k == null || c.Id == k ) ) { return c; } if( c.IsParent ) { Widget c2 = c.Widgets.Find(type, k); if( c2 != null ) return c2; } } return null; } public List<T> FindAll<T>() where T : class { List<T> items = null; foreach( Widget c in this ) { if( c is T ) { if( items == null ) items = new List<T>(); items.Add( c as T ); } if( c.Widgets != null ) { List<T> childItems = c.Widgets.FindAll<T>(); if( childItems != null ) { if( items == null ) items = childItems; else items.AddRange( childItems.ToArray() ); } } } return items; } public List<Widget> FindAll(Type type) { List<Widget> items = null; foreach( Widget c in this ) { if( c.GetType() == type ) { if( items == null ) items = new List<Widget>(); items.Add( c ); } if( c.Widgets != null ) { List<Widget> childItems = c.Widgets.FindAll(type); if( childItems != null ) { if( items == null ) items = childItems; else items.AddRange( childItems.ToArray() ); } } } return items; } public Widget Find( Type type ) { foreach( Widget c in this ) { if( c.GetType() == type ) { return c; } if( c.IsParent ) { Widget c2 = c.Widgets.Find( type ); if( c2 != null ) return c2; } } return null; } public void Remove( Widget c ) { ordered.Remove(c); } #region IEnumerable Members public IEnumerator GetEnumerator() { if (!initialized) initialize(); return ordered.GetEnumerator(); } #endregion #region IList Members public bool IsReadOnly { get { // TODO: Add WidgetCollection.IsReadOnly getter implementation return false; } } public void RemoveAt(int index) { ordered.RemoveAt( index ); } public void Insert(int index, Widget value) { if (!initialized) initialize(); ordered.Insert( index, value ); } public bool Contains(Widget value) { if (!initialized) initialize(); foreach( Widget w in ordered ) if( w == value ) return true; return false; } public void Clear() { ordered.Clear(); } public int IndexOf(Widget value) { return ordered.IndexOf( value ); } public int Add(Widget value) { if (!initialized) initialize(); ordered.Add( value ); return ordered.Count - 1; } public bool IsFixedSize { get { // TODO: Add WidgetCollection.IsFixedSize getter implementation return false; } } #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.DirectoryServices; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { internal class ADDNLinkedAttrSet : BookmarkableResultSet { // This class can be used to either enumerate the members of a group, or the groups // to which a principal belongs. If being used to enumerate the members of a group: // * groupDN --- the DN of the group we're enumerating // * members --- array of enumerators containing the DNs of the members of the group we're enumerating (the "member" attribute) // * primaryGroupDN --- should be null // * recursive --- whether or not to recursively enumerate group membership // // If being used to enumerate the groups to which a principal belongs: // * groupDN --- the DN of the principal (i.e., the user) // * members --- the DNs of the groups to which that principal belongs (e.g, the "memberOf" attribute) // * primaryGroupDN --- the DN of the principal's primary group (constructed from the "primaryGroupID" attribute) // * recursive --- should be false // // Note that the variables in this class are generally named in accord with the "enumerating the members // of a group" case. // // It is assumed that recursive enumeration will only be performed for the "enumerating the members of a group" // case, not the "groups to which a principal belongs" case, thus, this.recursive == true implies the former // (but this.recursive == false could imply either case). internal ADDNLinkedAttrSet( string groupDN, IEnumerable[] members, string primaryGroupDN, DirectorySearcher primaryGroupMembersSearcher, bool recursive, ADStoreCtx storeCtx) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, PG queryFilter={3}, PG queryBase={4}", groupDN, (primaryGroupDN != null ? primaryGroupDN : "NULL"), recursive, (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"), (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); _groupsVisited.Add(groupDN); // so we don't revisit it _recursive = recursive; _storeCtx = storeCtx; _originalStoreCtx = storeCtx; if (null != members) { foreach (IEnumerable enumerator in members) { _membersQueue.Enqueue(enumerator); _originalMembers.Enqueue(enumerator); } } _members = null; _currentMembersSearcher = null; _primaryGroupDN = primaryGroupDN; if (primaryGroupDN == null) _returnedPrimaryGroup = true; // so we don't bother trying to return the primary group _primaryGroupMembersSearcher = primaryGroupMembersSearcher; _expansionMode = ExpansionMode.Enum; _originalExpansionMode = _expansionMode; } internal ADDNLinkedAttrSet( string groupDN, DirectorySearcher[] membersSearcher, string primaryGroupDN, DirectorySearcher primaryGroupMembersSearcher, bool recursive, ADStoreCtx storeCtx) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, M queryFilter={3}, M queryBase={4}, PG queryFilter={5}, PG queryBase={6}", groupDN, (primaryGroupDN != null ? primaryGroupDN : "NULL"), recursive, (membersSearcher != null ? membersSearcher[0].Filter : "NULL"), (membersSearcher != null ? membersSearcher[0].SearchRoot.Path : "NULL"), (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"), (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); _groupsVisited.Add(groupDN); // so we don't revisit it _recursive = recursive; _storeCtx = storeCtx; _originalStoreCtx = storeCtx; _members = null; _originalMembers = null; _membersEnum = null; _primaryGroupDN = primaryGroupDN; if (primaryGroupDN == null) _returnedPrimaryGroup = true; // so we don't bother trying to return the primary group if (null != membersSearcher) { foreach (DirectorySearcher ds in membersSearcher) { _memberSearchersQueue.Enqueue(ds); _memberSearchersQueueOriginal.Enqueue(ds); } } _currentMembersSearcher = null; _primaryGroupMembersSearcher = primaryGroupMembersSearcher; _expansionMode = ExpansionMode.ASQ; _originalExpansionMode = _expansionMode; } // Return the principal we're positioned at as a Principal object. // Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal internal override object CurrentAsPrincipal { get { if (this.current != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using current"); if (this.current is DirectoryEntry) return ADUtils.DirectoryEntryAsPrincipal((DirectoryEntry)this.current, _storeCtx); else { return ADUtils.SearchResultAsPrincipal((SearchResult)this.current, _storeCtx, null); } } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using currentForeignPrincipal"); Debug.Assert(_currentForeignPrincipal != null); return _currentForeignPrincipal; } } } // Advance the enumerator to the next principal in the result set, pulling in additional pages // of results (or ranges of attribute values) as needed. // Returns true if successful, false if no more results to return. internal override bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNext"); _atBeginning = false; bool needToRetry; bool f = false; do { needToRetry = false; // reset our found state. If we are restarting the loop we don't have a current principal yet. f = false; if (!_returnedPrimaryGroup) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying PrimaryGroup DN"); f = MoveNextPrimaryGroupDN(); } if (!f) { if (_expansionMode == ExpansionMode.ASQ) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying member searcher"); f = MoveNextMemberSearcher(); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying member enum"); f = MoveNextMemberEnum(); } } if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying foreign"); f = MoveNextForeign(ref needToRetry); } if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying primary group search"); f = MoveNextQueryPrimaryGroupMember(); } } while (needToRetry); return f; } private bool MoveNextPrimaryGroupDN() { // Do the special primary group ID processing if we haven't yet returned the primary group. Debug.Assert(_primaryGroupDN != null); this.current = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(_primaryGroupDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions((DirectoryEntry)this.current); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: returning primary group {0}", ((DirectoryEntry)this.current).Path); _currentForeignDE = null; _currentForeignPrincipal = null; _returnedPrimaryGroup = true; return true; } private bool GetNextSearchResult() { bool memberFound = false; do { if (_currentMembersSearcher == null) { Debug.Assert(_memberSearchersQueue != null); if (_memberSearchersQueue.Count == 0) { // We are out of searchers in the queue. return false; } else { // Remove the next searcher from the queue and place it in the current search variable. _currentMembersSearcher = _memberSearchersQueue.Dequeue(); _memberSearchResults = _currentMembersSearcher.FindAll(); Debug.Assert(_memberSearchResults != null); _memberSearchResultsEnumerator = _memberSearchResults.GetEnumerator(); } } GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher"); memberFound = _memberSearchResultsEnumerator.MoveNext(); // The search is complete. // Dipose the searcher and search results. if (!memberFound) { _currentMembersSearcher.Dispose(); _currentMembersSearcher = null; _memberSearchResults.Dispose(); _memberSearchResults = null; } } while (!memberFound); return memberFound; } private bool MoveNextMemberSearcher() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextMemberSearcher"); bool needToRetry = false; bool f = false; do { f = GetNextSearchResult(); needToRetry = false; if (f) { SearchResult currentSR = (SearchResult)_memberSearchResultsEnumerator.Current; // Got a member from this group (or, got a group of which we're a member). // Create a DirectoryEntry for it. string memberDN = (string)currentSR.Properties["distinguishedName"][0]; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: got a value from the enumerator: {0}", memberDN); // Make sure the member is a principal if ((!ADUtils.IsOfObjectClass(currentSR, "group")) && (!ADUtils.IsOfObjectClass(currentSR, "user")) && // includes computer as well (!ADUtils.IsOfObjectClass(currentSR, "foreignSecurityPrincipal"))) { // We found a member, but it's not a principal type. Skip it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: not a principal, skipping"); needToRetry = true; } // If we're processing recursively, and the member is a group, we DON'T return it, // but rather treat it as something to recursively visit later // (unless we've already visited the group previously) else if (_recursive && ADUtils.IsOfObjectClass(currentSR, "group")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: adding to groupsToVisit"); if (!_groupsVisited.Contains(memberDN) && !_groupsToVisit.Contains(memberDN)) _groupsToVisit.Add(memberDN); // and go on to the next member.... needToRetry = true; } else if (_recursive && ADUtils.IsOfObjectClass(currentSR, "foreignSecurityPrincipal")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: foreign principal, adding to foreignMembers"); // If we haven't seen this FPO yet then add it to the seen user database. if (!_usersVisited.ContainsKey(currentSR.Properties["distinguishedName"][0].ToString())) { // The FPO might represent a group, in which case we should recursively enumerate its // membership. So save it off for later processing. _foreignMembersCurrentGroup.Add(currentSR.GetDirectoryEntry()); _usersVisited.Add(currentSR.Properties["distinguishedName"][0].ToString(), true); } // and go on to the next member.... needToRetry = true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: using as current"); // Check to see if we have already seen this user during the enumeration // If so then move on to the next user. If not then return it as current. if (!_usersVisited.ContainsKey(currentSR.Properties["distinguishedName"][0].ToString())) { this.current = currentSR; _currentForeignDE = null; _currentForeignPrincipal = null; _usersVisited.Add(currentSR.Properties["distinguishedName"][0].ToString(), true); } else { needToRetry = true; } } } else { // We reached the end of this group's membership. If we're not processing recursively, // we're done. Otherwise, go on to the next group to visit. // First create a DE that points to the group we want to expand, Using that as a search root run // an ASQ search against member and start enumerting those results. if (_recursive) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: recursive processing, groupsToVisit={0}", _groupsToVisit.Count); if (_groupsToVisit.Count > 0) { // Pull off the next group to visit string groupDN = _groupsToVisit[0]; _groupsToVisit.RemoveAt(0); _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: recursively processing {0}", groupDN); // get the membership of this new group DirectoryEntry groupDE = SDSUtils.BuildDirectoryEntry(BuildPathFromDN(groupDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions(groupDE); // Queue up a searcher for the new group expansion. DirectorySearcher ds = SDSUtils.ConstructSearcher(groupDE); ds.Filter = "(objectClass=*)"; ds.SearchScope = SearchScope.Base; ds.AttributeScopeQuery = "member"; ds.CacheResults = false; _memberSearchersQueue.Enqueue(ds); // and go on to the first member of this new group. needToRetry = true; } } } } while (needToRetry); return f; } private bool GetNextEnum() { bool memberFound = false; do { if (null == _members) { if (_membersQueue.Count == 0) { return false; } _members = _membersQueue.Dequeue(); _membersEnum = _members.GetEnumerator(); } memberFound = _membersEnum.MoveNext(); if (!memberFound) { IDisposable disposableMembers = _members as IDisposable; if (disposableMembers != null) { disposableMembers.Dispose(); } IDisposable disposableMembersEnum = _membersEnum as IDisposable; if (disposableMembersEnum != null) { disposableMembersEnum.Dispose(); } _members = null; _membersEnum = null; } } while (!memberFound); return memberFound; } private bool MoveNextMemberEnum() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextMemberEnum"); bool needToRetry = false; bool disposeMemberDE = false; bool f; do { f = GetNextEnum(); needToRetry = false; disposeMemberDE = false; if (f) { DirectoryEntry memberDE = null; try { // Got a member from this group (or, got a group of which we're a member). // Create a DirectoryEntry for it. string memberDN = (string)_membersEnum.Current; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: got a value from the enumerator: {0}", memberDN); memberDE = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(memberDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions(memberDE); _storeCtx.LoadDirectoryEntryAttributes(memberDE); // Make sure the member is a principal if ((!ADUtils.IsOfObjectClass(memberDE, "group")) && (!ADUtils.IsOfObjectClass(memberDE, "user")) && // includes computer as well (!ADUtils.IsOfObjectClass(memberDE, "foreignSecurityPrincipal"))) { // We found a member, but it's not a principal type. Skip it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: not a principal, skipping"); needToRetry = true; disposeMemberDE = true; //Since member is not principal we don't return it. So mark it for dispose. } // If we're processing recursively, and the member is a group, we DON'T return it, // but rather treat it as something to recursively visit later // (unless we've already visited the group previously) else if (_recursive && ADUtils.IsOfObjectClass(memberDE, "group")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: adding to groupsToVisit"); if (!_groupsVisited.Contains(memberDN) && !_groupsToVisit.Contains(memberDN)) _groupsToVisit.Add(memberDN); // and go on to the next member.... needToRetry = true; disposeMemberDE = true; //Since recursive is set to true, we do not return groups. So mark it for dispose. } else if (_recursive && ADUtils.IsOfObjectClass(memberDE, "foreignSecurityPrincipal")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: foreign principal, adding to foreignMembers"); // If we haven't seen this FPO yet then add it to the seen user database. if (!_usersVisited.ContainsKey(memberDE.Properties["distinguishedName"][0].ToString())) { // The FPO might represent a group, in which case we should recursively enumerate its // membership. So save it off for later processing. _foreignMembersCurrentGroup.Add(memberDE); _usersVisited.Add(memberDE.Properties["distinguishedName"][0].ToString(), true); disposeMemberDE = false; //We store the FPO DirectoryEntry objects for further processing. So do NOT dispose it. } // and go on to the next member.... needToRetry = true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: using as current"); // Check to see if we have already seen this user during the enumeration // If so then move on to the next user. If not then return it as current. if (!_usersVisited.ContainsKey(memberDE.Properties["distinguishedName"][0].ToString())) { this.current = memberDE; _currentForeignDE = null; _currentForeignPrincipal = null; _usersVisited.Add(memberDE.Properties["distinguishedName"][0].ToString(), true); disposeMemberDE = false; //memberDE will be set in the Principal object we return. So do NOT dispose it. } else { needToRetry = true; } } } finally { if (disposeMemberDE && memberDE != null) { //This means the constructed member is not used in the new principal memberDE.Dispose(); } } } else { // We reached the end of this group's membership. If we're not processing recursively, // we're done. Otherwise, go on to the next group to visit. if (_recursive) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextLocal: recursive processing, groupsToVisit={0}", _groupsToVisit.Count); if (_groupsToVisit.Count > 0) { // Pull off the next group to visit string groupDN = _groupsToVisit[0]; _groupsToVisit.RemoveAt(0); _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: recursively processing {0}", groupDN); // get the membership of this new group DirectoryEntry groupDE = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(groupDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions(groupDE); // set up for the next round of enumeration //Here a new DirectoryEntry object is created and passed //to RangeRetriever object. Hence, configure //RangeRetriever to dispose the DirEntry on its dispose. _membersQueue.Enqueue(new RangeRetriever(groupDE, "member", true)); // and go on to the first member of this new group.... needToRetry = true; } } } } while (needToRetry); return f; } private void TranslateForeignMembers() { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "TranslateForeignMembers: Translating foreign members"); List<byte[]> sidList = new List<byte[]>(_foreignMembersCurrentGroup.Count); // Foreach foreign principal retrive the sid. // If the SID is for a fake object we have to track it separately. If we were attempt to translate it // it would fail and not be returned and we would lose it. // Once we have a list of sids then translate them against the target store in one call. foreach (DirectoryEntry de in _foreignMembersCurrentGroup) { // Get the SID of the foreign principal if (de.Properties["objectSid"].Count == 0) { throw new PrincipalOperationException(SR.ADStoreCtxCantRetrieveObjectSidForCrossStore); } byte[] sid = (byte[])de.Properties["objectSid"].Value; // What type of SID is it? SidType sidType = Utils.ClassifySID(sid); if (sidType == SidType.FakeObject) { //Add the foreign member DirectoryEntry to fakePrincipalMembers list for further translation //This de will be disposed after completing the translation by another code block. _fakePrincipalMembers.Add(de); // It's a FPO for something like NT AUTHORITY\NETWORK SERVICE. // There's no real store object corresponding to this FPO, so // fake a Principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "TranslateForeignMembers: fake principal, SID={0}", Utils.ByteArrayToString(sid)); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "TranslateForeignMembers: standard principal, SID={0}", Utils.ByteArrayToString(sid)); sidList.Add(sid); //We do NOT need the Foreign member DirectoryEntry object once it has been translated and added to sidList. //So disposing it off now de.Dispose(); } } // This call will perform a bulk sid translate to the name + issuer domain. _foreignMembersToReturn = new SidList(sidList, _storeCtx.DnsHostName, _storeCtx.Credentials); // We have translated the sids so clear the group now. _foreignMembersCurrentGroup.Clear(); } private bool MoveNextForeign(ref bool outerNeedToRetry) { outerNeedToRetry = false; bool needToRetry; Principal foreignPrincipal; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextForeign"); do { needToRetry = false; if (_foreignMembersCurrentGroup.Count > 0) { TranslateForeignMembers(); } if (_fakePrincipalMembers.Count > 0) { foreignPrincipal = _storeCtx.ConstructFakePrincipalFromSID((byte[])_fakePrincipalMembers[0].Properties["objectSid"].Value); _fakePrincipalMembers[0].Dispose(); _fakePrincipalMembers.RemoveAt(0); } else if ((_foreignMembersToReturn != null) && (_foreignMembersToReturn.Length > 0)) { StoreCtx foreignStoreCtx; SidListEntry foreignSid = _foreignMembersToReturn[0]; // sidIssuerName is null only if SID was not resolved // return a unknown principal back if (null == foreignSid.sidIssuerName) { // create and return the unknown principal if it is not yet present in usersVisited if (!_usersVisited.ContainsKey(foreignSid.name)) { byte[] sid = Utils.ConvertNativeSidToByteArray(foreignSid.pSid); UnknownPrincipal unknownPrincipal = UnknownPrincipal.CreateUnknownPrincipal(_storeCtx.OwningContext, sid, foreignSid.name); _usersVisited.Add(foreignSid.name, true); this.current = null; _currentForeignDE = null; _currentForeignPrincipal = unknownPrincipal; // remove the current member _foreignMembersToReturn.RemoveAt(0); return true; } // remove the current member _foreignMembersToReturn.RemoveAt(0); needToRetry = true; continue; } SidType sidType = Utils.ClassifySID(foreignSid.pSid); if (sidType == SidType.RealObjectFakeDomain) { // This is a BUILTIN object. It's a real object on the store we're connected to, but LookupSid // will tell us it's a member of the BUILTIN domain. Resolve it as a principal on our store. GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: builtin principal"); foreignStoreCtx = _storeCtx; } else { ContextOptions remoteOptions = DefaultContextOptions.ADDefaultContextOption; #if USE_CTX_CACHE PrincipalContext remoteCtx = SDSCache.Domain.GetContext(foreignSid.sidIssuerName, _storeCtx.Credentials, remoteOptions); #else PrincipalContext remoteCtx = new PrincipalContext( ContextType.Domain, foreignSid.sidIssuerName, null, (this.storeCtx.Credentials != null ? this.storeCtx.Credentials.UserName : null), (this.storeCtx.Credentials != null ? storeCtx.storeCtx.Credentials.Password : null), remoteOptions); #endif foreignStoreCtx = remoteCtx.QueryCtx; } foreignPrincipal = foreignStoreCtx.FindPrincipalByIdentRef( typeof(Principal), UrnScheme.SidScheme, (new SecurityIdentifier(Utils.ConvertNativeSidToByteArray(_foreignMembersToReturn[0].pSid), 0)).ToString(), DateTime.UtcNow); if (null == foreignPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: no matching principal"); throw new PrincipalOperationException(SR.ADStoreCtxFailedFindCrossStoreTarget); } _foreignMembersToReturn.RemoveAt(0); } else { // We don't have any more foreign principals to return so start with the foreign groups if (_foreignGroups.Count > 0) { outerNeedToRetry = true; // Determine the domainFunctionalityMode of the foreign domain. If they are W2k or not a global group then we can't use ASQ. if (_foreignGroups[0].Context.ServerInformation.OsVersion == DomainControllerMode.Win2k || _foreignGroups[0].GroupScope != GroupScope.Global) { _expansionMode = ExpansionMode.Enum; return ExpandForeignGroupEnumerator(); } else { _expansionMode = ExpansionMode.ASQ; return ExpandForeignGroupSearcher(); } } else { // We are done with foreign principals and groups.. return false; } } if (foreignPrincipal is GroupPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: foreign member is a group"); // A group, need to recursively expand it (unless it's a fake group, // in which case it is by definition empty and so contains nothing to expand, or unless // we've already or will visit it). // Postpone to later. if (!foreignPrincipal.fakePrincipal) { string groupDN = (string)((DirectoryEntry)foreignPrincipal.UnderlyingObject).Properties["distinguishedName"].Value; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: not a fake group, adding {0} to foreignGroups", groupDN); if (!_groupsVisited.Contains(groupDN) && !_groupsToVisit.Contains(groupDN)) { _foreignGroups.Add((GroupPrincipal)foreignPrincipal); } else { foreignPrincipal.Dispose(); } } needToRetry = true; continue; } else { // Not a group, nothing to recursively expand, so just return it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: using as currentForeignDE/currentForeignPrincipal"); DirectoryEntry foreignDE = (DirectoryEntry)foreignPrincipal.GetUnderlyingObject(); _storeCtx.LoadDirectoryEntryAttributes(foreignDE); if (!_usersVisited.ContainsKey(foreignDE.Properties["distinguishedName"][0].ToString())) { _usersVisited.Add(foreignDE.Properties["distinguishedName"][0].ToString(), true); this.current = null; _currentForeignDE = null; _currentForeignPrincipal = foreignPrincipal; return true; } else { foreignPrincipal.Dispose(); } needToRetry = true; continue; } } while (needToRetry); return false; } private bool ExpandForeignGroupEnumerator() { Debug.Assert(_recursive == true); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupEnumerator: there are {0} foreignGroups", _foreignGroups.Count); GroupPrincipal foreignGroup = _foreignGroups[0]; _foreignGroups.RemoveAt(0); // Since members of AD groups must be AD objects Debug.Assert(foreignGroup.Context.QueryCtx is ADStoreCtx); Debug.Assert(foreignGroup.UnderlyingObject is DirectoryEntry); Debug.Assert(((DirectoryEntry)foreignGroup.UnderlyingObject).Path.StartsWith("LDAP:", StringComparison.Ordinal)); _storeCtx = (ADStoreCtx)foreignGroup.Context.QueryCtx; //Here the foreignGroup object is removed from the foreignGroups collection. //and not used anymore. Hence, configure RangeRetriever to dispose the DirEntry on its dispose. _membersQueue.Enqueue(new RangeRetriever((DirectoryEntry)foreignGroup.UnderlyingObject, "member", true)); string groupDN = (string)((DirectoryEntry)foreignGroup.UnderlyingObject).Properties["distinguishedName"].Value; _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupEnumerator: recursively processing {0}", groupDN); return true; } private bool ExpandForeignGroupSearcher() { Debug.Assert(_recursive == true); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupSearcher: there are {0} foreignGroups", _foreignGroups.Count); GroupPrincipal foreignGroup = _foreignGroups[0]; _foreignGroups.RemoveAt(0); // Since members of AD groups must be AD objects Debug.Assert(foreignGroup.Context.QueryCtx is ADStoreCtx); Debug.Assert(foreignGroup.UnderlyingObject is DirectoryEntry); Debug.Assert(((DirectoryEntry)foreignGroup.UnderlyingObject).Path.StartsWith("LDAP:", StringComparison.Ordinal)); _storeCtx = (ADStoreCtx)foreignGroup.Context.QueryCtx; // Queue up a searcher for the new group expansion. DirectorySearcher ds = SDSUtils.ConstructSearcher((DirectoryEntry)foreignGroup.UnderlyingObject); ds.Filter = "(objectClass=*)"; ds.SearchScope = SearchScope.Base; ds.AttributeScopeQuery = "member"; ds.CacheResults = false; _memberSearchersQueue.Enqueue(ds); string groupDN = (string)((DirectoryEntry)foreignGroup.UnderlyingObject).Properties["distinguishedName"].Value; _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupSearcher: recursively processing {0}", groupDN); return true; } private bool MoveNextQueryPrimaryGroupMember() { bool f = false; if (_primaryGroupMembersSearcher != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher"); if (_queryMembersResults == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: issuing query"); _queryMembersResults = _primaryGroupMembersSearcher.FindAll(); Debug.Assert(_queryMembersResults != null); _queryMembersResultEnumerator = _queryMembersResults.GetEnumerator(); } f = _queryMembersResultEnumerator.MoveNext(); if (f) { this.current = (SearchResult)_queryMembersResultEnumerator.Current; Debug.Assert(this.current != null); _currentForeignDE = null; _currentForeignPrincipal = null; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: got a result, using as current {0}", ((SearchResult)this.current).Path); } } return f; } // Resets the enumerator to before the first result in the set. This potentially can be an expensive // operation, e.g., if doing a paged search, may need to re-retrieve the first page of results. // As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be // a no-op. internal override void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Reset"); if (!_atBeginning) { _usersVisited.Clear(); _groupsToVisit.Clear(); string originalGroupDN = _groupsVisited[0]; _groupsVisited.Clear(); _groupsVisited.Add(originalGroupDN); // clear the current enumerator _members = null; _membersEnum = null; // replace all items in the queue with the originals and reset them. if (null != _originalMembers) { _membersQueue.Clear(); foreach (IEnumerable ie in _originalMembers) { _membersQueue.Enqueue(ie); IEnumerator enumerator = ie.GetEnumerator(); enumerator.Reset(); } } _expansionMode = _originalExpansionMode; _storeCtx = _originalStoreCtx; this.current = null; if (_primaryGroupDN != null) _returnedPrimaryGroup = false; _foreignMembersCurrentGroup.Clear(); _fakePrincipalMembers.Clear(); if (null != _foreignMembersToReturn) _foreignMembersToReturn.Clear(); _currentForeignPrincipal = null; _currentForeignDE = null; _foreignGroups.Clear(); _queryMembersResultEnumerator = null; if (_queryMembersResults != null) { _queryMembersResults.Dispose(); _queryMembersResults = null; } if (null != _currentMembersSearcher) { _currentMembersSearcher.Dispose(); _currentMembersSearcher = null; } _memberSearchResultsEnumerator = null; if (_memberSearchResults != null) { _memberSearchResults.Dispose(); _memberSearchResults = null; } if (null != _memberSearchersQueue) { foreach (DirectorySearcher ds in _memberSearchersQueue) { ds.Dispose(); } _memberSearchersQueue.Clear(); if (null != _memberSearchersQueueOriginal) { foreach (DirectorySearcher ds in _memberSearchersQueueOriginal) { _memberSearchersQueue.Enqueue(ds); } } } _atBeginning = true; } } internal override ResultSetBookmark BookmarkAndReset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Bookmarking"); ADDNLinkedAttrSetBookmark bookmark = new ADDNLinkedAttrSetBookmark(); bookmark.usersVisited = _usersVisited; _usersVisited = new Dictionary<string, bool>(); bookmark.groupsToVisit = _groupsToVisit; _groupsToVisit = new List<string>(); string originalGroupDN = _groupsVisited[0]; bookmark.groupsVisited = _groupsVisited; _groupsVisited = new List<string>(); _groupsVisited.Add(originalGroupDN); bookmark.expansionMode = _expansionMode; // bookmark the current enumerators bookmark.members = _members; bookmark.membersEnum = _membersEnum; // Clear the current enumerators for reset _members = null; _membersEnum = null; // Copy all enumerators in the queue over to the bookmark queue. if (null != _membersQueue) { bookmark.membersQueue = new Queue<IEnumerable>(_membersQueue.Count); foreach (IEnumerable ie in _membersQueue) { bookmark.membersQueue.Enqueue(ie); } } // Refill the original queue with the original enumerators and reset them if (null != _membersQueue) { _membersQueue.Clear(); if (_originalMembers != null) { foreach (IEnumerable ie in _originalMembers) { _membersQueue.Enqueue(ie); IEnumerator enumerator = ie.GetEnumerator(); enumerator.Reset(); } } } bookmark.storeCtx = _storeCtx; _expansionMode = _originalExpansionMode; if (null != _currentMembersSearcher) { _currentMembersSearcher.Dispose(); _currentMembersSearcher = null; } _storeCtx = _originalStoreCtx; bookmark.current = this.current; bookmark.returnedPrimaryGroup = _returnedPrimaryGroup; this.current = null; if (_primaryGroupDN != null) _returnedPrimaryGroup = false; bookmark.foreignMembersCurrentGroup = _foreignMembersCurrentGroup; bookmark.fakePrincipalMembers = _fakePrincipalMembers; bookmark.foreignMembersToReturn = _foreignMembersToReturn; bookmark.currentForeignPrincipal = _currentForeignPrincipal; bookmark.currentForeignDE = _currentForeignDE; _foreignMembersCurrentGroup = new List<DirectoryEntry>(); _fakePrincipalMembers = new List<DirectoryEntry>(); _currentForeignDE = null; bookmark.foreignGroups = _foreignGroups; _foreignGroups = new List<GroupPrincipal>(); bookmark.queryMembersResults = _queryMembersResults; bookmark.queryMembersResultEnumerator = _queryMembersResultEnumerator; _queryMembersResults = null; _queryMembersResultEnumerator = null; bookmark.memberSearchResults = _memberSearchResults; bookmark.memberSearchResultsEnumerator = _memberSearchResultsEnumerator; _memberSearchResults = null; _memberSearchResultsEnumerator = null; if (null != _memberSearchersQueue) { bookmark.memberSearcherQueue = new Queue<DirectorySearcher>(_memberSearchersQueue.Count); foreach (DirectorySearcher ds in _memberSearchersQueue) { bookmark.memberSearcherQueue.Enqueue(ds); } } if (null != _memberSearchersQueueOriginal) { _memberSearchersQueue.Clear(); foreach (DirectorySearcher ds in _memberSearchersQueueOriginal) { _memberSearchersQueue.Enqueue(ds); } } bookmark.atBeginning = _atBeginning; _atBeginning = true; return bookmark; } internal override void RestoreBookmark(ResultSetBookmark bookmark) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Restoring from bookmark"); Debug.Assert(bookmark is ADDNLinkedAttrSetBookmark); ADDNLinkedAttrSetBookmark adBookmark = (ADDNLinkedAttrSetBookmark)bookmark; _usersVisited = adBookmark.usersVisited; _groupsToVisit = adBookmark.groupsToVisit; _groupsVisited = adBookmark.groupsVisited; _storeCtx = adBookmark.storeCtx; this.current = adBookmark.current; _returnedPrimaryGroup = adBookmark.returnedPrimaryGroup; _foreignMembersCurrentGroup = adBookmark.foreignMembersCurrentGroup; _fakePrincipalMembers = adBookmark.fakePrincipalMembers; _foreignMembersToReturn = adBookmark.foreignMembersToReturn; _currentForeignPrincipal = adBookmark.currentForeignPrincipal; _currentForeignDE = adBookmark.currentForeignDE; _foreignGroups = adBookmark.foreignGroups; if (_queryMembersResults != null) _queryMembersResults.Dispose(); _queryMembersResults = adBookmark.queryMembersResults; _queryMembersResultEnumerator = adBookmark.queryMembersResultEnumerator; _memberSearchResults = adBookmark.memberSearchResults; _memberSearchResultsEnumerator = adBookmark.memberSearchResultsEnumerator; _atBeginning = adBookmark.atBeginning; _expansionMode = adBookmark.expansionMode; // Replace enumerators _members = adBookmark.members; _membersEnum = adBookmark.membersEnum; // Replace the enumerator queue elements if (null != _membersQueue) { _membersQueue.Clear(); if (null != adBookmark.membersQueue) { foreach (IEnumerable ie in adBookmark.membersQueue) { _membersQueue.Enqueue(ie); } } } if (null != _memberSearchersQueue) { foreach (DirectorySearcher ds in _memberSearchersQueue) { ds.Dispose(); } _memberSearchersQueue.Clear(); if (null != adBookmark.memberSearcherQueue) { foreach (DirectorySearcher ds in adBookmark.memberSearcherQueue) { _memberSearchersQueue.Enqueue(ds); } } } } // IDisposable implementation public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing"); if (_primaryGroupMembersSearcher != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing primaryGroupMembersSearcher"); _primaryGroupMembersSearcher.Dispose(); } if (_queryMembersResults != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing queryMembersResults"); _queryMembersResults.Dispose(); } if (_currentMembersSearcher != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersSearcher"); _currentMembersSearcher.Dispose(); } if (_memberSearchResults != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchResults"); _memberSearchResults.Dispose(); } if (_memberSearchersQueue != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchersQueue"); foreach (DirectorySearcher ds in _memberSearchersQueue) { ds.Dispose(); } _memberSearchersQueue.Clear(); } IDisposable disposableMembers = _members as IDisposable; if (disposableMembers != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing members Enumerable"); disposableMembers.Dispose(); } IDisposable disposableMembersEnum = _membersEnum as IDisposable; if (disposableMembersEnum != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersEnum Enumerator"); disposableMembersEnum.Dispose(); } if (_membersQueue != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersQueue"); foreach (IEnumerable enumerable in _membersQueue) { IDisposable disposableEnum = enumerable as IDisposable; if (disposableEnum != null) { disposableEnum.Dispose(); } } } if (_foreignGroups != null) { foreach (GroupPrincipal gp in _foreignGroups) { gp.Dispose(); } } _disposed = true; } } finally { base.Dispose(); } } // // // private UnsafeNativeMethods.IADsPathname _pathCracker = null; private readonly object _pathLock = new object(); private Dictionary<string, bool> _usersVisited = new Dictionary<string, bool>(); // The 0th entry in this list is always the DN of the original group/user whose membership we're querying private List<string> _groupsVisited = new List<string>(); private List<string> _groupsToVisit = new List<string>(); protected object current = null; // current member of the group (or current group of the user) private bool _returnedPrimaryGroup = false; private readonly string _primaryGroupDN; // the DN of the user's PrimaryGroup (not included in this.members/originalMembers) private readonly bool _recursive; private readonly Queue<IEnumerable> _membersQueue = new Queue<IEnumerable>(); private IEnumerable _members; // the membership we're currently enumerating over private readonly Queue<IEnumerable> _originalMembers = new Queue<IEnumerable>(); // the membership we started off with (before recursing) private IEnumerator _membersEnum = null; private ADStoreCtx _storeCtx; private readonly ADStoreCtx _originalStoreCtx; private bool _atBeginning = true; private bool _disposed = false; // foreign // This contains a list of employees built while enumerating the current group. These are FSP objects in the current domain and need to // be translated to find out the domain that holds the actual object. private List<DirectoryEntry> _foreignMembersCurrentGroup = new List<DirectoryEntry>(); // List of objects from the group tha are actual fake group objects. private List<DirectoryEntry> _fakePrincipalMembers = new List<DirectoryEntry>(); // list of SIDs + store that have been translated. These could be any principal object private SidList _foreignMembersToReturn = null; private Principal _currentForeignPrincipal = null; private DirectoryEntry _currentForeignDE = null; private List<GroupPrincipal> _foreignGroups = new List<GroupPrincipal>(); // members based on a query (used for users who are group members by virtue of their primaryGroupId pointing to the group) private readonly DirectorySearcher _primaryGroupMembersSearcher; private SearchResultCollection _queryMembersResults = null; private IEnumerator _queryMembersResultEnumerator = null; private DirectorySearcher _currentMembersSearcher = null; private readonly Queue<DirectorySearcher> _memberSearchersQueue = new Queue<DirectorySearcher>(); private readonly Queue<DirectorySearcher> _memberSearchersQueueOriginal = new Queue<DirectorySearcher>(); private SearchResultCollection _memberSearchResults = null; private IEnumerator _memberSearchResultsEnumerator = null; private ExpansionMode _expansionMode; private readonly ExpansionMode _originalExpansionMode; private string BuildPathFromDN(string dn) { string userSuppliedServername = _storeCtx.UserSuppliedServerName; if (null == _pathCracker) { lock (_pathLock) { if (null == _pathCracker) { UnsafeNativeMethods.Pathname pathNameObj = new UnsafeNativeMethods.Pathname(); _pathCracker = (UnsafeNativeMethods.IADsPathname)pathNameObj; _pathCracker.EscapedMode = 2 /* ADS_ESCAPEDMODE_ON */; } } } _pathCracker.Set(dn, 4 /* ADS_SETTYPE_DN */); string escapedDn = _pathCracker.Retrieve(7 /* ADS_FORMAT_X500_DN */); if (userSuppliedServername.Length > 0) return "LDAP://" + _storeCtx.UserSuppliedServerName + "/" + escapedDn; else return "LDAP://" + escapedDn; } } internal enum ExpansionMode { Enum = 0, ASQ = 1, } internal class ADDNLinkedAttrSetBookmark : ResultSetBookmark { public Dictionary<string, bool> usersVisited; public List<string> groupsToVisit; public List<string> groupsVisited; public IEnumerable members; public IEnumerator membersEnum = null; public Queue<IEnumerable> membersQueue; public ADStoreCtx storeCtx; public object current; public bool returnedPrimaryGroup; public List<DirectoryEntry> foreignMembersCurrentGroup; public List<DirectoryEntry> fakePrincipalMembers; public SidList foreignMembersToReturn; public Principal currentForeignPrincipal; public DirectoryEntry currentForeignDE; public List<GroupPrincipal> foreignGroups; public SearchResultCollection queryMembersResults; public IEnumerator queryMembersResultEnumerator; public SearchResultCollection memberSearchResults; public IEnumerator memberSearchResultsEnumerator; public bool atBeginning; public ExpansionMode expansionMode; public Queue<DirectorySearcher> memberSearcherQueue; } } // #endif
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace MagicOnion.Generator.Tests { public class GenerateGenericsStreamingHubTest { private readonly ITestOutputHelper _testOutputHelper; public GenerateGenericsStreamingHubTest(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public async Task Parameters() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task A(MyGenericObject<int> a); Task B(MyGenericObject<MyObject> a); } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject>", }); } [Fact] public async Task Parameters_MultipleTypeArgs() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task A(MyGenericObject<int, MyObject> a); Task B(MyGenericObject<MyObject, int> a); } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T1, T2> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T1, T2> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T1, T2>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T1, T2> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T1, T2> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int, global::TempProject.MyObject>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject, int>", }); } [Fact] public async Task Parameters_Nested() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task A(MyGenericObject<MyGenericObject<MyObject>> a); Task B(MyGenericObject<MyGenericObject<MyGenericObject<MyObject>>> a); Task C(MyGenericObject<MyGenericObject<MyGenericObject<int>>> a); } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyObject>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyGenericObject<global::TempProject.MyObject>>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyGenericObject<int>>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject>", }); } [Fact] public async Task Parameters_Nested_Enum() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<Nil> GetEnumAsync(MyGenericObject<MyGenericObject<MyEnum>> arg0); } public enum MyEnum { A, B, C } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter")); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyEnum>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyEnum>>", }); } [Fact] public async Task Parameters_Nested_Array() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<Nil> GetValuesAsync(MyGenericObject<MyNestedGenericObject[]> arg0); } public class MyGenericObject<T> { } public class MyNestedGenericObject { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyNestedGenericObject[]>", "global::MessagePack.Formatters.ArrayFormatter<global::TempProject.MyNestedGenericObject>" }); } [Fact] public async Task Parameters_ListFormatter_KnownType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Collections.Generic; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<Nil> GetStringValuesAsync(List<string> arg0); Task<Nil> GetIntValuesAsync(List<int> arg0); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ListFormatter<string>", "global::MessagePack.Formatters.ListFormatter<int>" }); } [Fact] public async Task Parameters_ListFormatter_UserType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Collections.Generic; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<Nil> GetValuesAsync(List<MyResponse> arg0); } public class MyResponse { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ListFormatter<global::TempProject.MyResponse>", }); } [Fact] public async Task Parameters_ArrayFormatter_KnownType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<Nil> GetStringValuesAsync(string[] arg0); Task<Nil> GetIntValuesAsync(int[] arg0); Task<Nil> GetInt32ValuesAsync(Int32[] arg0); Task<Nil> GetSingleValuesAsync(float[] arg0); Task<Nil> GetBooleanValuesAsync(bool[] arg0); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().BeEmpty(); } [Fact] public async Task Parameters_ArrayFormatter_UserType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<Nil> GetValuesAsync(MyResponse[] arg0); } public class MyResponse { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ArrayFormatter<global::TempProject.MyResponse>" }); } [Fact] public async Task Return() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyGenericObject<int>> A(); Task<MyGenericObject<MyObject>> B(); } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject>", }); } [Fact] public async Task Return_Nested() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyGenericObject<MyGenericObject<MyObject>>> A(); Task<MyGenericObject<MyGenericObject<MyGenericObject<MyObject>>>> B(); Task<MyGenericObject<MyGenericObject<MyGenericObject<int>>>> C(); } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyObject>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyGenericObject<global::TempProject.MyObject>>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyGenericObject<int>>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject>", }); } [Fact] public async Task Return_MultipleTypeArgs() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyGenericObject<int, MyObject>> A(); Task<MyGenericObject<MyObject, int>> B(); } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T1, T2> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T1, T2> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T1, T2>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T1, T2> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T1, T2> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int, global::TempProject.MyObject>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject, int>", }); } [Fact] public async Task Return_Enum() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyGenericObject<MyEnum>> GetEnumAsync(); } public enum MyEnum { A, B, C } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter")); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyEnum>", }); } [Fact] public async Task Return_Nested_Enum() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyGenericObject<MyGenericObject<MyEnum>>> GetEnumAsync(); } public enum MyEnum { A, B, C } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter")); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyEnum>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyEnum>>", }); } [Fact] public async Task Return_Nested_Array() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyGenericObject<MyNestedGenericObject[]>> GetValuesAsync(); } public class MyGenericObject<T> { } public class MyNestedGenericObject { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyNestedGenericObject[]>", "global::MessagePack.Formatters.ArrayFormatter<global::TempProject.MyNestedGenericObject>" }); } [Fact] public async Task Return_ListFormatter_KnownType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Collections.Generic; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<List<string>> GetStringValuesAsync(); Task<List<int>> GetIntValuesAsync(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ListFormatter<string>", "global::MessagePack.Formatters.ListFormatter<int>" }); } [Fact] public async Task Return_ListFormatter_UserType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Collections.Generic; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<List<MyResponse>> GetValuesAsync(); } public class MyResponse { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ListFormatter<global::TempProject.MyResponse>", }); } [Fact] public async Task Return_ArrayFormatter_KnownType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<string[]> GetStringValuesAsync(); Task<int[]> GetIntValuesAsync(); Task<Int32[]> GetInt32ValuesAsync(); Task<float[]> GetSingleValuesAsync(); Task<bool[]> GetBooleanValuesAsync(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().BeEmpty(); } [Fact] public async Task Return_ArrayFormatter_UserType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { Task<MyResponse[]> GetValuesAsync(); } public class MyResponse { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ArrayFormatter<global::TempProject.MyResponse>" }); } [Fact] public async Task HubReceiver() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyGenericObject<int> a); void B(MyGenericObject<MyObject> b); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject>", }); } [Fact] public async Task HubReceiver_Nested() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyGenericObject<MyGenericObject<MyObject>> a); void B(MyGenericObject<MyGenericObject<MyGenericObject<MyObject>>> b); void C(MyGenericObject<MyGenericObject<MyGenericObject<int>>> c); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyObject>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyGenericObject<global::TempProject.MyObject>>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyGenericObject<int>>>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject>", }); } [Fact] public async Task HubReceiver_MultipleTypeArgs() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyGenericObject<int, MyObject> a); void B(MyGenericObject<MyObject, int> b); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } [MessagePackObject] public class MyObject { } [MessagePackObject] public class MyGenericObject<T1, T2> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T1, T2> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T1, T2>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T1, T2> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T1, T2> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<int, global::TempProject.MyObject>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyObject, int>", }); } [Fact] public async Task HubReceiver_Enum() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyGenericObject<MyEnum> a); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } public enum MyEnum { A, B, C } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter")); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyEnum>", }); } [Fact] public async Task HubReceiver_Nested_Enum() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyGenericObject<MyGenericObject<MyEnum>> a); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } public enum MyEnum { A, B, C } [MessagePackObject] public class MyGenericObject<T> { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, Path.Combine(tempWorkspace.OutputDirectory, "Generated.cs"), true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); symbols.Should().Contain(x => x.Name.EndsWith("MyEnumFormatter")); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyEnum>", "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyGenericObject<global::TempProject.MyEnum>>", }); } [Fact] public async Task HubReceiver_Nested_Array() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyGenericObject<MyNestedGenericObject[]> a); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } public class MyGenericObject<T> { } public class MyNestedGenericObject { } } // Pseudo generated MessagePackFormatter using mpc (MessagePack.Generator) namespace MessagePack.Formatters.TempProject { public class MyGenericObjectFormatter<T> : MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyGenericObject<T>> { public void Serialize(ref MessagePackWriter writer, global::TempProject.MyGenericObject<T> value, MessagePackSerializerOptions options) => throw new NotImplementedException(); public global::TempProject.MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new NotImplementedException(); } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.TempProject.MyGenericObjectFormatter<global::TempProject.MyNestedGenericObject[]>", "global::MessagePack.Formatters.ArrayFormatter<global::TempProject.MyNestedGenericObject>" }); } [Fact] public async Task HubReceiver_ListFormatter_KnownType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Collections.Generic; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(List<string> a); void B(List<int> b); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ListFormatter<string>", "global::MessagePack.Formatters.ListFormatter<int>" }); } [Fact] public async Task HubReceiver_ListFormatter_UserType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Collections.Generic; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(List<MyResponse> a); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } public class MyResponse { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ListFormatter<global::TempProject.MyResponse>", }); } [Fact] public async Task HubReceiver_ArrayFormatter_KnownType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(string[] a); void B(int[] a); void C(Int32[] a); void D(float[] a); void E(bool[] a); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().BeEmpty(); } [Fact] public async Task HubReceiver_ArrayFormatter_UserType() { using var tempWorkspace = TemporaryProjectWorkarea.Create(); tempWorkspace.AddFileToProject("IMyHub.cs", @" using System; using System.Threading.Tasks; using MessagePack; using MagicOnion; namespace TempProject { public interface IMyHubReceiver { void A(MyResponse[] a); } public interface IMyHub : IStreamingHub<IMyHub, IMyHubReceiver> { } public class MyResponse { } } "); var compiler = new MagicOnionCompiler(_testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkspace.CsProjectPath, tempWorkspace.OutputDirectory, true, "TempProject.Generated", "", "MessagePack.Formatters" ); var compilation = tempWorkspace.GetOutputCompilation(); compilation.GetCompilationErrors().Should().BeEmpty(); var symbols = compilation.GetNamedTypeSymbolsFromGenerated(); compilation.GetResolverKnownFormatterTypes().Should().Contain(new[] { "global::MessagePack.Formatters.ArrayFormatter<global::TempProject.MyResponse>" }); } } }
using System; using System.Collections.Specialized; using System.Globalization; using System.Runtime; namespace System.Management { public class WqlEventQuery : EventQuery { private readonly static string tokenSelectAll; private string eventClassName; private TimeSpan withinInterval; private string condition; private TimeSpan groupWithinInterval; private StringCollection groupByPropertyList; private string havingCondition; public string Condition { get { if (this.condition != null) { return this.condition; } else { return string.Empty; } } set { this.condition = value; this.BuildQuery(); } } public string EventClassName { get { if (this.eventClassName != null) { return this.eventClassName; } else { return string.Empty; } } set { this.eventClassName = value; this.BuildQuery(); } } public StringCollection GroupByPropertyList { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.groupByPropertyList; } set { StringCollection stringCollections = value; StringCollection stringCollections1 = new StringCollection(); foreach (string str in stringCollections) { stringCollections1.Add(str); } this.groupByPropertyList = stringCollections1; this.BuildQuery(); } } public TimeSpan GroupWithinInterval { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.groupWithinInterval; } set { this.groupWithinInterval = value; this.BuildQuery(); } } public string HavingCondition { get { if (this.havingCondition != null) { return this.havingCondition; } else { return string.Empty; } } set { this.havingCondition = value; this.BuildQuery(); } } public override string QueryLanguage { get { return base.QueryLanguage; } } public override string QueryString { get { this.BuildQuery(); return base.QueryString; } set { base.QueryString = value; } } public TimeSpan WithinInterval { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.withinInterval; } set { this.withinInterval = value; this.BuildQuery(); } } static WqlEventQuery() { WqlEventQuery.tokenSelectAll = "select * "; } public WqlEventQuery() : this(null, TimeSpan.Zero, null, TimeSpan.Zero, null, null) { } public WqlEventQuery(string queryOrEventClassName) { this.groupByPropertyList = new StringCollection(); if (queryOrEventClassName == null) { return; } else { if (!queryOrEventClassName.TrimStart(new char[0]).StartsWith(WqlEventQuery.tokenSelectAll, StringComparison.OrdinalIgnoreCase)) { ManagementPath managementPath = new ManagementPath(queryOrEventClassName); if (!managementPath.IsClass || managementPath.NamespacePath.Length != 0) { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "queryOrEventClassName"); } else { this.EventClassName = queryOrEventClassName; return; } } else { this.QueryString = queryOrEventClassName; return; } } } public WqlEventQuery(string eventClassName, string condition) : this(eventClassName, TimeSpan.Zero, condition, TimeSpan.Zero, null, null) { } public WqlEventQuery(string eventClassName, TimeSpan withinInterval) : this(eventClassName, withinInterval, null, TimeSpan.Zero, null, null) { } public WqlEventQuery(string eventClassName, TimeSpan withinInterval, string condition) : this(eventClassName, withinInterval, condition, TimeSpan.Zero, null, null) { } public WqlEventQuery(string eventClassName, string condition, TimeSpan groupWithinInterval) : this(eventClassName, TimeSpan.Zero, condition, groupWithinInterval, null, null) { } public WqlEventQuery(string eventClassName, string condition, TimeSpan groupWithinInterval, string[] groupByPropertyList) : this(eventClassName, TimeSpan.Zero, condition, groupWithinInterval, groupByPropertyList, null) { } public WqlEventQuery(string eventClassName, TimeSpan withinInterval, string condition, TimeSpan groupWithinInterval, string[] groupByPropertyList, string havingCondition) { this.eventClassName = eventClassName; this.withinInterval = withinInterval; this.condition = condition; this.groupWithinInterval = groupWithinInterval; this.groupByPropertyList = new StringCollection(); if (groupByPropertyList != null) { this.groupByPropertyList.AddRange(groupByPropertyList); } this.havingCondition = havingCondition; this.BuildQuery(); } protected internal void BuildQuery() { string str; if (this.eventClassName == null || this.eventClassName.Length == 0) { base.SetQueryString(string.Empty); return; } else { string str1 = WqlEventQuery.tokenSelectAll; str1 = string.Concat(str1, "from ", this.eventClassName); if (this.withinInterval != TimeSpan.Zero) { double totalSeconds = this.withinInterval.TotalSeconds; str1 = string.Concat(str1, " within ", totalSeconds.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(double)))); } if (this.Condition.Length != 0) { str1 = string.Concat(str1, " where ", this.condition); } if (this.groupWithinInterval != TimeSpan.Zero) { double num = this.groupWithinInterval.TotalSeconds; str1 = string.Concat(str1, " group within ", num.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(double)))); if (this.groupByPropertyList != null && 0 < this.groupByPropertyList.Count) { int count = this.groupByPropertyList.Count; str1 = string.Concat(str1, " by "); for (int i = 0; i < count; i++) { string str2 = str1; string item = this.groupByPropertyList[i]; if (i == count - 1) { str = ""; } else { str = ","; } str1 = string.Concat(str2, item, str); } } if (this.HavingCondition.Length != 0) { str1 = string.Concat(str1, " having ", this.havingCondition); } } base.SetQueryString(str1); return; } } public override object Clone() { string[] strArrays = null; if (this.groupByPropertyList != null) { int count = this.groupByPropertyList.Count; if (0 < count) { strArrays = new string[count]; this.groupByPropertyList.CopyTo(strArrays, 0); } } return new WqlEventQuery(this.eventClassName, this.withinInterval, this.condition, this.groupWithinInterval, strArrays, this.havingCondition); } protected internal override void ParseQuery(string query) { string str; string str1; this.eventClassName = null; this.withinInterval = TimeSpan.Zero; this.condition = null; this.groupWithinInterval = TimeSpan.Zero; if (this.groupByPropertyList != null) { this.groupByPropertyList.Clear(); } this.havingCondition = null; string str2 = query.Trim(); bool flag = false; string str3 = ManagementQuery.tokenSelect; if (str2.Length < str3.Length || string.Compare(str2, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) != 0) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } else { str2 = str2.Remove(0, str3.Length).TrimStart(null); if (str2.StartsWith("*", StringComparison.Ordinal)) { str2 = str2.Remove(0, 1).TrimStart(null); str3 = "from "; if (str2.Length < str3.Length || string.Compare(str2, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) != 0) { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "from"); } else { ManagementQuery.ParseToken(ref str2, str3, null, ref flag, ref this.eventClassName); str3 = "within "; if (str2.Length >= str3.Length && string.Compare(str2, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { string str4 = null; flag = false; ManagementQuery.ParseToken(ref str2, str3, null, ref flag, ref str4); this.withinInterval = TimeSpan.FromSeconds(((IConvertible)str4).ToDouble(null)); } str3 = "group within "; if (str2.Length >= str3.Length) { int num = str2.ToLower(CultureInfo.InvariantCulture).IndexOf(str3, StringComparison.Ordinal); int num1 = num; if (num == -1) { str = str2.Trim(); str3 = "where "; if (str.Length >= str3.Length && string.Compare(str, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { this.condition = str.Substring(str3.Length); } return; } str = str2.Substring(0, num1).Trim(); str2 = str2.Remove(0, num1); string str5 = null; flag = false; ManagementQuery.ParseToken(ref str2, str3, null, ref flag, ref str5); this.groupWithinInterval = TimeSpan.FromSeconds(((IConvertible)str5).ToDouble(null)); str3 = "by "; if (str2.Length >= str3.Length && string.Compare(str2, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { str2 = str2.Remove(0, str3.Length); if (this.groupByPropertyList == null) { this.groupByPropertyList = new StringCollection(); } else { this.groupByPropertyList.Clear(); } while (true) { int num2 = str2.IndexOf(','); num1 = num2; if (num2 <= 0) { break; } str1 = str2.Substring(0, num1); str2 = str2.Remove(0, num1 + 1).TrimStart(null); str1 = str1.Trim(); if (str1.Length > 0) { this.groupByPropertyList.Add(str1); } } int num3 = str2.IndexOf(' '); num1 = num3; if (num3 <= 0) { this.groupByPropertyList.Add(str2); return; } else { str1 = str2.Substring(0, num1); str2 = str2.Remove(0, num1).TrimStart(null); this.groupByPropertyList.Add(str1); } } str3 = "having "; if (str2.Length >= str3.Length && string.Compare(str2, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { str2 = str2.Remove(0, str3.Length); if (str2.Length != 0) { this.havingCondition = str2; str3 = "where "; if (str.Length >= str3.Length && string.Compare(str, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { this.condition = str.Substring(str3.Length); } return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "having"); } } else { str3 = "where "; if (str.Length >= str3.Length && string.Compare(str, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { this.condition = str.Substring(str3.Length); } return; } } str = str2.Trim(); str3 = "where "; if (str.Length >= str3.Length && string.Compare(str, 0, str3, 0, str3.Length, StringComparison.OrdinalIgnoreCase) == 0) { this.condition = str.Substring(str3.Length); } return; } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "*"); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Should; using Xunit; namespace AutoMapper.UnitTests { namespace Dictionaries { //[Explicit("Need to resolve the assignable collection bug as well")] //public class When_mapping_to_a_non_generic_dictionary : AutoMapperSpecBase //{ // private Destination _result; // public class Source // { // public Hashtable Values { get; set; } // } // public class Destination // { // public IDictionary Values { get; set; } // } // protected override void Establish_context() // { // Mapper.CreateMap<Source, Destination>(); // } // protected override void Because_of() // { // var source = new Source // { // Values = new Hashtable // { // {"Key1", "Value1"}, // {"Key2", 4} // } // }; // _result = Mapper.Map<Source, Destination>(source); // } // [Fact] // public void Should_map_the_source_dictionary_with_all_keys_and_values_preserved() // { // _result.Values.Count.ShouldEqual(2); // _result.Values["Key1"].ShouldEqual("Value1"); // _result.Values["Key2"].ShouldEqual(4); // } //} public class When_mapping_to_a_generic_dictionary_with_mapped_value_pairs : SpecBase { private Destination _result; public class Source { public Dictionary<string, SourceValue> Values { get; set; } } public class SourceValue { public int Value { get; set; } } public class Destination { public Dictionary<string, DestinationValue> Values { get; set; } } public class DestinationValue { public int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); Mapper.CreateMap<SourceValue, DestinationValue>(); } protected override void Because_of() { var source = new Source { Values = new Dictionary<string, SourceValue> { {"Key1", new SourceValue {Value = 5}}, {"Key2", new SourceValue {Value = 10}}, } }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_perform_mapping_for_individual_values() { _result.Values.Count.ShouldEqual(2); _result.Values["Key1"].Value.ShouldEqual(5); _result.Values["Key2"].Value.ShouldEqual(10); } } public class When_mapping_to_a_generic_dictionary_interface_with_mapped_value_pairs : SpecBase { private Destination _result; public class Source { public Dictionary<string, SourceValue> Values { get; set; } } public class SourceValue { public int Value { get; set; } } public class Destination { public System.Collections.Generic.IDictionary<string, DestinationValue> Values { get; set; } } public class DestinationValue { public int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); Mapper.CreateMap<SourceValue, DestinationValue>(); } protected override void Because_of() { var source = new Source { Values = new Dictionary<string, SourceValue> { {"Key1", new SourceValue {Value = 5}}, {"Key2", new SourceValue {Value = 10}}, } }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_perform_mapping_for_individual_values() { _result.Values.Count.ShouldEqual(2); _result.Values["Key1"].Value.ShouldEqual(5); _result.Values["Key2"].Value.ShouldEqual(10); } } public class When_mapping_from_a_source_with_a_null_dictionary_member : AutoMapperSpecBase { private FooDto _result; public class Foo { public System.Collections.Generic.IDictionary<string, Foo> Bar { get; set; } } public class FooDto { public System.Collections.Generic.IDictionary<string, FooDto> Bar { get; set; } } protected override void Establish_context() { Mapper.AllowNullDestinationValues = false; Mapper.CreateMap<Foo, FooDto>(); Mapper.CreateMap<FooDto, Foo>(); } protected override void Because_of() { var foo1 = new Foo { Bar = new Dictionary<string, Foo> { {"lol", new Foo()} } }; _result = Mapper.Map<Foo, FooDto>(foo1); } [Fact] public void Should_fill_the_destination_with_an_empty_dictionary() { _result.Bar["lol"].Bar.ShouldNotBeNull(); _result.Bar["lol"].Bar.ShouldBeType<Dictionary<string, FooDto>>(); } } public class When_mapping_to_a_generic_dictionary_that_does_not_use_keyvaluepairs : SpecBase { private System.Collections.Generic.IDictionary<string, string> _dest; public class SourceDto { public System.Collections.Generic.IDictionary<string, string> Items { get; set; } } public class DestDto { public System.Collections.Generic.IDictionary<string, string> Items { get; set; } } protected override void Establish_context() { Mapper.CreateMap<SourceDto, DestDto>() .ForMember(d => d.Items, opt => opt.MapFrom(s => s.Items)); } protected override void Because_of() { var source = new SourceDto() { Items = new GenericWrappedDictionary<string, string> { {"A", "AAA"}, {"B", "BBB"}, {"C", "CCC"} } }; _dest = Mapper.Map<System.Collections.Generic.IDictionary<string, string>, System.Collections.Generic.IDictionary<string, string>>(source.Items); } [Fact] public void Should_map_using_the_nongeneric_dictionaryentry() { _dest.Values.Count.ShouldEqual(3); } // A wrapper for an IDictionary that implements IDictionary<TKey, TValue> // // The important difference from a standard generic BCL dictionary is that: // // ((IEnumerable)GenericWrappedDictionary).GetEnumerator() returns DictionaryEntrys // GenericWrappedDictionary.GetEnumerator() returns KeyValuePairs // // This behaviour is demonstrated by NHibernate's PersistentGenericMap // (which wraps a nongeneric PersistentMap). public class GenericWrappedDictionary<TKey, TValue> : System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.IDictionary { System.Collections.IDictionary inner = new Dictionary<TKey, TValue>(); public void Add(TKey key, TValue value) { inner.Add(key, value); } public bool ContainsKey(TKey key) { throw new NotImplementedException(); } public ICollection<TKey> Keys { get { return inner.Keys.Cast<TKey>().ToList(); } } public bool Remove(TKey key) { throw new NotImplementedException(); } public bool TryGetValue(TKey key, out TValue value) { throw new NotImplementedException(); } public ICollection<TValue> Values { get { return inner.Values.Cast<TValue>().ToList(); } } public TValue this[TKey key] { get { return (TValue)inner[key]; } set { inner[key] = value; } } public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } public int Count { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return inner.OfType<DictionaryEntry>() .Select(e => new KeyValuePair<TKey, TValue>((TKey)e.Key, (TValue)e.Value)) .GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return inner.GetEnumerator(); } public void Add(object key, object value) { inner.Add(key, value); } public bool Contains(object key) { throw new NotImplementedException(); } IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return ((System.Collections.IDictionary)inner).GetEnumerator(); } public bool IsFixedSize { get { throw new NotImplementedException(); } } ICollection System.Collections.IDictionary.Keys { get { return inner.Keys; } } public void Remove(object key) { throw new NotImplementedException(); } ICollection System.Collections.IDictionary.Values { get { return inner.Values; } } public object this[object key] { get { return inner[key]; } set { inner[key] = value; } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } } } public class When_mapping_from_a_list_of_object_to_generic_dictionary : SpecBase { private FooObject _result; public class FooDto { public DestinationValuePair[] Values { get; set; } } public class FooObject { public Dictionary<string, string> Values { get; set; } } public class DestinationValuePair { public string Key { get; set; } public string Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<FooDto, FooObject>(); Mapper.CreateMap<DestinationValuePair, KeyValuePair<string, string>>() .ConvertUsing(src => new KeyValuePair<string, string>(src.Key, src.Value)); } protected override void Because_of() { var source = new FooDto { Values = new List<DestinationValuePair> { new DestinationValuePair {Key = "Key1", Value = "Value1"}, new DestinationValuePair {Key = "Key2", Value = "Value2"} }.ToArray() }; _result = Mapper.Map<FooDto, FooObject>(source); } [Fact] public void Should_perform_mapping_for_individual_values() { _result.Values.Count.ShouldEqual(2); _result.Values["Key1"].ShouldEqual("Value1"); _result.Values["Key2"].ShouldEqual("Value2"); } } } }
#if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabResultEvent<LoginResult> OnLoginResultEvent; public event PlayFabRequestEvent<AcceptTradeRequest> OnAcceptTradeRequestEvent; public event PlayFabResultEvent<AcceptTradeResponse> OnAcceptTradeResultEvent; public event PlayFabRequestEvent<AddFriendRequest> OnAddFriendRequestEvent; public event PlayFabResultEvent<AddFriendResult> OnAddFriendResultEvent; public event PlayFabRequestEvent<AddGenericIDRequest> OnAddGenericIDRequestEvent; public event PlayFabResultEvent<AddGenericIDResult> OnAddGenericIDResultEvent; public event PlayFabRequestEvent<AddOrUpdateContactEmailRequest> OnAddOrUpdateContactEmailRequestEvent; public event PlayFabResultEvent<AddOrUpdateContactEmailResult> OnAddOrUpdateContactEmailResultEvent; public event PlayFabRequestEvent<AddSharedGroupMembersRequest> OnAddSharedGroupMembersRequestEvent; public event PlayFabResultEvent<AddSharedGroupMembersResult> OnAddSharedGroupMembersResultEvent; public event PlayFabRequestEvent<AddUsernamePasswordRequest> OnAddUsernamePasswordRequestEvent; public event PlayFabResultEvent<AddUsernamePasswordResult> OnAddUsernamePasswordResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<AndroidDevicePushNotificationRegistrationRequest> OnAndroidDevicePushNotificationRegistrationRequestEvent; public event PlayFabResultEvent<AndroidDevicePushNotificationRegistrationResult> OnAndroidDevicePushNotificationRegistrationResultEvent; public event PlayFabRequestEvent<AttributeInstallRequest> OnAttributeInstallRequestEvent; public event PlayFabResultEvent<AttributeInstallResult> OnAttributeInstallResultEvent; public event PlayFabRequestEvent<CancelTradeRequest> OnCancelTradeRequestEvent; public event PlayFabResultEvent<CancelTradeResponse> OnCancelTradeResultEvent; public event PlayFabRequestEvent<ConfirmPurchaseRequest> OnConfirmPurchaseRequestEvent; public event PlayFabResultEvent<ConfirmPurchaseResult> OnConfirmPurchaseResultEvent; public event PlayFabRequestEvent<ConsumeItemRequest> OnConsumeItemRequestEvent; public event PlayFabResultEvent<ConsumeItemResult> OnConsumeItemResultEvent; public event PlayFabRequestEvent<ConsumeMicrosoftStoreEntitlementsRequest> OnConsumeMicrosoftStoreEntitlementsRequestEvent; public event PlayFabResultEvent<ConsumeMicrosoftStoreEntitlementsResponse> OnConsumeMicrosoftStoreEntitlementsResultEvent; public event PlayFabRequestEvent<ConsumePS5EntitlementsRequest> OnConsumePS5EntitlementsRequestEvent; public event PlayFabResultEvent<ConsumePS5EntitlementsResult> OnConsumePS5EntitlementsResultEvent; public event PlayFabRequestEvent<ConsumePSNEntitlementsRequest> OnConsumePSNEntitlementsRequestEvent; public event PlayFabResultEvent<ConsumePSNEntitlementsResult> OnConsumePSNEntitlementsResultEvent; public event PlayFabRequestEvent<ConsumeXboxEntitlementsRequest> OnConsumeXboxEntitlementsRequestEvent; public event PlayFabResultEvent<ConsumeXboxEntitlementsResult> OnConsumeXboxEntitlementsResultEvent; public event PlayFabRequestEvent<CreateSharedGroupRequest> OnCreateSharedGroupRequestEvent; public event PlayFabResultEvent<CreateSharedGroupResult> OnCreateSharedGroupResultEvent; public event PlayFabRequestEvent<ExecuteCloudScriptRequest> OnExecuteCloudScriptRequestEvent; public event PlayFabResultEvent<ExecuteCloudScriptResult> OnExecuteCloudScriptResultEvent; public event PlayFabRequestEvent<GetAccountInfoRequest> OnGetAccountInfoRequestEvent; public event PlayFabResultEvent<GetAccountInfoResult> OnGetAccountInfoResultEvent; public event PlayFabRequestEvent<GetAdPlacementsRequest> OnGetAdPlacementsRequestEvent; public event PlayFabResultEvent<GetAdPlacementsResult> OnGetAdPlacementsResultEvent; public event PlayFabRequestEvent<ListUsersCharactersRequest> OnGetAllUsersCharactersRequestEvent; public event PlayFabResultEvent<ListUsersCharactersResult> OnGetAllUsersCharactersResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterDataResultEvent; public event PlayFabRequestEvent<GetCharacterInventoryRequest> OnGetCharacterInventoryRequestEvent; public event PlayFabResultEvent<GetCharacterInventoryResult> OnGetCharacterInventoryResultEvent; public event PlayFabRequestEvent<GetCharacterLeaderboardRequest> OnGetCharacterLeaderboardRequestEvent; public event PlayFabResultEvent<GetCharacterLeaderboardResult> OnGetCharacterLeaderboardResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetCharacterStatisticsRequest> OnGetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<GetCharacterStatisticsResult> OnGetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetContentDownloadUrlRequest> OnGetContentDownloadUrlRequestEvent; public event PlayFabResultEvent<GetContentDownloadUrlResult> OnGetContentDownloadUrlResultEvent; public event PlayFabRequestEvent<CurrentGamesRequest> OnGetCurrentGamesRequestEvent; public event PlayFabResultEvent<CurrentGamesResult> OnGetCurrentGamesResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardRequest> OnGetFriendLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetFriendLeaderboardResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardAroundPlayerRequest> OnGetFriendLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetFriendLeaderboardAroundPlayerResult> OnGetFriendLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetFriendsListRequest> OnGetFriendsListRequestEvent; public event PlayFabResultEvent<GetFriendsListResult> OnGetFriendsListResultEvent; public event PlayFabRequestEvent<GameServerRegionsRequest> OnGetGameServerRegionsRequestEvent; public event PlayFabResultEvent<GameServerRegionsResult> OnGetGameServerRegionsResultEvent; public event PlayFabRequestEvent<GetLeaderboardRequest> OnGetLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetLeaderboardResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundCharacterRequest> OnGetLeaderboardAroundCharacterRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundCharacterResult> OnGetLeaderboardAroundCharacterResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundPlayerRequest> OnGetLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundPlayerResult> OnGetLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetLeaderboardForUsersCharactersRequest> OnGetLeaderboardForUserCharactersRequestEvent; public event PlayFabResultEvent<GetLeaderboardForUsersCharactersResult> OnGetLeaderboardForUserCharactersResultEvent; public event PlayFabRequestEvent<GetPaymentTokenRequest> OnGetPaymentTokenRequestEvent; public event PlayFabResultEvent<GetPaymentTokenResult> OnGetPaymentTokenResultEvent; public event PlayFabRequestEvent<GetPhotonAuthenticationTokenRequest> OnGetPhotonAuthenticationTokenRequestEvent; public event PlayFabResultEvent<GetPhotonAuthenticationTokenResult> OnGetPhotonAuthenticationTokenResultEvent; public event PlayFabRequestEvent<GetPlayerCombinedInfoRequest> OnGetPlayerCombinedInfoRequestEvent; public event PlayFabResultEvent<GetPlayerCombinedInfoResult> OnGetPlayerCombinedInfoResultEvent; public event PlayFabRequestEvent<GetPlayerProfileRequest> OnGetPlayerProfileRequestEvent; public event PlayFabResultEvent<GetPlayerProfileResult> OnGetPlayerProfileResultEvent; public event PlayFabRequestEvent<GetPlayerSegmentsRequest> OnGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticsRequest> OnGetPlayerStatisticsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticsResult> OnGetPlayerStatisticsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnGetPlayerTagsResultEvent; public event PlayFabRequestEvent<GetPlayerTradesRequest> OnGetPlayerTradesRequestEvent; public event PlayFabResultEvent<GetPlayerTradesResponse> OnGetPlayerTradesResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookIDsRequest> OnGetPlayFabIDsFromFacebookIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookIDsResult> OnGetPlayFabIDsFromFacebookIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookInstantGamesIdsRequest> OnGetPlayFabIDsFromFacebookInstantGamesIdsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookInstantGamesIdsResult> OnGetPlayFabIDsFromFacebookInstantGamesIdsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGameCenterIDsRequest> OnGetPlayFabIDsFromGameCenterIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGameCenterIDsResult> OnGetPlayFabIDsFromGameCenterIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGenericIDsRequest> OnGetPlayFabIDsFromGenericIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGenericIDsResult> OnGetPlayFabIDsFromGenericIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGoogleIDsRequest> OnGetPlayFabIDsFromGoogleIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGoogleIDsResult> OnGetPlayFabIDsFromGoogleIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromKongregateIDsRequest> OnGetPlayFabIDsFromKongregateIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromKongregateIDsResult> OnGetPlayFabIDsFromKongregateIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromNintendoSwitchDeviceIdsRequest> OnGetPlayFabIDsFromNintendoSwitchDeviceIdsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromNintendoSwitchDeviceIdsResult> OnGetPlayFabIDsFromNintendoSwitchDeviceIdsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromPSNAccountIDsRequest> OnGetPlayFabIDsFromPSNAccountIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromPSNAccountIDsResult> OnGetPlayFabIDsFromPSNAccountIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromSteamIDsRequest> OnGetPlayFabIDsFromSteamIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromSteamIDsResult> OnGetPlayFabIDsFromSteamIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromTwitchIDsRequest> OnGetPlayFabIDsFromTwitchIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromTwitchIDsResult> OnGetPlayFabIDsFromTwitchIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromXboxLiveIDsRequest> OnGetPlayFabIDsFromXboxLiveIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromXboxLiveIDsResult> OnGetPlayFabIDsFromXboxLiveIDsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetPurchaseRequest> OnGetPurchaseRequestEvent; public event PlayFabResultEvent<GetPurchaseResult> OnGetPurchaseResultEvent; public event PlayFabRequestEvent<GetSharedGroupDataRequest> OnGetSharedGroupDataRequestEvent; public event PlayFabResultEvent<GetSharedGroupDataResult> OnGetSharedGroupDataResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTimeRequest> OnGetTimeRequestEvent; public event PlayFabResultEvent<GetTimeResult> OnGetTimeResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleNewsRequest> OnGetTitleNewsRequestEvent; public event PlayFabResultEvent<GetTitleNewsResult> OnGetTitleNewsResultEvent; public event PlayFabRequestEvent<GetTitlePublicKeyRequest> OnGetTitlePublicKeyRequestEvent; public event PlayFabResultEvent<GetTitlePublicKeyResult> OnGetTitlePublicKeyResultEvent; public event PlayFabRequestEvent<GetTradeStatusRequest> OnGetTradeStatusRequestEvent; public event PlayFabResultEvent<GetTradeStatusResponse> OnGetTradeStatusResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnGetUserInventoryResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<GrantCharacterToUserRequest> OnGrantCharacterToUserRequestEvent; public event PlayFabResultEvent<GrantCharacterToUserResult> OnGrantCharacterToUserResultEvent; public event PlayFabRequestEvent<LinkAndroidDeviceIDRequest> OnLinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<LinkAndroidDeviceIDResult> OnLinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<LinkAppleRequest> OnLinkAppleRequestEvent; public event PlayFabResultEvent<EmptyResult> OnLinkAppleResultEvent; public event PlayFabRequestEvent<LinkCustomIDRequest> OnLinkCustomIDRequestEvent; public event PlayFabResultEvent<LinkCustomIDResult> OnLinkCustomIDResultEvent; public event PlayFabRequestEvent<LinkFacebookAccountRequest> OnLinkFacebookAccountRequestEvent; public event PlayFabResultEvent<LinkFacebookAccountResult> OnLinkFacebookAccountResultEvent; public event PlayFabRequestEvent<LinkFacebookInstantGamesIdRequest> OnLinkFacebookInstantGamesIdRequestEvent; public event PlayFabResultEvent<LinkFacebookInstantGamesIdResult> OnLinkFacebookInstantGamesIdResultEvent; public event PlayFabRequestEvent<LinkGameCenterAccountRequest> OnLinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<LinkGameCenterAccountResult> OnLinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<LinkGoogleAccountRequest> OnLinkGoogleAccountRequestEvent; public event PlayFabResultEvent<LinkGoogleAccountResult> OnLinkGoogleAccountResultEvent; public event PlayFabRequestEvent<LinkIOSDeviceIDRequest> OnLinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<LinkIOSDeviceIDResult> OnLinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<LinkKongregateAccountRequest> OnLinkKongregateRequestEvent; public event PlayFabResultEvent<LinkKongregateAccountResult> OnLinkKongregateResultEvent; public event PlayFabRequestEvent<LinkNintendoServiceAccountRequest> OnLinkNintendoServiceAccountRequestEvent; public event PlayFabResultEvent<EmptyResult> OnLinkNintendoServiceAccountResultEvent; public event PlayFabRequestEvent<LinkNintendoSwitchDeviceIdRequest> OnLinkNintendoSwitchDeviceIdRequestEvent; public event PlayFabResultEvent<LinkNintendoSwitchDeviceIdResult> OnLinkNintendoSwitchDeviceIdResultEvent; public event PlayFabRequestEvent<LinkOpenIdConnectRequest> OnLinkOpenIdConnectRequestEvent; public event PlayFabResultEvent<EmptyResult> OnLinkOpenIdConnectResultEvent; public event PlayFabRequestEvent<LinkPSNAccountRequest> OnLinkPSNAccountRequestEvent; public event PlayFabResultEvent<LinkPSNAccountResult> OnLinkPSNAccountResultEvent; public event PlayFabRequestEvent<LinkSteamAccountRequest> OnLinkSteamAccountRequestEvent; public event PlayFabResultEvent<LinkSteamAccountResult> OnLinkSteamAccountResultEvent; public event PlayFabRequestEvent<LinkTwitchAccountRequest> OnLinkTwitchRequestEvent; public event PlayFabResultEvent<LinkTwitchAccountResult> OnLinkTwitchResultEvent; public event PlayFabRequestEvent<LinkXboxAccountRequest> OnLinkXboxAccountRequestEvent; public event PlayFabResultEvent<LinkXboxAccountResult> OnLinkXboxAccountResultEvent; public event PlayFabRequestEvent<LoginWithAndroidDeviceIDRequest> OnLoginWithAndroidDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithAppleRequest> OnLoginWithAppleRequestEvent; public event PlayFabRequestEvent<LoginWithCustomIDRequest> OnLoginWithCustomIDRequestEvent; public event PlayFabRequestEvent<LoginWithEmailAddressRequest> OnLoginWithEmailAddressRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookRequest> OnLoginWithFacebookRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookInstantGamesIdRequest> OnLoginWithFacebookInstantGamesIdRequestEvent; public event PlayFabRequestEvent<LoginWithGameCenterRequest> OnLoginWithGameCenterRequestEvent; public event PlayFabRequestEvent<LoginWithGoogleAccountRequest> OnLoginWithGoogleAccountRequestEvent; public event PlayFabRequestEvent<LoginWithIOSDeviceIDRequest> OnLoginWithIOSDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithKongregateRequest> OnLoginWithKongregateRequestEvent; public event PlayFabRequestEvent<LoginWithNintendoServiceAccountRequest> OnLoginWithNintendoServiceAccountRequestEvent; public event PlayFabRequestEvent<LoginWithNintendoSwitchDeviceIdRequest> OnLoginWithNintendoSwitchDeviceIdRequestEvent; public event PlayFabRequestEvent<LoginWithOpenIdConnectRequest> OnLoginWithOpenIdConnectRequestEvent; public event PlayFabRequestEvent<LoginWithPlayFabRequest> OnLoginWithPlayFabRequestEvent; public event PlayFabRequestEvent<LoginWithPSNRequest> OnLoginWithPSNRequestEvent; public event PlayFabRequestEvent<LoginWithSteamRequest> OnLoginWithSteamRequestEvent; public event PlayFabRequestEvent<LoginWithTwitchRequest> OnLoginWithTwitchRequestEvent; public event PlayFabRequestEvent<LoginWithXboxRequest> OnLoginWithXboxRequestEvent; public event PlayFabRequestEvent<MatchmakeRequest> OnMatchmakeRequestEvent; public event PlayFabResultEvent<MatchmakeResult> OnMatchmakeResultEvent; public event PlayFabRequestEvent<OpenTradeRequest> OnOpenTradeRequestEvent; public event PlayFabResultEvent<OpenTradeResponse> OnOpenTradeResultEvent; public event PlayFabRequestEvent<PayForPurchaseRequest> OnPayForPurchaseRequestEvent; public event PlayFabResultEvent<PayForPurchaseResult> OnPayForPurchaseResultEvent; public event PlayFabRequestEvent<PurchaseItemRequest> OnPurchaseItemRequestEvent; public event PlayFabResultEvent<PurchaseItemResult> OnPurchaseItemResultEvent; public event PlayFabRequestEvent<RedeemCouponRequest> OnRedeemCouponRequestEvent; public event PlayFabResultEvent<RedeemCouponResult> OnRedeemCouponResultEvent; public event PlayFabRequestEvent<RefreshPSNAuthTokenRequest> OnRefreshPSNAuthTokenRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnRefreshPSNAuthTokenResultEvent; public event PlayFabRequestEvent<RegisterForIOSPushNotificationRequest> OnRegisterForIOSPushNotificationRequestEvent; public event PlayFabResultEvent<RegisterForIOSPushNotificationResult> OnRegisterForIOSPushNotificationResultEvent; public event PlayFabRequestEvent<RegisterPlayFabUserRequest> OnRegisterPlayFabUserRequestEvent; public event PlayFabResultEvent<RegisterPlayFabUserResult> OnRegisterPlayFabUserResultEvent; public event PlayFabRequestEvent<RemoveContactEmailRequest> OnRemoveContactEmailRequestEvent; public event PlayFabResultEvent<RemoveContactEmailResult> OnRemoveContactEmailResultEvent; public event PlayFabRequestEvent<RemoveFriendRequest> OnRemoveFriendRequestEvent; public event PlayFabResultEvent<RemoveFriendResult> OnRemoveFriendResultEvent; public event PlayFabRequestEvent<RemoveGenericIDRequest> OnRemoveGenericIDRequestEvent; public event PlayFabResultEvent<RemoveGenericIDResult> OnRemoveGenericIDResultEvent; public event PlayFabRequestEvent<RemoveSharedGroupMembersRequest> OnRemoveSharedGroupMembersRequestEvent; public event PlayFabResultEvent<RemoveSharedGroupMembersResult> OnRemoveSharedGroupMembersResultEvent; public event PlayFabRequestEvent<ReportAdActivityRequest> OnReportAdActivityRequestEvent; public event PlayFabResultEvent<ReportAdActivityResult> OnReportAdActivityResultEvent; public event PlayFabRequestEvent<DeviceInfoRequest> OnReportDeviceInfoRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnReportDeviceInfoResultEvent; public event PlayFabRequestEvent<ReportPlayerClientRequest> OnReportPlayerRequestEvent; public event PlayFabResultEvent<ReportPlayerClientResult> OnReportPlayerResultEvent; public event PlayFabRequestEvent<RestoreIOSPurchasesRequest> OnRestoreIOSPurchasesRequestEvent; public event PlayFabResultEvent<RestoreIOSPurchasesResult> OnRestoreIOSPurchasesResultEvent; public event PlayFabRequestEvent<RewardAdActivityRequest> OnRewardAdActivityRequestEvent; public event PlayFabResultEvent<RewardAdActivityResult> OnRewardAdActivityResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<SetFriendTagsRequest> OnSetFriendTagsRequestEvent; public event PlayFabResultEvent<SetFriendTagsResult> OnSetFriendTagsResultEvent; public event PlayFabRequestEvent<SetPlayerSecretRequest> OnSetPlayerSecretRequestEvent; public event PlayFabResultEvent<SetPlayerSecretResult> OnSetPlayerSecretResultEvent; public event PlayFabRequestEvent<StartPurchaseRequest> OnStartPurchaseRequestEvent; public event PlayFabResultEvent<StartPurchaseResult> OnStartPurchaseResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<UnlinkAndroidDeviceIDRequest> OnUnlinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkAndroidDeviceIDResult> OnUnlinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkAppleRequest> OnUnlinkAppleRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUnlinkAppleResultEvent; public event PlayFabRequestEvent<UnlinkCustomIDRequest> OnUnlinkCustomIDRequestEvent; public event PlayFabResultEvent<UnlinkCustomIDResult> OnUnlinkCustomIDResultEvent; public event PlayFabRequestEvent<UnlinkFacebookAccountRequest> OnUnlinkFacebookAccountRequestEvent; public event PlayFabResultEvent<UnlinkFacebookAccountResult> OnUnlinkFacebookAccountResultEvent; public event PlayFabRequestEvent<UnlinkFacebookInstantGamesIdRequest> OnUnlinkFacebookInstantGamesIdRequestEvent; public event PlayFabResultEvent<UnlinkFacebookInstantGamesIdResult> OnUnlinkFacebookInstantGamesIdResultEvent; public event PlayFabRequestEvent<UnlinkGameCenterAccountRequest> OnUnlinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<UnlinkGameCenterAccountResult> OnUnlinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<UnlinkGoogleAccountRequest> OnUnlinkGoogleAccountRequestEvent; public event PlayFabResultEvent<UnlinkGoogleAccountResult> OnUnlinkGoogleAccountResultEvent; public event PlayFabRequestEvent<UnlinkIOSDeviceIDRequest> OnUnlinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkIOSDeviceIDResult> OnUnlinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkKongregateAccountRequest> OnUnlinkKongregateRequestEvent; public event PlayFabResultEvent<UnlinkKongregateAccountResult> OnUnlinkKongregateResultEvent; public event PlayFabRequestEvent<UnlinkNintendoServiceAccountRequest> OnUnlinkNintendoServiceAccountRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUnlinkNintendoServiceAccountResultEvent; public event PlayFabRequestEvent<UnlinkNintendoSwitchDeviceIdRequest> OnUnlinkNintendoSwitchDeviceIdRequestEvent; public event PlayFabResultEvent<UnlinkNintendoSwitchDeviceIdResult> OnUnlinkNintendoSwitchDeviceIdResultEvent; public event PlayFabRequestEvent<UnlinkOpenIdConnectRequest> OnUnlinkOpenIdConnectRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUnlinkOpenIdConnectResultEvent; public event PlayFabRequestEvent<UnlinkPSNAccountRequest> OnUnlinkPSNAccountRequestEvent; public event PlayFabResultEvent<UnlinkPSNAccountResult> OnUnlinkPSNAccountResultEvent; public event PlayFabRequestEvent<UnlinkSteamAccountRequest> OnUnlinkSteamAccountRequestEvent; public event PlayFabResultEvent<UnlinkSteamAccountResult> OnUnlinkSteamAccountResultEvent; public event PlayFabRequestEvent<UnlinkTwitchAccountRequest> OnUnlinkTwitchRequestEvent; public event PlayFabResultEvent<UnlinkTwitchAccountResult> OnUnlinkTwitchResultEvent; public event PlayFabRequestEvent<UnlinkXboxAccountRequest> OnUnlinkXboxAccountRequestEvent; public event PlayFabResultEvent<UnlinkXboxAccountResult> OnUnlinkXboxAccountResultEvent; public event PlayFabRequestEvent<UnlockContainerInstanceRequest> OnUnlockContainerInstanceRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerInstanceResultEvent; public event PlayFabRequestEvent<UnlockContainerItemRequest> OnUnlockContainerItemRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerItemResultEvent; public event PlayFabRequestEvent<UpdateAvatarUrlRequest> OnUpdateAvatarUrlRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUpdateAvatarUrlResultEvent; public event PlayFabRequestEvent<UpdateCharacterDataRequest> OnUpdateCharacterDataRequestEvent; public event PlayFabResultEvent<UpdateCharacterDataResult> OnUpdateCharacterDataResultEvent; public event PlayFabRequestEvent<UpdateCharacterStatisticsRequest> OnUpdateCharacterStatisticsRequestEvent; public event PlayFabResultEvent<UpdateCharacterStatisticsResult> OnUpdateCharacterStatisticsResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticsRequest> OnUpdatePlayerStatisticsRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticsResult> OnUpdatePlayerStatisticsResultEvent; public event PlayFabRequestEvent<UpdateSharedGroupDataRequest> OnUpdateSharedGroupDataRequestEvent; public event PlayFabResultEvent<UpdateSharedGroupDataResult> OnUpdateSharedGroupDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<ValidateAmazonReceiptRequest> OnValidateAmazonIAPReceiptRequestEvent; public event PlayFabResultEvent<ValidateAmazonReceiptResult> OnValidateAmazonIAPReceiptResultEvent; public event PlayFabRequestEvent<ValidateGooglePlayPurchaseRequest> OnValidateGooglePlayPurchaseRequestEvent; public event PlayFabResultEvent<ValidateGooglePlayPurchaseResult> OnValidateGooglePlayPurchaseResultEvent; public event PlayFabRequestEvent<ValidateIOSReceiptRequest> OnValidateIOSReceiptRequestEvent; public event PlayFabResultEvent<ValidateIOSReceiptResult> OnValidateIOSReceiptResultEvent; public event PlayFabRequestEvent<ValidateWindowsReceiptRequest> OnValidateWindowsStoreReceiptRequestEvent; public event PlayFabResultEvent<ValidateWindowsReceiptResult> OnValidateWindowsStoreReceiptResultEvent; public event PlayFabRequestEvent<WriteClientCharacterEventRequest> OnWriteCharacterEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteCharacterEventResultEvent; public event PlayFabRequestEvent<WriteClientPlayerEventRequest> OnWritePlayerEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWritePlayerEventResultEvent; public event PlayFabRequestEvent<WriteTitleEventRequest> OnWriteTitleEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteTitleEventResultEvent; } } #endif
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRegionNetworkEndpointGroupsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "regionedb20d96", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionNetworkEndpointGroupsClient client = new RegionNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "regionedb20d96", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionNetworkEndpointGroupsClient client = new RegionNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "regionedb20d96", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionNetworkEndpointGroupsClient client = new RegionNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup response = client.Get(request.Project, request.Region, request.NetworkEndpointGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<RegionNetworkEndpointGroups.RegionNetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionNetworkEndpointGroupRequest request = new GetRegionNetworkEndpointGroupRequest { Region = "regionedb20d96", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionNetworkEndpointGroupsClient client = new RegionNetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup responseCallSettings = await client.GetAsync(request.Project, request.Region, request.NetworkEndpointGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.NetworkEndpointGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using OpenMetaverse; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.InterfaceCommander; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System.Xml; using System.Xml.Serialization; using System.IO; namespace OpenSim.Region.OptionalModules.World.TreePopulator { /// <summary> /// Version 2.02 - Still hacky /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")] public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Commander m_commander = new Commander("tree"); private Scene m_scene; [XmlRootAttribute(ElementName = "Copse", IsNullable = false)] public class Copse { public string m_name; public Boolean m_frozen; public Tree m_tree_type; public int m_tree_quantity; public float m_treeline_low; public float m_treeline_high; public Vector3 m_seed_point; public double m_range; public Vector3 m_initial_scale; public Vector3 m_maximum_scale; public Vector3 m_rate; [XmlIgnore] public Boolean m_planted; [XmlIgnore] public List<UUID> m_trees; public Copse() { } public Copse(string fileName, Boolean planted) { Copse cp = (Copse)DeserializeObject(fileName); this.m_name = cp.m_name; this.m_frozen = cp.m_frozen; this.m_tree_quantity = cp.m_tree_quantity; this.m_treeline_high = cp.m_treeline_high; this.m_treeline_low = cp.m_treeline_low; this.m_range = cp.m_range; this.m_tree_type = cp.m_tree_type; this.m_seed_point = cp.m_seed_point; this.m_initial_scale = cp.m_initial_scale; this.m_maximum_scale = cp.m_maximum_scale; this.m_initial_scale = cp.m_initial_scale; this.m_rate = cp.m_rate; this.m_planted = planted; this.m_trees = new List<UUID>(); } public Copse(string copsedef) { char[] delimiterChars = {':', ';'}; string[] field = copsedef.Split(delimiterChars); this.m_name = field[1].Trim(); this.m_frozen = (copsedef[0] == 'F'); this.m_tree_quantity = int.Parse(field[2]); this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo); this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo); this.m_range = double.Parse(field[5], Culture.NumberFormatInfo); this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]); this.m_seed_point = Vector3.Parse(field[7]); this.m_initial_scale = Vector3.Parse(field[8]); this.m_maximum_scale = Vector3.Parse(field[9]); this.m_rate = Vector3.Parse(field[10]); this.m_planted = true; this.m_trees = new List<UUID>(); } public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees) { this.m_name = name; this.m_frozen = false; this.m_tree_quantity = quantity; this.m_treeline_high = high; this.m_treeline_low = low; this.m_range = range; this.m_tree_type = type; this.m_seed_point = point; this.m_initial_scale = scale; this.m_maximum_scale = max_scale; this.m_rate = rate; this.m_planted = false; this.m_trees = trees; } public override string ToString() { string frozen = (this.m_frozen ? "F" : "A"); return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};", frozen, this.m_name, this.m_tree_quantity, this.m_treeline_high, this.m_treeline_low, this.m_range, this.m_tree_type, this.m_seed_point.ToString(), this.m_initial_scale.ToString(), this.m_maximum_scale.ToString(), this.m_rate.ToString()); } } private List<Copse> m_copse; private double m_update_ms = 1000.0; // msec between updates private bool m_active_trees = false; Timer CalculateTrees; #region ICommandableModule Members public ICommander CommandInterface { get { return m_commander; } } #endregion #region Region Module interface public void Initialise(IConfigSource config) { // ini file settings try { m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees); } catch (Exception) { m_log.Debug("[TREES]: ini failure for active_trees - using default"); } try { m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms); } catch (Exception) { m_log.Debug("[TREES]: ini failure for update_rate - using default"); } InstallCommands(); m_log.Debug("[TREES]: Initialised tree module"); } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleCommander(m_commander); m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { ReloadCopse(); if (m_copse.Count > 0) m_log.Info("[TREES]: Copse load complete"); if (m_active_trees) activeizeTreeze(true); } public void Close() { } public string Name { get { return "TreePopulatorModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion //-------------------------------------------------------------- #region ICommandableModule Members private void HandleTreeActive(Object[] args) { if ((Boolean)args[0] && !m_active_trees) { m_log.InfoFormat("[TREES]: Activating Trees"); m_active_trees = true; activeizeTreeze(m_active_trees); } else if (!(Boolean)args[0] && m_active_trees) { m_log.InfoFormat("[TREES]: Trees module is no longer active"); m_active_trees = false; activeizeTreeze(m_active_trees); } else { m_log.InfoFormat("[TREES]: Trees module is already in the required state"); } } private void HandleTreeFreeze(Object[] args) { string copsename = ((string)args[0]).Trim(); Boolean freezeState = (Boolean) args[1]; foreach (Copse cp in m_copse) { if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)) { cp.m_frozen = freezeState; foreach (UUID tree in cp.m_trees) { SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM")); sop.ParentGroup.HasGroupChanged = true; } m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState); return; } else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState)) { m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename); return; } } m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename); } private void HandleTreeLoad(Object[] args) { Copse copse; m_log.InfoFormat("[TREES]: Loading copse definition...."); copse = new Copse(((string)args[0]), false); foreach (Copse cp in m_copse) { if (cp.m_name == copse.m_name) { m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name); return; } } m_copse.Add(copse); m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString()); } private void HandleTreePlant(Object[] args) { string copsename = ((string)args[0]).Trim(); m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename); UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner; foreach (Copse copse in m_copse) { if (copse.m_name == copsename) { if (!copse.m_planted) { // The first tree for a copse is created here CreateTree(uuid, copse, copse.m_seed_point); copse.m_planted = true; return; } else { m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename); } } } m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename); } private void HandleTreeRate(Object[] args) { m_update_ms = (double)args[0]; if (m_update_ms >= 1000.0) { if (m_active_trees) { activeizeTreeze(false); activeizeTreeze(true); } m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms); } else { m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed"); } } private void HandleTreeReload(Object[] args) { if (m_active_trees) { CalculateTrees.Stop(); } ReloadCopse(); if (m_active_trees) { CalculateTrees.Start(); } } private void HandleTreeRemove(Object[] args) { string copsename = ((string)args[0]).Trim(); Copse copseIdentity = null; foreach (Copse cp in m_copse) { if (cp.m_name == copsename) { copseIdentity = cp; } } if (copseIdentity != null) { foreach (UUID tree in copseIdentity.m_trees) { if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; // Delete tree and alert clients (not silent) m_scene.DeleteSceneObject(selectedTree.ParentGroup, false); } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } copseIdentity.m_trees = new List<UUID>(); m_copse.Remove(copseIdentity); m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename); } else { m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename); } } private void HandleTreeStatistics(Object[] args) { m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms); foreach (Copse cp in m_copse) { m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen); } } private void InstallCommands() { Command treeActiveCommand = new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module"); treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean"); Command treeFreezeCommand = new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse"); treeFreezeCommand.AddArgument("copse", "The required copse", "String"); treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean"); Command treeLoadCommand = new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file"); treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String"); Command treePlantCommand = new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse"); treePlantCommand.AddArgument("copse", "The required copse", "String"); Command treeRateCommand = new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)"); treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double"); Command treeReloadCommand = new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees"); Command treeRemoveCommand = new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees"); treeRemoveCommand.AddArgument("copse", "The required copse", "String"); Command treeStatisticsCommand = new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees"); m_commander.RegisterCommand("active", treeActiveCommand); m_commander.RegisterCommand("freeze", treeFreezeCommand); m_commander.RegisterCommand("load", treeLoadCommand); m_commander.RegisterCommand("plant", treePlantCommand); m_commander.RegisterCommand("rate", treeRateCommand); m_commander.RegisterCommand("reload", treeReloadCommand); m_commander.RegisterCommand("remove", treeRemoveCommand); m_commander.RegisterCommand("statistics", treeStatisticsCommand); } /// <summary> /// Processes commandline input. Do not call directly. /// </summary> /// <param name="args">Commandline arguments</param> private void EventManager_OnPluginConsole(string[] args) { if (args[0] == "tree") { if (args.Length == 1) { m_commander.ProcessConsoleCommand("help", new string[0]); return; } string[] tmpArgs = new string[args.Length - 2]; int i; for (i = 2; i < args.Length; i++) { tmpArgs[i - 2] = args[i]; } m_commander.ProcessConsoleCommand(args[1], tmpArgs); } } #endregion #region IVegetationModule Members public SceneObjectGroup AddTree( UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree) { PrimitiveBaseShape treeShape = new PrimitiveBaseShape(); treeShape.PathCurve = 16; treeShape.PathEnd = 49900; treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree; treeShape.Scale = scale; treeShape.State = (byte)treeType; return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape); } #endregion #region IEntityCreator Members protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree }; public PCode[] CreationCapabilities { get { return creationCapabilities; } } public SceneObjectGroup CreateEntity( UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) { if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0) { m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name); return null; } SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape); SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID); rootPart.AddFlag(PrimFlags.Phantom); sceneObject.SetGroup(groupID, null); m_scene.AddNewSceneObject(sceneObject, true); sceneObject.InvalidateEffectivePerms(); return sceneObject; } #endregion //-------------------------------------------------------------- #region Tree Utilities static public void SerializeObject(string fileName, Object obj) { try { XmlSerializer xs = new XmlSerializer(typeof(Copse)); using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8)) { writer.Formatting = Formatting.Indented; xs.Serialize(writer, obj); } } catch (SystemException ex) { throw new ApplicationException("Unexpected failure in Tree serialization", ex); } } static public object DeserializeObject(string fileName) { try { XmlSerializer xs = new XmlSerializer(typeof(Copse)); using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) return xs.Deserialize(fs); } catch (SystemException ex) { throw new ApplicationException("Unexpected failure in Tree de-serialization", ex); } } private void ReloadCopse() { m_copse = new List<Copse>(); EntityBase[] objs = m_scene.GetEntities(); foreach (EntityBase obj in objs) { if (obj is SceneObjectGroup) { SceneObjectGroup grp = (SceneObjectGroup)obj; if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:")) { // Create a new copse definition or add uuid to an existing definition try { Boolean copsefound = false; Copse copse = new Copse(grp.Name); foreach (Copse cp in m_copse) { if (cp.m_name == copse.m_name) { copsefound = true; cp.m_trees.Add(grp.UUID); //m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID); } } if (!copsefound) { m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name); m_copse.Add(copse); copse.m_trees.Add(grp.UUID); } } catch { m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name); } } } } } #endregion private void activeizeTreeze(bool activeYN) { if (activeYN) { CalculateTrees = new Timer(m_update_ms); CalculateTrees.Elapsed += CalculateTrees_Elapsed; CalculateTrees.Start(); } else { CalculateTrees.Stop(); } } private void growTrees() { foreach (Copse copse in m_copse) { if (!copse.m_frozen) { foreach (UUID tree in copse.m_trees) { if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z) { s_tree.Scale += copse.m_rate; s_tree.ParentGroup.HasGroupChanged = true; s_tree.ScheduleFullUpdate(); } } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } } } } private void seedTrees() { foreach (Copse copse in m_copse) { if (!copse.m_frozen) { foreach (UUID tree in copse.m_trees) { if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; if (copse.m_trees.Count < copse.m_tree_quantity) { // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0) { if (Util.RandomClass.NextDouble() > 0.75) { SpawnChild(copse, s_tree); } } } } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } } } } private void killTrees() { foreach (Copse copse in m_copse) { if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity) { foreach (UUID tree in copse.m_trees) { double killLikelyhood = 0.0; if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) + Math.Pow(selectedTree.Scale.Y, 2) + Math.Pow(selectedTree.Scale.Z, 2)); foreach (UUID picktree in copse.m_trees) { if (picktree != tree) { SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart; double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) + Math.Pow(pickedTree.Scale.Y, 2) + Math.Pow(pickedTree.Scale.Z, 2)); double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition); killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1; } } if (Util.RandomClass.NextDouble() < killLikelyhood) { // Delete tree and alert clients (not silent) m_scene.DeleteSceneObject(selectedTree.ParentGroup, false); copse.m_trees.Remove(selectedTree.ParentGroup.UUID); break; } } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } } } } private void SpawnChild(Copse copse, SceneObjectPart s_tree) { Vector3 position = new Vector3(); double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); position.X = s_tree.AbsolutePosition.X + (float)randX; position.Y = s_tree.AbsolutePosition.Y + (float)randY; if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 && position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 && Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range) { UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner; CreateTree(uuid, copse, position); } } private void CreateTree(UUID uuid, Copse copse, Vector3 position) { position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y]; if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high) { SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false); tree.Name = copse.ToString(); copse.m_trees.Add(tree.UUID); tree.SendGroupFullUpdate(); } } private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e) { growTrees(); seedTrees(); killTrees(); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using Commands.Storage.ScenarioTest.Common; using Commands.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using MS.Test.Common.MsTestLib; using StorageTestLib; using StorageBlob = Microsoft.WindowsAzure.Storage.Blob; namespace Commands.Storage.ScenarioTest.BVT.HTTPS { /// <summary> /// bvt cases for anonymous storage account /// </summary> [TestClass] class AnonymousBVT : TestBase { protected static string downloadDirRoot; private static string ContainerPrefix = "anonymousbvt"; protected static string StorageAccountName; protected static string StorageEndPoint; protected static bool useHttps; [ClassInitialize()] public static void AnonymousBVTClassInitialize(TestContext testContext) { TestBase.TestClassInitialize(testContext); CLICommonBVT.SaveAndCleanSubScriptionAndEnvConnectionString(); StorageAccountName = Test.Data.Get("StorageAccountName"); StorageEndPoint = Test.Data.Get("StorageEndPoint").Trim(); useHttps = true; PowerShellAgent.SetAnonymousStorageContext(StorageAccountName, useHttps, StorageEndPoint); downloadDirRoot = Test.Data.Get("DownloadDir"); SetupDownloadDir(); } [ClassCleanup()] public static void AnonymousBVTClassCleanup() { FileUtil.CleanDirectory(downloadDirRoot); CLICommonBVT.RestoreSubScriptionAndEnvConnectionString(); TestBase.TestClassCleanup(); } /// <summary> /// create download dir /// </summary> //TODO remove code redundancy protected static void SetupDownloadDir() { if (!Directory.Exists(downloadDirRoot)) { Directory.CreateDirectory(downloadDirRoot); } FileUtil.CleanDirectory(downloadDirRoot); } [TestMethod] [TestCategory(Tag.BVT)] public void ListContainerWithContianerPermission() { string containerName = Utility.GenNameString(ContainerPrefix); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName, StorageBlob.BlobContainerPublicAccessType.Container); try { Test.Assert(agent.GetAzureStorageContainer(containerName), Utility.GenComparisonData("GetAzureStorageContainer", true)); Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Container, containerName); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>> { dic }; //remove the permssion information for anonymous storage account CloudBlobUtil.PackContainerCompareData(container, dic); dic["PublicAccess"] = null; dic["Permission"] = null; // Verification for returned values agent.OutputValidation(comp); //check the http or https usage StorageBlob.CloudBlobContainer retrievedContainer = (StorageBlob.CloudBlobContainer)agent.Output[0]["CloudBlobContainer"]; ; string uri = retrievedContainer.Uri.ToString(); string uriPrefix = string.Empty; if (useHttps) { uriPrefix = "https"; } else { uriPrefix = "http"; } Test.Assert(uri.ToString().StartsWith(uriPrefix), string.Format("The prefix of container uri should be {0}, actually it's {1}", uriPrefix, uri)); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// list blobs when container's public access level is public /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void ListBlobsWithBlobPermission() { string containerName = Utility.GenNameString(ContainerPrefix); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName, StorageBlob.BlobContainerPublicAccessType.Blob); try { string pageBlobName = Utility.GenNameString("pageblob"); string blockBlobName = Utility.GenNameString("blockblob"); StorageBlob.ICloudBlob blockBlob = blobUtil.CreateBlockBlob(container, blockBlobName); StorageBlob.ICloudBlob pageBlob = blobUtil.CreatePageBlob(container, pageBlobName); Test.Assert(agent.GetAzureStorageBlob(blockBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(new List<StorageBlob.ICloudBlob> { blockBlob }); Test.Assert(agent.GetAzureStorageBlob(pageBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(new List<StorageBlob.ICloudBlob> { pageBlob }); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// download blob when container's public access level is container /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetBlobContentWithContainerPermission() { string containerName = Utility.GenNameString(ContainerPrefix); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName, StorageBlob.BlobContainerPublicAccessType.Container); try { DownloadBlobFromContainerTest(container); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// download blob when container's public access level is blob /// </summary> [TestMethod] [TestCategory(Tag.BVT)] public void GetBlobContentWithBlobPermission() { string containerName = Utility.GenNameString(ContainerPrefix); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName, StorageBlob.BlobContainerPublicAccessType.Blob); try { DownloadBlobFromContainerTest(container); } finally { blobUtil.RemoveContainer(containerName); } } /// <summary> /// download test in specified container /// </summary> /// <param name="container">CloudBlobContainer object</param> private void DownloadBlobFromContainerTest(StorageBlob.CloudBlobContainer container) { DownloadBlobFromContainer(container, StorageBlob.BlobType.BlockBlob); DownloadBlobFromContainer(container, StorageBlob.BlobType.PageBlob); } /// <summary> /// download specified blob /// </summary> /// <param name="container"></param> /// <param name="blob"></param> private void DownloadBlobFromContainer(StorageBlob.CloudBlobContainer container, StorageBlob.BlobType type) { string blobName = Utility.GenNameString("blob"); StorageBlob.ICloudBlob blob = blobUtil.CreateBlob(container, blobName, type); string filePath = Path.Combine(downloadDirRoot, blob.Name); Test.Assert(agent.GetAzureStorageBlobContent(blob.Name, filePath, container.Name, true), "download blob should be successful"); string localMd5 = Helper.GetFileContentMD5(filePath); Test.Assert(localMd5 == blob.Properties.ContentMD5, string.Format("local content md5 should be {0}, and actualy it's {1}", blob.Properties.ContentMD5, localMd5)); agent.OutputValidation(new List<StorageBlob.ICloudBlob> { blob }); } [TestMethod()] [TestCategory(Tag.BVT)] public void MakeSureBvtUsingAnonymousContext() { //TODO EnvKey is not empty since we called SaveAndCleanSubScriptionAndEnvConnectionString when initializing string key = System.Environment.GetEnvironmentVariable(CLICommonBVT.EnvKey); Test.Assert(string.IsNullOrEmpty(key), string.Format("env connection string {0} should be null or empty", key)); Test.Assert(PowerShellAgent.Context != null, "PowerShell context should be not null when running bvt against Anonymous storage account"); } /// <summary> /// Anonymous storage context should work with specified end point /// </summary> [TestMethod()] [TestCategory(Tag.BVT)] public void AnonymousContextWithEndPoint() { string containerName = Utility.GenNameString(ContainerPrefix); StorageBlob.CloudBlobContainer container = blobUtil.CreateContainer(containerName, StorageBlob.BlobContainerPublicAccessType.Blob); try { string pageBlobName = Utility.GenNameString("pageblob"); string blockBlobName = Utility.GenNameString("blockblob"); StorageBlob.ICloudBlob blockBlob = blobUtil.CreateBlockBlob(container, blockBlobName); StorageBlob.ICloudBlob pageBlob = blobUtil.CreatePageBlob(container, pageBlobName); agent.UseContextParam = false; string cmd = string.Format("new-azurestoragecontext -StorageAccountName {0} " + "-Anonymous -EndPoint {1}", StorageAccountName, StorageEndPoint); ((PowerShellAgent)agent).AddPipelineScript(cmd); Test.Assert(agent.GetAzureStorageBlob(blockBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(new List<StorageBlob.ICloudBlob> { blockBlob }); ((PowerShellAgent)agent).AddPipelineScript(cmd); Test.Assert(agent.GetAzureStorageBlob(pageBlobName, containerName), Utility.GenComparisonData("Get-AzureStorageBlob", true)); agent.OutputValidation(new List<StorageBlob.ICloudBlob> { pageBlob }); } finally { blobUtil.RemoveContainer(containerName); } } } }
#region License //============================================================================= // Velox.DB - Portable .NET ORM // // Copyright (c) 2015 Philippe Leybaert // // 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; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Velox.DB.Core; using Velox.DB.Sql; namespace Velox.DB { internal sealed class DataSet<T> : IDataSet<T> { private readonly Repository<T> _repository; private readonly FilterSpec _filter; private readonly SortOrderSpec _sortOrder; private readonly List<Expression<Func<T, object>>> _relationsToLoad; private int? _skip; private int? _take; private readonly OrmSchema.Relation _parentRelation; private readonly object _parentObject; public DataSet(Repository repository) { _repository = (Repository<T>) repository; } [Preserve] public DataSet(Repository repository, FilterSpec filter) { _repository = (Repository<T>)repository; _filter = filter; } [Preserve] public DataSet(Repository repository, FilterSpec filter, OrmSchema.Relation parentRelation, object parentObject) { _repository = (Repository<T>)repository; _filter = filter; _parentRelation = parentRelation; _parentObject = parentObject; } private DataSet(DataSet<T> baseDataSet, FilterSpec newFilterSpec = null, SortOrderSpec newSortSpec = null, IEnumerable<Expression<Func<T,object>>> additionalRelations = null) { _repository = baseDataSet._repository; _skip = baseDataSet._skip; _take = baseDataSet._take; _filter = newFilterSpec ?? baseDataSet._filter; _sortOrder = newSortSpec ?? baseDataSet._sortOrder; if (baseDataSet._relationsToLoad != null) _relationsToLoad = new List<Expression<Func<T, object>>>(baseDataSet._relationsToLoad); if (additionalRelations != null) { if (_relationsToLoad == null) _relationsToLoad = new List<Expression<Func<T, object>>>(additionalRelations); else _relationsToLoad.AddRange(additionalRelations); } _parentRelation = baseDataSet._parentRelation; _parentObject = baseDataSet._parentObject; } public IAsyncDataSet<T> Async() { return new AsyncDataSet<T>(this); } public IDataSet<T> Where(Expression<Func<T, bool>> whereExpression) { return new DataSet<T>(this, newFilterSpec: new FilterSpec(whereExpression, _filter)); } public IDataSet<T> OrderBy<TKey>(Expression<Func<T, TKey>> keySelector) { return new DataSet<T>(this, newSortSpec: new SortOrderSpec(keySelector,SortOrder.Ascending, _sortOrder)); } public IDataSet<T> OrderByDescending<TKey>(Expression<Func<T, TKey>> keySelector) { return new DataSet<T>(this, newSortSpec: new SortOrderSpec(keySelector, SortOrder.Descending, _sortOrder)); } public IDataSet<T> ThenBy<TKey>(Expression<Func<T, TKey>> keySelector) { return new DataSet<T>(this, newSortSpec: new SortOrderSpec(keySelector, SortOrder.Ascending, _sortOrder)); } public IDataSet<T> ThenByDescending<TKey>(Expression<Func<T, TKey>> keySelector) { return new DataSet<T>(this, newSortSpec: new SortOrderSpec(keySelector, SortOrder.Descending, _sortOrder)); } public IDataSet<T> OrderBy(QueryExpression expression, SortOrder sortOrder) { return new DataSet<T>(this, newSortSpec: new SortOrderSpec(expression, sortOrder, _sortOrder)); } public IEnumerator<T> GetEnumerator() { return _repository.List(_repository.CreateQuerySpec(_filter, sortSpec: _sortOrder, skip:_skip, take:_take), _relationsToLoad, _parentRelation, _parentObject).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Purge() { _repository.Purge(); } public T Read(object key, params Expression<Func<T, object>>[] relationsToLoad) { return _repository.Read(key,relationsToLoad); } public T Read(Expression<Func<T, bool>> condition, params Expression<Func<T, object>>[] relationsToLoad) { return WithRelations(relationsToLoad).FirstOrDefault(condition); } public T Load(T obj, object key, params Expression<Func<T, object>>[] relationsToLoad) { return _repository.Load(obj, key, relationsToLoad); } public bool Save(T obj, bool saveRelations = false, bool? create = null) { return _repository.Save(obj, saveRelations, create); } public bool InsertOrUpdate(T obj, bool saveRelations = false) { return _repository.Save(obj, saveRelations, create:null); } public bool Insert(T obj, bool saveRelations = false) { return _repository.Save(obj, saveRelations, create: true); } public bool Update(T obj, bool saveRelations = false) { return _repository.Save(obj, saveRelations, create: false); } public bool Delete(T obj) { return _repository.Delete(obj); } public bool DeleteAll() { return _repository.Delete(_repository.CreateQuerySpec(_filter)); } public bool Delete(Expression<Func<T, bool>> filter) { return Where(filter).DeleteAll(); } public bool Delete(QueryExpression filterExpression) { return _repository.Delete(_repository.CreateQuerySpec(new FilterSpec(filterExpression))); } public IDataSet<T> WithRelations(params Expression<Func<T, object>>[] relationsToLoad) { return new DataSet<T>(this, additionalRelations: relationsToLoad); } public IDataSet<T> Where(QueryExpression filterExpression) { return new DataSet<T>(this, newFilterSpec: new FilterSpec(filterExpression)); } public IDataSet<T> Skip(int n) { n += _skip ?? 0; return new DataSet<T>(this) {_skip = n}; } public IDataSet<T> Take(int n) { return new DataSet<T>(this) { _take = Math.Min(n,_take ?? int.MaxValue) }; } public T First() { return _repository.List(_repository.CreateQuerySpec(_filter, sortSpec: _sortOrder, skip: _skip, take: 1), _relationsToLoad, _parentRelation, _parentObject).First(); } public T First(Expression<Func<T, bool>> filter) { return _repository.List(_repository.CreateQuerySpec(new FilterSpec(filter, _filter), sortSpec: _sortOrder, skip: _skip, take: 1), _relationsToLoad, _parentRelation, _parentObject).First(); } public T FirstOrDefault() { return _repository.List(_repository.CreateQuerySpec(_filter, sortSpec: _sortOrder, skip: _skip, take: 1), _relationsToLoad, _parentRelation, _parentObject).FirstOrDefault(); } public T FirstOrDefault(Expression<Func<T, bool>> filter) { return _repository.List(_repository.CreateQuerySpec(new FilterSpec(filter, _filter), sortSpec: _sortOrder, skip: _skip, take: 1), _relationsToLoad, _parentRelation, _parentObject).FirstOrDefault(); } public long Count() { return _repository.GetAggregate<long>(Aggregate.Count, _repository.CreateQuerySpec(_filter)); } public long Count(Expression<Func<T, bool>> filter) { return _repository.GetAggregate<long>(Aggregate.Count, _repository.CreateQuerySpec(new FilterSpec(filter, _filter))); } public TScalar Max<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return _repository.GetAggregate<TScalar>(Aggregate.Max, _repository.CreateQuerySpec(new FilterSpec(filter, _filter),new ScalarSpec(expression))); } public TScalar Min<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return _repository.GetAggregate<TScalar>(Aggregate.Min, _repository.CreateQuerySpec(new FilterSpec(filter, _filter), new ScalarSpec(expression))); } public TScalar Sum<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return _repository.GetAggregate<TScalar>(Aggregate.Sum, _repository.CreateQuerySpec(new FilterSpec(filter, _filter), new ScalarSpec(expression))); } public bool All(Expression<Func<T, bool>> filter) { return Count(Expression.Lambda<Func<T, bool>>(Expression.Not(filter.Body), filter.Parameters[0])) == 0; } public TScalar Max<TScalar>(Expression<Func<T, TScalar>> expression) { return _repository.GetAggregate<TScalar>(Aggregate.Max, _repository.CreateQuerySpec(_filter, new ScalarSpec(expression))); } public TScalar Min<TScalar>(Expression<Func<T, TScalar>> expression) { return _repository.GetAggregate<TScalar>(Aggregate.Min, _repository.CreateQuerySpec(_filter, new ScalarSpec(expression))); } public TScalar Sum<TScalar>(Expression<Func<T, TScalar>> expression) { return _repository.GetAggregate<TScalar>(Aggregate.Sum, _repository.CreateQuerySpec(_filter, new ScalarSpec(expression))); } public TScalar Average<TScalar>(Expression<Func<T, TScalar>> expression) { return _repository.GetAggregate<TScalar>(Aggregate.Average, _repository.CreateQuerySpec(_filter, new ScalarSpec(expression))); } public bool Any() { return _repository.GetAggregate<bool>(Aggregate.Any, _repository.CreateQuerySpec(_filter)); } public TScalar Average<TScalar>(Expression<Func<T, TScalar>> expression, Expression<Func<T, bool>> filter) { return _repository.GetAggregate<TScalar>(Aggregate.Average, _repository.CreateQuerySpec(new FilterSpec(filter, _filter), new ScalarSpec(expression))); } public bool Any(Expression<Func<T, bool>> filter) { return _repository.GetAggregate<bool>(Aggregate.Any, _repository.CreateQuerySpec(new FilterSpec(filter, _filter))); } public T ElementAt(int index) { return Skip(index).Take(1).FirstOrDefault(); } public Vx.IEvents<T> Events => _repository.Events; } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using ServiceStack.Logging; using ServiceStack.Net30.Collections.Concurrent; namespace ServiceStack.CacheAccess.Providers { public class MemoryCacheClient : ICacheClient, IRemoveByPattern { private static readonly ILog Log = LogManager.GetLogger(typeof (MemoryCacheClient)); private ConcurrentDictionary<string, CacheEntry> memory; private ConcurrentDictionary<string, int> counters; public bool FlushOnDispose { get; set; } private class CacheEntry { private object cacheValue; /// <summary> /// Create new instance of CacheEntry. /// </summary> /// <param name="value">The value being cached.</param> /// <param name="expiresAt">The UTC time at which CacheEntry expires.</param> public CacheEntry(object value, DateTime expiresAt) { Value = value; ExpiresAt = expiresAt; LastModifiedTicks = DateTime.UtcNow.Ticks; } /// <summary>UTC time at which CacheEntry expires.</summary> internal DateTime ExpiresAt { get; set; } internal object Value { get { return cacheValue; } set { cacheValue = value; LastModifiedTicks = DateTime.UtcNow.Ticks; } } internal long LastModifiedTicks { get; private set; } } public MemoryCacheClient() { this.memory = new ConcurrentDictionary<string, CacheEntry>(); this.counters = new ConcurrentDictionary<string, int>(); } /// <summary> /// Add value with specified key to the cache, and set the cache entry to never expire. /// </summary> /// <param name="key">Key associated with value.</param> /// <param name="value">Value being cached.</param> /// <returns></returns> private bool CacheAdd(string key, object value) { return CacheAdd(key, value, DateTime.MaxValue); } private bool TryGetValue(string key, out CacheEntry entry) { return this.memory.TryGetValue(key, out entry); } private void Set(string key, CacheEntry entry) { this.memory[key] = entry; } /// <summary> /// Stores The value with key only if such key doesn't exist at the server yet. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="expiresAt">The UTC DateTime at which the cache entry expires.</param> /// <returns></returns> private bool CacheAdd(string key, object value, DateTime expiresAt) { CacheEntry entry; if (this.TryGetValue(key, out entry)) return false; entry = new CacheEntry(value, expiresAt); this.Set(key, entry); return true; } /// <summary> /// Adds or replaces the value with key, and sets the cache entry to never expire. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns></returns> private bool CacheSet(string key, object value) { return CacheSet(key, value, DateTime.MaxValue); } /// <summary> /// Adds or replaces the value with key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="expiresAt">The UTC DateTime at which the cache entry expires.</param> /// <returns></returns> private bool CacheSet(string key, object value, DateTime expiresAt) { return CacheSet(key, value, expiresAt, null); } /// <summary> /// Adds or replaces the value with key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="expiresAt">The UTC DateTime at which the cache entry expires.</param> /// <param name="checkLastModified">The check last modified.</param> /// <returns>True; if it succeeded</returns> private bool CacheSet(string key, object value, DateTime expiresAt, long? checkLastModified) { CacheEntry entry; if (!this.TryGetValue(key, out entry)) { entry = new CacheEntry(value, expiresAt); this.Set(key, entry); return true; } if (checkLastModified.HasValue && entry.LastModifiedTicks != checkLastModified.Value) return false; entry.Value = value; entry.ExpiresAt = expiresAt; return true; } /// <summary> /// Replace the value with specified key if it exists, and set the cache entry to never expire. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value to be cached.</param> /// <returns></returns> private bool CacheReplace(string key, object value) { return CacheReplace(key, value, DateTime.MaxValue); } /// <summary> /// Replace the value with specified key if it exists. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value to be cached.</param> /// <param name="expiresAt">The UTC DateTime at which the cache entry expires.</param> /// <returns></returns> private bool CacheReplace(string key, object value, DateTime expiresAt) { return !CacheSet(key, value, expiresAt); } public void Dispose() { if (!FlushOnDispose) return; this.memory = new ConcurrentDictionary<string, CacheEntry>(); this.counters = new ConcurrentDictionary<string, int>(); } public bool Remove(string key) { CacheEntry item; return this.memory.TryRemove(key, out item); } public void RemoveAll(IEnumerable<string> keys) { foreach (var key in keys) { try { this.Remove(key); } catch (Exception ex) { Log.Error(string.Format("Error trying to remove {0} from the cache", key), ex); } } } public object Get(string key) { long lastModifiedTicks; return Get(key, out lastModifiedTicks); } public object Get(string key, out long lastModifiedTicks) { lastModifiedTicks = 0; CacheEntry cacheEntry; if (this.memory.TryGetValue(key, out cacheEntry)) { if (cacheEntry.ExpiresAt < DateTime.UtcNow) { this.memory.TryRemove(key, out cacheEntry); return null; } lastModifiedTicks = cacheEntry.LastModifiedTicks; return cacheEntry.Value; } return null; } public T Get<T>(string key) { var value = Get(key); if (value != null) return (T)value; return default(T); } private int UpdateCounter(string key, int value) { if (!this.counters.ContainsKey(key)) { this.counters[key] = 0; } this.counters[key] += value; return this.counters[key]; } public long Increment(string key, uint amount) { return UpdateCounter(key, (int)amount); } public long Decrement(string key, uint amount) { return UpdateCounter(key, (int)amount * -1); } /// <summary> /// Add the value with key to the cache, set to never expire. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <returns>True if Add succeeds, otherwise false.</returns> public bool Add<T>(string key, T value) { return CacheAdd(key, value); } /// <summary> /// Add or replace the value with key to the cache, set to never expire. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <returns>True if Set succeeds, otherwise false.</returns> public bool Set<T>(string key, T value) { return CacheSet(key, value); } /// <summary> /// Replace the value with key in the cache, set to never expire. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <returns>True if Replace succeeds, otherwise false.</returns> public bool Replace<T>(string key, T value) { return CacheReplace(key, value); } /// <summary> /// Add the value with key to the cache, set to expire at specified DateTime. /// </summary> /// <remarks>This method examines the DateTimeKind of expiresAt to determine if conversion to /// universal time is needed. The version of Add that takes a TimeSpan expiration is faster /// than using this method with a DateTime of Kind other than Utc, and is not affected by /// ambiguous local time during daylight savings/standard time transition.</remarks> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <param name="expiresAt">The DateTime at which the cache entry expires.</param> /// <returns>True if Add succeeds, otherwise false.</returns> public bool Add<T>(string key, T value, DateTime expiresAt) { if (expiresAt.Kind != DateTimeKind.Utc) expiresAt = expiresAt.ToUniversalTime(); return CacheAdd(key, value, expiresAt); } /// <summary> /// Add or replace the value with key to the cache, set to expire at specified DateTime. /// </summary> /// <remarks>This method examines the DateTimeKind of expiresAt to determine if conversion to /// universal time is needed. The version of Set that takes a TimeSpan expiration is faster /// than using this method with a DateTime of Kind other than Utc, and is not affected by /// ambiguous local time during daylight savings/standard time transition.</remarks> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <param name="expiresAt">The DateTime at which the cache entry expires.</param> /// <returns>True if Set succeeds, otherwise false.</returns> public bool Set<T>(string key, T value, DateTime expiresAt) { if (expiresAt.Kind != DateTimeKind.Utc) expiresAt = expiresAt.ToUniversalTime(); return CacheSet(key, value, expiresAt); } /// <summary> /// Replace the value with key in the cache, set to expire at specified DateTime. /// </summary> /// <remarks>This method examines the DateTimeKind of expiresAt to determine if conversion to /// universal time is needed. The version of Replace that takes a TimeSpan expiration is faster /// than using this method with a DateTime of Kind other than Utc, and is not affected by /// ambiguous local time during daylight savings/standard time transition.</remarks> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <param name="expiresAt">The DateTime at which the cache entry expires.</param> /// <returns>True if Replace succeeds, otherwise false.</returns> public bool Replace<T>(string key, T value, DateTime expiresAt) { if (expiresAt.Kind != DateTimeKind.Utc) expiresAt = expiresAt.ToUniversalTime(); return CacheReplace(key, value, expiresAt); } /// <summary> /// Add the value with key to the cache, set to expire after specified TimeSpan. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <param name="expiresIn">The TimeSpan at which the cache entry expires.</param> /// <returns>True if Add succeeds, otherwise false.</returns> public bool Add<T>(string key, T value, TimeSpan expiresIn) { return CacheAdd(key, value, DateTime.UtcNow.Add(expiresIn)); } /// <summary> /// Add or replace the value with key to the cache, set to expire after specified TimeSpan. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <param name="expiresIn">The TimeSpan at which the cache entry expires.</param> /// <returns>True if Set succeeds, otherwise false.</returns> public bool Set<T>(string key, T value, TimeSpan expiresIn) { return CacheSet(key, value, DateTime.UtcNow.Add(expiresIn)); } /// <summary> /// Replace the value with key in the cache, set to expire after specified TimeSpan. /// </summary> /// <param name="key">The key of the cache entry.</param> /// <param name="value">The value being cached.</param> /// <param name="expiresIn">The TimeSpan at which the cache entry expires.</param> /// <returns>True if Replace succeeds, otherwise false.</returns> public bool Replace<T>(string key, T value, TimeSpan expiresIn) { return CacheReplace(key, value, DateTime.UtcNow.Add(expiresIn)); } public void FlushAll() { this.memory = new ConcurrentDictionary<string, CacheEntry>(); } public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys) { var valueMap = new Dictionary<string, T>(); foreach (var key in keys) { var value = Get<T>(key); valueMap[key] = value; } return valueMap; } public void SetAll<T>(IDictionary<string, T> values) { foreach (var entry in values) { Set(entry.Key, entry.Value); } } public void RemoveByPattern(string pattern) { RemoveByRegex(pattern.Replace("*", ".*").Replace("?", ".+")); } public void RemoveByRegex(string pattern) { var regex = new Regex(pattern); var enumerator = this.memory.GetEnumerator(); try { while (enumerator.MoveNext()) { var current = enumerator.Current; if (regex.IsMatch(current.Key)) { this.Remove(current.Key); } } } catch (Exception ex) { Log.Error(string.Format("Error trying to remove items from cache with this {0} pattern", pattern), ex); } } } }
/* * 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 OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.Timers; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Collect statistics from the scene to send to the client and for access by other monitoring tools. /// </summary> /// <remarks> /// FIXME: This should be a monitoring region module /// </remarks> public class SimStatsReporter { private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public const string LastReportedObjectUpdateStatName = "LastReportedObjectUpdates"; public const string SlowFramesStatName = "SlowFrames"; public delegate void SendStatResult(SimStats stats); public delegate void YourStatsAreWrong(); public event SendStatResult OnSendStatsResult; public event YourStatsAreWrong OnStatsIncorrect; private SendStatResult handlerSendStatResult; private YourStatsAreWrong handlerStatsIncorrect; /// <summary> /// These are the IDs of stats sent in the StatsPacket to the viewer. /// </summary> /// <remarks> /// Some of these are not relevant to OpenSimulator since it is architected differently to other simulators /// (e.g. script instructions aren't executed as part of the frame loop so 'script time' is tricky). /// </remarks> public enum Stats : uint { TimeDilation = 0, SimFPS = 1, PhysicsFPS = 2, AgentUpdates = 3, FrameMS = 4, NetMS = 5, OtherMS = 6, PhysicsMS = 7, AgentMS = 8, ImageMS = 9, ScriptMS = 10, TotalPrim = 11, ActivePrim = 12, Agents = 13, ChildAgents = 14, ActiveScripts = 15, ScriptLinesPerSecond = 16, InPacketsPerSecond = 17, OutPacketsPerSecond = 18, PendingDownloads = 19, PendingUploads = 20, VirtualSizeKb = 21, ResidentSizeKb = 22, PendingLocalUploads = 23, UnAckedBytes = 24, PhysicsPinnedTasks = 25, PhysicsLodTasks = 26, SimPhysicsStepMs = 27, SimPhysicsShapeMs = 28, SimPhysicsOtherMs = 29, SimPhysicsMemory = 30, ScriptEps = 31, SimSpareMs = 32, SimSleepMs = 33, SimIoPumpTime = 34 } /// <summary> /// This is for llGetRegionFPS /// </summary> public float LastReportedSimFPS { get { return lastReportedSimFPS; } } /// <summary> /// Number of object updates performed in the last stats cycle /// </summary> /// <remarks> /// This isn't sent out to the client but it is very useful data to detect whether viewers are being sent a /// large number of object updates. /// </remarks> public float LastReportedObjectUpdates { get; private set; } public float[] LastReportedSimStats { get { return lastReportedSimStats; } } /// <summary> /// Number of frames that have taken longer to process than Scene.MIN_FRAME_TIME /// </summary> public Stat SlowFramesStat { get; private set; } /// <summary> /// The threshold at which we log a slow frame. /// </summary> public int SlowFramesStatReportThreshold { get; private set; } /// <summary> /// Extra sim statistics that are used by monitors but not sent to the client. /// </summary> /// <value> /// The keys are the stat names. /// </value> private Dictionary<string, float> m_lastReportedExtraSimStats = new Dictionary<string, float>(); // Sending a stats update every 3 seconds- private int m_statsUpdatesEveryMS = 3000; private float m_statsUpdateFactor; private float m_timeDilation; private int m_fps; /// <summary> /// Number of the last frame on which we processed a stats udpate. /// </summary> private uint m_lastUpdateFrame; /// <summary> /// Our nominal fps target, as expected in fps stats when a sim is running normally. /// </summary> private float m_nominalReportedFps = 55; /// <summary> /// Parameter to adjust reported scene fps /// </summary> /// <remarks> /// Our scene loop runs slower than other server implementations, apparantly because we work somewhat differently. /// However, we will still report an FPS that's closer to what people are used to seeing. A lower FPS might /// affect clients and monitoring scripts/software. /// </remarks> private float m_reportedFpsCorrectionFactor = 5; // saved last reported value so there is something available for llGetRegionFPS private float lastReportedSimFPS; private float[] lastReportedSimStats = new float[22]; private float m_pfps; /// <summary> /// Number of agent updates requested in this stats cycle /// </summary> private int m_agentUpdates; /// <summary> /// Number of object updates requested in this stats cycle /// </summary> private int m_objectUpdates; private int m_frameMS; private int m_spareMS; private int m_netMS; private int m_agentMS; private int m_physicsMS; private int m_imageMS; private int m_otherMS; //Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. //Ckrinke private int m_scriptMS = 0; private int m_rootAgents; private int m_childAgents; private int m_numPrim; private int m_inPacketsPerSecond; private int m_outPacketsPerSecond; private int m_activePrim; private int m_unAckedBytes; private int m_pendingDownloads; private int m_pendingUploads = 0; // FIXME: Not currently filled in private int m_activeScripts; private int m_scriptLinesPerSecond; private int m_objectCapacity = 45000; private Scene m_scene; private RegionInfo ReportingRegion; private Timer m_report = new Timer(); private IEstateModule estateModule; public SimStatsReporter(Scene scene) { m_scene = scene; m_reportedFpsCorrectionFactor = scene.MinFrameTime * m_nominalReportedFps; m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000); ReportingRegion = scene.RegionInfo; m_objectCapacity = scene.RegionInfo.ObjectCapacity; m_report.AutoReset = true; m_report.Interval = m_statsUpdatesEveryMS; m_report.Elapsed += TriggerStatsHeartbeat; m_report.Enabled = true; if (StatsManager.SimExtraStats != null) OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket; /// At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit /// longer than ideal (which in itself is a concern). SlowFramesStatReportThreshold = (int)Math.Ceiling(m_scene.MinFrameTime * 1000 * 1.2); SlowFramesStat = new Stat( "SlowFrames", "Slow Frames", "Number of frames where frame time has been significantly longer than the desired frame time.", " frames", "scene", m_scene.Name, StatType.Push, null, StatVerbosity.Info); StatsManager.RegisterStat(SlowFramesStat); } public void Close() { m_report.Elapsed -= TriggerStatsHeartbeat; m_report.Close(); } /// <summary> /// Sets the number of milliseconds between stat updates. /// </summary> /// <param name='ms'></param> public void SetUpdateMS(int ms) { m_statsUpdatesEveryMS = ms; m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000); m_report.Interval = m_statsUpdatesEveryMS; } private void TriggerStatsHeartbeat(object sender, EventArgs args) { try { statsHeartBeat(sender, args); } catch (Exception e) { m_log.Warn(string.Format( "[SIM STATS REPORTER] Update for {0} failed with exception ", m_scene.RegionInfo.RegionName), e); } } private void statsHeartBeat(object sender, EventArgs e) { if (!m_scene.Active) return; SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22]; SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); // Know what's not thread safe in Mono... modifying timers. // m_log.Debug("Firing Stats Heart Beat"); lock (m_report) { uint regionFlags = 0; try { if (estateModule == null) estateModule = m_scene.RequestModuleInterface<IEstateModule>(); regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0; } catch (Exception) { // leave region flags at 0 } #region various statistic googly moogly // We're going to lie about the FPS because we've been lying since 2008. The actual FPS is currently // locked at a maximum of 11. Maybe at some point this can change so that we're not lying. int reportedFPS = (int)(m_fps * m_reportedFpsCorrectionFactor); // save the reported value so there is something available for llGetRegionFPS lastReportedSimFPS = reportedFPS / m_statsUpdateFactor; float physfps = ((m_pfps / 1000)); //if (physfps > 600) //physfps = physfps - (physfps - 600); if (physfps < 0) physfps = 0; #endregion m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); m_numPrim = m_scene.SceneGraph.GetTotalObjectsCount(); m_activePrim = m_scene.SceneGraph.GetActiveObjectsCount(); m_activeScripts = m_scene.SceneGraph.GetActiveScriptsCount(); // FIXME: Checking for stat sanity is a complex approach. What we really need to do is fix the code // so that stat numbers are always consistent. CheckStatSanity(); //Our time dilation is 0.91 when we're running a full speed, // therefore to make sure we get an appropriate range, // we have to factor in our error. (0.10f * statsUpdateFactor) // multiplies the fix for the error times the amount of times it'll occur a second // / 10 divides the value by the number of times the sim heartbeat runs (10fps) // Then we divide the whole amount by the amount of seconds pass in between stats updates. // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change // values to X-per-second values. uint thisFrame = m_scene.Frame; float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; m_lastUpdateFrame = thisFrame; // Avoid div-by-zero if somehow we've not updated any frames. if (framesUpdated == 0) framesUpdated = 1; for (int i = 0; i < 22; i++) { sb[i] = new SimStatsPacket.StatBlock(); } sb[0].StatID = (uint) Stats.TimeDilation; sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor)); sb[1].StatID = (uint) Stats.SimFPS; sb[1].StatValue = reportedFPS / m_statsUpdateFactor; sb[2].StatID = (uint) Stats.PhysicsFPS; sb[2].StatValue = physfps / m_statsUpdateFactor; sb[3].StatID = (uint) Stats.AgentUpdates; sb[3].StatValue = (m_agentUpdates / m_statsUpdateFactor); sb[4].StatID = (uint) Stats.Agents; sb[4].StatValue = m_rootAgents; sb[5].StatID = (uint) Stats.ChildAgents; sb[5].StatValue = m_childAgents; sb[6].StatID = (uint) Stats.TotalPrim; sb[6].StatValue = m_numPrim; sb[7].StatID = (uint) Stats.ActivePrim; sb[7].StatValue = m_activePrim; sb[8].StatID = (uint)Stats.FrameMS; sb[8].StatValue = m_frameMS / framesUpdated; sb[9].StatID = (uint)Stats.NetMS; sb[9].StatValue = m_netMS / framesUpdated; sb[10].StatID = (uint)Stats.PhysicsMS; sb[10].StatValue = m_physicsMS / framesUpdated; sb[11].StatID = (uint)Stats.ImageMS ; sb[11].StatValue = m_imageMS / framesUpdated; sb[12].StatID = (uint)Stats.OtherMS; sb[12].StatValue = m_otherMS / framesUpdated; sb[13].StatID = (uint)Stats.InPacketsPerSecond; sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor); sb[14].StatID = (uint)Stats.OutPacketsPerSecond; sb[14].StatValue = (m_outPacketsPerSecond / m_statsUpdateFactor); sb[15].StatID = (uint)Stats.UnAckedBytes; sb[15].StatValue = m_unAckedBytes; sb[16].StatID = (uint)Stats.AgentMS; sb[16].StatValue = m_agentMS / framesUpdated; sb[17].StatID = (uint)Stats.PendingDownloads; sb[17].StatValue = m_pendingDownloads; sb[18].StatID = (uint)Stats.PendingUploads; sb[18].StatValue = m_pendingUploads; sb[19].StatID = (uint)Stats.ActiveScripts; sb[19].StatValue = m_activeScripts; sb[20].StatID = (uint)Stats.ScriptLinesPerSecond; sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor; sb[21].StatID = (uint)Stats.SimSpareMs; sb[21].StatValue = m_spareMS / framesUpdated; for (int i = 0; i < 22; i++) { lastReportedSimStats[i] = sb[i].StatValue; } SimStats simStats = new SimStats( ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)m_objectCapacity, rb, sb, m_scene.RegionInfo.originRegionID); handlerSendStatResult = OnSendStatsResult; if (handlerSendStatResult != null) { handlerSendStatResult(simStats); } // Extra statistics that aren't currently sent to clients lock (m_lastReportedExtraSimStats) { m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor; m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value; Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats(); if (physicsStats != null) { foreach (KeyValuePair<string, float> tuple in physicsStats) { // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second // Need to change things so that stats source can indicate whether they are per second or // per frame. if (tuple.Key.EndsWith("MS")) m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; else m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; } } } ResetValues(); } } private void ResetValues() { m_timeDilation = 0; m_fps = 0; m_pfps = 0; m_agentUpdates = 0; m_objectUpdates = 0; //m_inPacketsPerSecond = 0; //m_outPacketsPerSecond = 0; m_unAckedBytes = 0; m_scriptLinesPerSecond = 0; m_frameMS = 0; m_agentMS = 0; m_netMS = 0; m_physicsMS = 0; m_imageMS = 0; m_otherMS = 0; m_spareMS = 0; //Ckrinke This variable is not used, so comment to remove compiler warning until it is used. //Ckrinke m_scriptMS = 0; } # region methods called from Scene // The majority of these functions are additive // so that you can easily change the amount of // seconds in between sim stats updates public void AddTimeDilation(float td) { //float tdsetting = td; //if (tdsetting > 1.0f) //tdsetting = (tdsetting - (tdsetting - 0.91f)); //if (tdsetting < 0) //tdsetting = 0.0f; m_timeDilation = td; } internal void CheckStatSanity() { if (m_rootAgents < 0 || m_childAgents < 0) { handlerStatsIncorrect = OnStatsIncorrect; if (handlerStatsIncorrect != null) { handlerStatsIncorrect(); } } if (m_rootAgents == 0 && m_childAgents == 0) { m_unAckedBytes = 0; } } public void AddFPS(int frames) { m_fps += frames; } public void AddPhysicsFPS(float frames) { m_pfps += frames; } public void AddObjectUpdates(int numUpdates) { m_objectUpdates += numUpdates; } public void AddAgentUpdates(int numUpdates) { m_agentUpdates += numUpdates; } public void AddInPackets(int numPackets) { m_inPacketsPerSecond = numPackets; } public void AddOutPackets(int numPackets) { m_outPacketsPerSecond = numPackets; } public void AddunAckedBytes(int numBytes) { m_unAckedBytes += numBytes; if (m_unAckedBytes < 0) m_unAckedBytes = 0; } public void addFrameMS(int ms) { m_frameMS += ms; // At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit // longer than ideal due to the inaccuracy of the Sleep in Scene.Update() (which in itself is a concern). if (ms > SlowFramesStatReportThreshold) SlowFramesStat.Value++; } public void AddSpareMS(int ms) { m_spareMS += ms; } public void addNetMS(int ms) { m_netMS += ms; } public void addAgentMS(int ms) { m_agentMS += ms; } public void addPhysicsMS(int ms) { m_physicsMS += ms; } public void addImageMS(int ms) { m_imageMS += ms; } public void addOtherMS(int ms) { m_otherMS += ms; } public void AddPendingDownloads(int count) { m_pendingDownloads += count; if (m_pendingDownloads < 0) m_pendingDownloads = 0; //m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads); } public void addScriptLines(int count) { m_scriptLinesPerSecond += count; } public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes) { AddInPackets(inPackets); AddOutPackets(outPackets); AddunAckedBytes(unAckedBytes); } #endregion public Dictionary<string, float> GetExtraSimStats() { lock (m_lastReportedExtraSimStats) return new Dictionary<string, float>(m_lastReportedExtraSimStats); } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using Microsoft.Samples.VisualStudio.CodeSweep.Scanner; using Microsoft.Samples.VisualStudio.CodeSweep.VSPackage.Properties; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.Samples.VisualStudio.CodeSweep.VSPackage { internal class BackgroundScanner : IBackgroundScanner { /// <summary> /// Creates a new background scanner. /// </summary> /// <param name="serviceProvider">The service provider that is used to get VS services.</param> /// <exception cref="System.ArgumentNullException">Thrown if <c>serviceProvider</c> is null.</exception> public BackgroundScanner(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } _serviceProvider = serviceProvider; } /// <summary> /// Fired just before the background scan starts. The call occurs on the thread on which /// <c>Start</c> is called, not on the background thread. /// </summary> public event EventHandler Started; /// <summary> /// Fired after the background scan stops. The call occurs on the background thread. /// </summary> public event EventHandler Stopped; /// <summary> /// Starts a scan on a background thread. /// </summary> /// <param name="projects">The projects which will be scanned.</param> /// <exception cref="System.ArgumentNullException">Thrown if <c>project</c> is null.</exception> /// <exception cref="System.InvalidOperationException">Thrown if a background scan is already running.</exception> /// <remarks> /// Before this method returns, the CodeSweep task list will be cleared, and the tasklist /// window will be activated with the CodeSweep task list visible. /// While the scan is running, the status bar will display a progress indicator. /// As each file is processed, the results (if any) will be placed in the task list. /// If <c>project</c> does not contain a CodeSweep configuration, this method will return /// immediately without creating a background thread. <c>Started</c> is not fired. /// </remarks> public void Start(IEnumerable<IVsProject> projects) { if (projects == null) { throw new ArgumentNullException("projects"); } if (IsRunning) { throw new InvalidOperationException(Resources.BackgroundScanAlreadyRunning); } GatherProjectInfo(projects); StartWithExistingConfigs(); } /// <summary> /// Starts a new scan, using the same project as the previous scan. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if a background scan is already running or if there was no previous scan to repeat.</exception> public void RepeatLast() { if (_projectsToScan.Count == 0) { throw new InvalidOperationException(Resources.NoPreviousScan); } StartWithExistingConfigs(); } /// <summary> /// Gets a boolean value indicating whether a background scan is currently running. /// </summary> public bool IsRunning { get; private set; } /// <summary> /// Stops a scan in progress. /// </summary> /// <param name="blockUntilDone">Controls whether this method returns immediately or waits until the background thread has finished.</param> public void StopIfRunning(bool blockUntilDone) { ManualResetEvent doneEvent = new ManualResetEvent(false); if (blockUntilDone) { Stopped += (sender, e) => doneEvent.Set(); } lock (_lockObj) { if (IsRunning) { _stopPending = true; } else { return; } } if (blockUntilDone) { doneEvent.WaitOne(); } } #region Private members class ProjectConfiguration { readonly List<string> _filesToScan; readonly List<string> _termTableFiles; readonly string _projectPath; public ProjectConfiguration(IEnumerable<string> filesToScan, IEnumerable<string> termTableFiles, string projectPath) { _filesToScan = new List<string>(filesToScan); _termTableFiles = new List<string>(termTableFiles); _projectPath = projectPath; } public ICollection<string> FilesToScan { get { return _filesToScan; } } public ICollection<string> TermTableFiles { get { return _termTableFiles; } } public string ProjectPath { get { return _projectPath; } } } delegate IMultiFileScanResult ScanDelegate( IEnumerable<string> filePaths, IEnumerable<ITermTable> termTables, FileScanCompleted callback, FileContentGetter contentGetter, ScanStopper stopper); readonly IServiceProvider _serviceProvider; bool _stopPending = false; uint _filesProcessed = 0; uint _totalFiles = 0; uint _statusBarCookie = 0; List<IVsProject> _projectList = new List<IVsProject>(); List<ProjectConfiguration> _projectsToScan = new List<ProjectConfiguration>(); int _currentProject = 0; object _lockObj = new object(); void ScanCompleted(IAsyncResult result) { lock (_lockObj) { ++_currentProject; if (_currentProject == _projectsToScan.Count || _stopPending) { _currentProject = 0; IsRunning = false; _stopPending = false; UpdateStatusBar(false, String.Empty, 0, 0); var handler = Stopped; if (handler != null) { handler(this, EventArgs.Empty); } } else { StartCurrentConfig(); } } } void UpdateStatusBar(bool usingStatusBar, string text, uint soFar, uint total) { var statusBar = _serviceProvider.GetService(typeof(SVsStatusbar)) as IVsStatusbar; if (statusBar != null) { statusBar.Progress(ref _statusBarCookie, usingStatusBar ? 1 : 0, text, soFar, total); } else { Debug.Fail("Failed to get SVsStatusbar service."); } if (!usingStatusBar) { _statusBarCookie = 0; } } void ScanResultRecieved(IScanResult result) { if (!_stopPending) { var taskProvider = Factory.GetTaskProvider() as TaskProvider; taskProvider.SetCurrentProject(_projectList[_currentProject]); Factory.GetTaskProvider().AddResult(result, _projectsToScan[_currentProject].ProjectPath); ++_filesProcessed; UpdateStatusBar(true, Resources.AppName, _filesProcessed, _totalFiles); } } void StartCurrentConfig() { ScanDelegate scanDelegate = CodeSweep.Scanner.Factory.GetScanner().Scan; List<ITermTable> termTables = new List<ITermTable>(); foreach (string tableFile in _projectsToScan[_currentProject].TermTableFiles) { try { termTables.Add(CodeSweep.Scanner.Factory.GetTermTable(tableFile)); } catch (Exception ex) { if (!(ex is ArgumentException || ex is System.Xml.XmlException)) { throw; } } } UpdateStatusBar(true, Resources.AppName, _filesProcessed, _totalFiles); var handler = Started; if (handler != null) { handler(this, EventArgs.Empty); } ScanStopper stopper = () => _stopPending; IsRunning = true; scanDelegate.BeginInvoke( _projectsToScan[_currentProject].FilesToScan, termTables, new FileScanCompleted(ScanResultRecieved), new FileContentGetter(GetTextOfFileIfOpenInIde), stopper, ScanCompleted, null /* 'object' argument */); } void StartWithExistingConfigs() { if (IsRunning) { throw new InvalidOperationException(Resources.AlreadyScanning); } ResetScanRun(); if (_totalFiles == 0) { return; } StartCurrentConfig(); } void ResetScanRun() { _currentProject = 0; _filesProcessed = 0; Factory.GetTaskProvider().Clear(); Factory.GetTaskProvider().ShowTaskList(); } void GatherProjectInfo(IEnumerable<IVsProject> projects) { _projectsToScan.Clear(); _totalFiles = 0; _projectList.Clear(); int projectNumber = 0; foreach (IVsProject project in projects) { _projectList.Insert(projectNumber, project); projectNumber++; List<string> filesToScan = new List<string>(); List<string> termTableFiles = new List<string>(); if (Factory.GetProjectConfigurationStore(project).HasConfiguration) { filesToScan.AddRange(Factory.GetBuildManager().AllItemsInProject(project)); termTableFiles.AddRange(Factory.GetProjectConfigurationStore(project).TermTableFiles); _totalFiles += (uint)filesToScan.Count; } _projectsToScan.Add(new ProjectConfiguration(filesToScan, termTableFiles, ProjectUtilities.GetProjectFilePath(project))); } } public string GetTextOfFileIfOpenInIde(string filePath) { var rdt = _serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt == null) { Debug.Fail("Failed to get SVsRunningDocumentTable service."); return null; } IVsHierarchy hierarchy = null; uint itemid = 0; IntPtr docDataUnk = IntPtr.Zero; uint lockCookie = 0; int hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, filePath, out hierarchy, out itemid, out docDataUnk, out lockCookie); try { if (hr == VSConstants.S_OK) { var textLines = Marshal.GetUniqueObjectForIUnknown(docDataUnk) as IVsTextLines; if (textLines != null) { string text = null; int endLine = 0; int endIndex = 0; hr = textLines.GetLastLineIndex(out endLine, out endIndex); Debug.Assert(hr == VSConstants.S_OK, "GetLastLineIndex did not return S_OK."); hr = textLines.GetLineText(0, 0, endLine, endIndex, out text); Debug.Assert(hr == VSConstants.S_OK, "GetLineText did not return S_OK."); return text; } } return null; } finally { if (lockCookie != 0) { rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, lockCookie); } } } #endregion Private members } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.VisualBasic.CompilerServices; using Xunit.Sdk; namespace Looker.RTL { public interface IAuthSession { IApiSettings Settings { get; set; } ITransport Transport { get; set; } /// <summary> /// ID of sudo user. Empty if not sudoing /// </summary> string SudoId { get; } /// <summary> /// Is the current session already authenticated? /// </summary> /// <returns>True if authenticated and token is active</returns> bool IsAuthenticated(); /// <summary> /// Add authentication information to the HTTP request /// </summary> /// <param name="request">Request to update</param> /// <returns>Request with authentication information added</returns> Task<HttpRequestMessage> Authenticate(HttpRequestMessage request); /// <summary> /// Log out the current user /// </summary> /// <remarks> /// If the current user is a sudo user, the API user becomes the active user /// If the current user is the API user, the API session is logged out. /// However, any subsequent SDK method calls automatically log the API user back in /// </remarks> /// <returns><c>True</c> if a logout happened, <c>false</c> otherwise</returns> Task<bool> Logout(); /// <summary> /// Typically returns an <c>IAccessToken</c> but could be any data used for auth. /// </summary> /// <returns>authentication payload</returns> Task<object> GetToken(); /// <summary> /// Is the SDK session sudoing? /// </summary> /// <returns><c>True</c> if a sudo user is using the SDK session</returns> bool IsSudo(); /// <summary> /// Authenticates the SDK session /// </summary> /// <param name="sudoId">Optional ID of the user to login</param> /// <returns></returns> Task<object> Login(string sudoId = null); /// <summary> /// Clears all authentication information, but does NOT log the API user out /// </summary> /// <remarks>This is based on the default <c>AuthSession</c> behavior</remarks> void Reset(); } public class AuthSession : IAuthSession { private readonly string _apiPath = $"/api/{Constants.DefaultApiVersion}"; private AuthToken _authToken = new AuthToken(); private AuthToken _sudoToken = new AuthToken(); private AuthToken ActiveToken => _sudoToken.access_token.IsFull() ? _sudoToken : _authToken; public IApiSettings Settings { get; set; } public ITransport Transport { get; set; } public string SudoId { get; private set; } = null; public AuthSession() { } public AuthSession(IApiSettings settings, ITransport transport) { Settings = settings; Transport = transport; } public bool IsAuthenticated() { return ActiveToken.IsActive(); } public async Task<HttpRequestMessage> Authenticate(HttpRequestMessage request) { if ((await GetToken() is IAccessToken token) && token.access_token.IsFull()) { request.Headers.Authorization = new AuthenticationHeaderValue( Constants.Bearer, token.access_token); } return request; } private async Task<bool> SudoLogout() { var result = false; if (IsSudo()) { result = await Logout(); // Logout current sudo user _sudoToken.Reset(); } return result; } protected Task<TSuccess> Ok<TSuccess, TError>(Task<SdkResponse<TSuccess, TError>> task) where TSuccess : class where TError : Exception { return SdkUtils.Ok(task); } private async Task<object> _login(string sudoId = null) { await SudoLogout(); if (sudoId != SudoId) { SudoId = sudoId; } if (!_authToken.IsActive()) { Reset(); // only retain client API3 credentials for the lifetime of the login request var section = Settings.ReadConfig(); var clientId = section["client_id"].ToString(); var secret = section["client_secret"].ToString(); if (clientId.IsNullOrEmpty() || secret.IsNullOrEmpty()) { throw new SdkError("API3 credentials client_id and/or client_secret are not set"); } var body = $"client_id={SdkUtils.EncodeParam(clientId)}&client_secret={SdkUtils.EncodeParam(secret)}"; var apiToken = await Ok(Transport.Request<AccessToken, Exception>( HttpMethod.Post, $"{_apiPath}/login", null, body )); this._authToken.SetToken(apiToken); } if (sudoId.IsNullOrEmpty()) return this.ActiveToken; // Now that API user is logged in, login as the Sudo user var token = this.ActiveToken; async Task<HttpRequestMessage> Auth(HttpRequestMessage request) { if (token.access_token.IsFull()) { request.Headers.Authorization = new AuthenticationHeaderValue( Constants.Bearer, token.access_token); } return await Task.FromResult(request); } var sudoPath = $"{_apiPath}/login/{SdkUtils.EncodeParam(sudoId)}"; var sudoToken = await Ok(Transport.Request<AccessToken, Exception>( HttpMethod.Post, sudoPath, null, null, Auth )); _sudoToken.SetToken(sudoToken); return ActiveToken; } private async Task<bool> _logout() { var token = ActiveToken; async Task<HttpRequestMessage> Auth(HttpRequestMessage request) { if (token.access_token.IsFull()) { request.Headers.Authorization = new AuthenticationHeaderValue( Constants.Bearer, token.access_token); } return await Task.FromResult(request); } await Ok(Transport.Request<string, SdkError>( HttpMethod.Delete, $"{_apiPath}/logout", null, null, Auth )); if (SudoId.IsFull()) { SudoId = null; _sudoToken.Reset(); if (!_authToken.IsActive()) { await _login(); } } else { // completely logged out Reset(); } return true; } public async Task<bool> Logout() { var result = false; if (IsAuthenticated()) { result = await this._logout(); } return result; } public async Task<object> GetToken() { if (!IsAuthenticated()) await Login(); return ActiveToken; } public bool IsSudo() { return SudoId.IsFull(); } public async Task<object> Login(string sudoId = null) { if ((sudoId.IsFull() && sudoId != SudoId) || !IsAuthenticated()) { await _login(sudoId); } else { await _login(); } return ActiveToken; } public void Reset() { SudoId = null; _authToken.Reset(); _sudoToken.Reset(); } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // 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; namespace NUnit.Framework.Constraints { /// <summary> /// ConstraintExpression represents a compound constraint in the /// process of being constructed from a series of syntactic elements. /// /// Individual elements are appended to the expression as they are /// reorganized. When a constraint is appended, it is returned as the /// value of the operation so that modifiers may be applied. However, /// any partially built expression is attached to the constraint for /// later resolution. When an operator is appended, the partial /// expression is returned. If it's a self-resolving operator, then /// a ResolvableConstraintExpression is returned. /// </summary> public class ConstraintExpression { #region Instance Fields /// <summary> /// The ConstraintBuilder holding the elements recognized so far /// </summary> protected ConstraintBuilder builder; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ConstraintExpression"/> class. /// </summary> public ConstraintExpression() { this.builder = new ConstraintBuilder(); } /// <summary> /// Initializes a new instance of the <see cref="ConstraintExpression"/> /// class passing in a ConstraintBuilder, which may be pre-populated. /// </summary> /// <param name="builder">The builder.</param> public ConstraintExpression(ConstraintBuilder builder) { this.builder = builder; } #endregion #region ToString() /// <summary> /// Returns a string representation of the expression as it /// currently stands. This should only be used for testing, /// since it has the side-effect of resolving the expression. /// </summary> /// <returns></returns> public override string ToString() { return builder.Resolve().ToString(); } #endregion #region Append Methods /// <summary> /// Appends an operator to the expression and returns the /// resulting expression itself. /// </summary> public ConstraintExpression Append(ConstraintOperator op) { builder.Append(op); return this; } /// <summary> /// Appends a self-resolving operator to the expression and /// returns a new ResolvableConstraintExpression. /// </summary> public ResolvableConstraintExpression Append(SelfResolvingOperator op) { builder.Append(op); return new ResolvableConstraintExpression(builder); } /// <summary> /// Appends a constraint to the expression and returns that /// constraint, which is associated with the current state /// of the expression being built. Note that the constraint /// is not reduced at this time. For example, if there /// is a NotOperator on the stack we don't reduce and /// return a NotConstraint. The original constraint must /// be returned because it may support modifiers that /// are yet to be applied. /// </summary> public Constraint Append(Constraint constraint) { builder.Append(constraint); return constraint; } #endregion #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression Not { get { return this.Append(new NotOperator()); } } /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression No { get { return this.Append(new NotOperator()); } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public ConstraintExpression All { get { return this.Append(new AllOperator()); } } #endregion #region Some /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if at least one of them succeeds. /// </summary> public ConstraintExpression Some { get { return this.Append(new SomeOperator()); } } #endregion #region None /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them fail. /// </summary> public ConstraintExpression None { get { return this.Append(new NoneOperator()); } } #endregion #region Exactly(n) /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding only if a specified number of them succeed. /// </summary> public ItemsConstraintExpression Exactly(int expectedCount) { builder.Append(new ExactCountOperator(expectedCount)); return new ItemsConstraintExpression(builder); } #endregion #region One /// <summary> /// Returns a <see cref="ItemsConstraintExpression"/>, which will /// apply the following constraint to a collection of length one, succeeding /// only if exactly one of them succeeds. /// </summary> public ItemsConstraintExpression One { get { builder.Append(new ExactCountOperator(1)); return new ItemsConstraintExpression(builder); } } #endregion #region Property /// <summary> /// Returns a new PropertyConstraintExpression, which will either /// test for the existence of the named property on the object /// being tested or apply any following constraint to that property. /// </summary> public ResolvableConstraintExpression Property(string name) { return this.Append(new PropOperator(name)); } #endregion #region Length /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Length property of the object being tested. /// </summary> public ResolvableConstraintExpression Length { get { return Property("Length"); } } #endregion #region Count /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Count property of the object being tested. /// </summary> public ResolvableConstraintExpression Count { get { return Property("Count"); } } #endregion #region Message /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Message property of the object being tested. /// </summary> public ResolvableConstraintExpression Message { get { return Property("Message"); } } #endregion #region InnerException /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the InnerException property of the object being tested. /// </summary> public ResolvableConstraintExpression InnerException { get { return Property("InnerException"); } } #endregion #region Attribute /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute(Type expectedType) { return this.Append(new AttributeOperator(expectedType)); } /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute<TExpected>() { return Attribute(typeof(TExpected)); } #endregion #region With /// <summary> /// With is currently a NOP - reserved for future use. /// </summary> public ConstraintExpression With { get { return this.Append(new WithOperator()); } } #endregion #region Matches /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches(IResolveConstraint constraint) { return this.Append((Constraint)constraint.Resolve()); } /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches<TActual>(Predicate<TActual> predicate) { return this.Append(new PredicateConstraint<TActual>(predicate)); } #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public NullConstraint Null { get { return (NullConstraint)this.Append(new NullConstraint()); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public TrueConstraint True { get { return (TrueConstraint)this.Append(new TrueConstraint()); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public FalseConstraint False { get { return (FalseConstraint)this.Append(new FalseConstraint()); } } #endregion #region Positive /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public GreaterThanConstraint Positive { get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); } } #endregion #region Negative /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public LessThanConstraint Negative { get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); } } #endregion #region Zero /// <summary> /// Returns a constraint that tests if item is equal to zero /// </summary> public EqualConstraint Zero { get { return (EqualConstraint)this.Append(new EqualConstraint(0)); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public NaNConstraint NaN { get { return (NaNConstraint)this.Append(new NaNConstraint()); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public EmptyConstraint Empty { get { return (EmptyConstraint)this.Append(new EmptyConstraint()); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public UniqueItemsConstraint Unique { get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); } } #endregion #region BinarySerializable #if !NETSTANDARD1_3 && !NETSTANDARD1_6 /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public BinarySerializableConstraint BinarySerializable { get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); } } #endif #endregion #region XmlSerializable #if !NETSTANDARD1_3 && !NETSTANDARD1_6 /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml format. /// </summary> public XmlSerializableConstraint XmlSerializable { get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); } } #endif #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public EqualConstraint EqualTo(object expected) { return (EqualConstraint)this.Append(new EqualConstraint(expected)); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public SameAsConstraint SameAs(object expected) { return (SameAsConstraint)this.Append(new SameAsConstraint(expected)); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the supplied argument /// </summary> public GreaterThanConstraint GreaterThan(object expected) { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected)); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the supplied argument /// </summary> public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the supplied argument /// </summary> public GreaterThanOrEqualConstraint AtLeast(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the supplied argument /// </summary> public LessThanConstraint LessThan(object expected) { return (LessThanConstraint)this.Append(new LessThanConstraint(expected)); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the supplied argument /// </summary> public LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the supplied argument /// </summary> public LessThanOrEqualConstraint AtMost(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf(Type expectedType) { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf<TExpected>() { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(TExpected))); } #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf(Type expectedType) { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf<TExpected>() { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(TExpected))); } #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom(Type expectedType) { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom<TExpected>() { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(TExpected))); } #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo(Type expectedType) { return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo<TExpected>() { return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(TExpected))); } #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected)); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected)); } #endregion #region SupersetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a superset of the collection supplied as an argument. /// </summary> public CollectionSupersetConstraint SupersetOf(IEnumerable expected) { return (CollectionSupersetConstraint)this.Append(new CollectionSupersetConstraint(expected)); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public CollectionOrderedConstraint Ordered { get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); } } #endregion #region Member /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Member(object expected) { return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected))); } #endregion #region Contains /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Contains(object expected) { return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected))); } /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contains(string expected) { return (ContainsConstraint)this.Append(new ContainsConstraint(expected)); } /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Contain(object expected) { return Contains(expected); } /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contain(string expected) { return Contains(expected); } #endregion #region DictionaryContains /// <summary> /// Returns a new DictionaryContainsKeyConstraint checking for the /// presence of a particular key in the Dictionary key collection. /// </summary> /// <param name="expected">The key to be matched in the Dictionary key collection</param> public DictionaryContainsKeyConstraint ContainKey(object expected) { return (DictionaryContainsKeyConstraint)this.Append(new DictionaryContainsKeyConstraint(expected)); } /// <summary> /// Returns a new DictionaryContainsValueConstraint checking for the /// presence of a particular value in the Dictionary value collection. /// </summary> /// <param name="expected">The value to be matched in the Dictionary value collection</param> public DictionaryContainsValueConstraint ContainValue(object expected) { return (DictionaryContainsValueConstraint)this.Append(new DictionaryContainsValueConstraint(expected)); } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Contains")] public SubstringConstraint StringContaining(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Contains")] public SubstringConstraint ContainsSubstring(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } #endregion #region StartsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartsWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Does.StartWith or StartsWith")] public StartsWithConstraint StringStarting(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } #endregion #region EndsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndsWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Does.EndWith or EndsWith")] public EndsWithConstraint StringEnding(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } #endregion #region Matches /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Match(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Matches(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> [Obsolete("Deprecated, use Does.Match or Matches")] public RegexConstraint StringMatching(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public SamePathConstraint SamePath(string expected) { return (SamePathConstraint)this.Append(new SamePathConstraint(expected)); } #endregion #region SubPath /// <summary> /// Returns a constraint that tests whether the path provided /// is the a subpath of the expected path after canonicalization. /// </summary> public SubPathConstraint SubPathOf(string expected) { return (SubPathConstraint)this.Append(new SubPathConstraint(expected)); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SamePathOrUnderConstraint SamePathOrUnder(string expected) { return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected)); } #endregion #region InRange /// <summary> /// Returns a constraint that tests whether the actual value falls /// inclusively within a specified range. /// </summary> /// <param name="from">Inclusive beginning of the range.</param> /// <param name="to">Inclusive end of the range.</param> public RangeConstraint InRange(object from, object to) { return (RangeConstraint)this.Append(new RangeConstraint(from, to)); } #endregion #region Exist /// <summary> /// Returns a constraint that succeeds if the value /// is a file or directory and it exists. /// </summary> public Constraint Exist { get { return Append(new FileOrDirectoryExistsConstraint()); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeParameter2))] public sealed class CodeParameter : AbstractCodeElement, EnvDTE.CodeParameter, EnvDTE80.CodeParameter2, IParameterKind { internal static EnvDTE.CodeParameter Create( CodeModelState state, AbstractCodeMember parent, string name) { var element = new CodeParameter(state, parent, name); return (EnvDTE.CodeParameter)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _name; private CodeParameter( CodeModelState state, AbstractCodeMember parent, string name) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _name = name; } private IParameterSymbol ParameterSymbol { get { return (IParameterSymbol)LookupSymbol(); } } private void UpdateNodeAndReacquireParentNodeKey<T>(Action<SyntaxNode, T> parameterUpdater, T value) { Action<SyntaxNode, T> updater = (n, v) => { var parentNode = _parentHandle.Value.LookupNode(); var parentNodePath = new SyntaxPath(parentNode); parameterUpdater(n, v); _parentHandle.Value.ReacquireNodeKey(parentNodePath, CancellationToken.None); }; UpdateNode(updater, value); } protected override EnvDTE.CodeElements GetCollection() { return GetCollection<CodeParameter>(Parent); } protected override string GetName() { return _name; } protected override string GetFullName() { var node = LookupNode(); if (node == null) { return string.Empty; } return CodeModelService.GetParameterFullName(node); } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetParameterNode(parentNode, _name, out var parameterNode)) { return false; } node = parameterNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementParameter; } } public override object Parent { get { return _parentHandle.Value; } } EnvDTE.CodeElement EnvDTE.CodeParameter.Parent { get { return (EnvDTE.CodeElement)Parent; } } EnvDTE.CodeElement EnvDTE80.CodeParameter2.Parent { get { return (EnvDTE.CodeElement)Parent; } } public override EnvDTE.CodeElements Children { get { return this.Attributes; } } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, GetProjectId(), ParameterSymbol.Type); } set { UpdateNodeAndReacquireParentNodeKey(FileCodeModel.UpdateType, value); } } public EnvDTE80.vsCMParameterKind ParameterKind { get { return CodeModelService.GetParameterKind(LookupNode()); } set { UpdateNodeAndReacquireParentNodeKey(FileCodeModel.UpdateParameterKind, value); } } public string DefaultValue { get { return CodeModelService.GetInitExpression(LookupNode()); } set { UpdateNode(FileCodeModel.UpdateInitExpression, value); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddAttribute(LookupNode(), name, value, position); }); } void IParameterKind.SetParameterPassingMode(PARAMETER_PASSING_MODE passingMode) { this.ParameterKind = this.CodeModelService.UpdateParameterKind(ParameterKind, passingMode); } void IParameterKind.SetParameterArrayDimensions(int dimensions) { var type = this.ParameterSymbol.Type; var compilation = this.FileCodeModel.GetCompilation(); var elementType = type is IArrayTypeSymbol ? ((IArrayTypeSymbol)type).ElementType : type; // The original C# implementation had a weird behavior where it wold allow setting array dimensions // to 0 to create an array with a single rank. var rank = Math.Max(dimensions, 1); var newType = compilation.CreateArrayTypeSymbol(elementType, rank); this.Type = CodeTypeRef.Create(this.State, this, GetProjectId(), newType); } int IParameterKind.GetParameterArrayCount() { var arrayType = this.ParameterSymbol.Type as IArrayTypeSymbol; var count = 0; while (arrayType != null) { count++; arrayType = arrayType.ElementType as IArrayTypeSymbol; } return count; } int IParameterKind.GetParameterArrayDimensions(int index) { if (index < 0) { throw Exceptions.ThrowEInvalidArg(); } var arrayType = this.ParameterSymbol.Type as IArrayTypeSymbol; var count = 0; while (count < index && arrayType != null) { count++; arrayType = arrayType.ElementType as IArrayTypeSymbol; } if (arrayType == null) { throw Exceptions.ThrowEInvalidArg(); } return arrayType.Rank; } PARAMETER_PASSING_MODE IParameterKind.GetParameterPassingMode() { var parameterKind = this.ParameterKind; if ((parameterKind & EnvDTE80.vsCMParameterKind.vsCMParameterKindRef) != 0) { return PARAMETER_PASSING_MODE.cmParameterTypeInOut; } else if ((parameterKind & EnvDTE80.vsCMParameterKind.vsCMParameterKindOut) != 0) { return PARAMETER_PASSING_MODE.cmParameterTypeOut; } else { return PARAMETER_PASSING_MODE.cmParameterTypeIn; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Permissions { using System; using System.IO; using System.Security.Util; using System.Text; using System.Threading; using System.Runtime.Remoting; using System.Security; using System.Runtime.Serialization; using System.Reflection; using System.Globalization; using System.Diagnostics.Contracts; [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] // The csharp compiler requires these types to be public, but they are not used elsewhere. [Obsolete("SecurityPermissionFlag is no longer accessible to application code.")] public enum SecurityPermissionFlag { NoFlags = 0x00, /* The following enum value is used in the EE (ASSERT_PERMISSION in security.cpp) * Should this value change, make corresponding changes there */ Assertion = 0x01, UnmanagedCode = 0x02, // Update vm\Security.h if you change this ! SkipVerification = 0x04, // Update vm\Security.h if you change this ! Execution = 0x08, ControlThread = 0x10, ControlEvidence = 0x20, ControlPolicy = 0x40, SerializationFormatter = 0x80, ControlDomainPolicy = 0x100, ControlPrincipal = 0x200, ControlAppDomain = 0x400, RemotingConfiguration = 0x800, Infrastructure = 0x1000, BindingRedirects = 0x2000, AllFlags = 0x3fff, } [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class SecurityPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission { #pragma warning disable 618 private SecurityPermissionFlag m_flags; #pragma warning restore 618 // // Public Constructors // public SecurityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { SetUnrestricted( true ); } else if (state == PermissionState.None) { SetUnrestricted( false ); Reset(); } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } // SecurityPermission // #pragma warning disable 618 public SecurityPermission(SecurityPermissionFlag flag) #pragma warning restore 618 { VerifyAccess(flag); SetUnrestricted(false); m_flags = flag; } //------------------------------------------------------ // // PRIVATE AND PROTECTED MODIFIERS // //------------------------------------------------------ private void SetUnrestricted(bool unrestricted) { if (unrestricted) { #pragma warning disable 618 m_flags = SecurityPermissionFlag.AllFlags; #pragma warning restore 618 } } private void Reset() { #pragma warning disable 618 m_flags = SecurityPermissionFlag.NoFlags; #pragma warning restore 618 } #pragma warning disable 618 public SecurityPermissionFlag Flags #pragma warning restore 618 { set { VerifyAccess(value); m_flags = value; } get { return m_flags; } } // // CodeAccessPermission methods // /* * IPermission interface implementation */ public override bool IsSubsetOf(IPermission target) { if (target == null) { return m_flags == 0; } SecurityPermission operand = target as SecurityPermission; if (operand != null) { return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0; } else { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } } public override IPermission Union(IPermission target) { if (target == null) return(this.Copy()); if (!VerifyType(target)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } SecurityPermission sp_target = (SecurityPermission) target; if (sp_target.IsUnrestricted() || IsUnrestricted()) { return(new SecurityPermission(PermissionState.Unrestricted)); } #pragma warning disable 618 SecurityPermissionFlag flag_union = (SecurityPermissionFlag)(m_flags | sp_target.m_flags); #pragma warning restore 618 return(new SecurityPermission(flag_union)); } public override IPermission Intersect(IPermission target) { if (target == null) return null; else if (!VerifyType(target)) { throw new ArgumentException( Environment.GetResourceString("Argument_WrongType", this.GetType().FullName) ); } SecurityPermission operand = (SecurityPermission)target; #pragma warning disable 618 SecurityPermissionFlag isectFlags = SecurityPermissionFlag.NoFlags; #pragma warning restore 618 if (operand.IsUnrestricted()) { if (this.IsUnrestricted()) return new SecurityPermission(PermissionState.Unrestricted); else #pragma warning disable 618 isectFlags = (SecurityPermissionFlag)this.m_flags; #pragma warning restore 618 } else if (this.IsUnrestricted()) { #pragma warning disable 618 isectFlags = (SecurityPermissionFlag)operand.m_flags; #pragma warning restore 618 } else { #pragma warning disable 618 isectFlags = (SecurityPermissionFlag)m_flags & (SecurityPermissionFlag)operand.m_flags; #pragma warning restore 618 } if (isectFlags == 0) return null; else return new SecurityPermission(isectFlags); } public override IPermission Copy() { if (IsUnrestricted()) return new SecurityPermission(PermissionState.Unrestricted); else #pragma warning disable 618 return new SecurityPermission((SecurityPermissionFlag)m_flags); #pragma warning restore 618 } public bool IsUnrestricted() { #pragma warning disable 618 return m_flags == SecurityPermissionFlag.AllFlags; #pragma warning restore 618 } private #pragma warning disable 618 void VerifyAccess(SecurityPermissionFlag type) #pragma warning restore 618 { #pragma warning disable 618 if ((type & ~SecurityPermissionFlag.AllFlags) != 0) #pragma warning restore 618 throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type)); Contract.EndContractBlock(); } // // Object Overrides // /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return SecurityPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.SecurityPermissionIndex; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Used by the class to hold the underlying socket the stream uses. private Socket _streamSocket; // Used by the class to indicate that the stream is m_Readable. private bool _readable; // Used by the class to indicate that the stream is writable. private bool _writeable; private bool _ownsSocket; // Creates a new instance of the System.Net.Sockets.NetworkStream without initialization. internal NetworkStream() { _ownsSocket = true; } // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket. public NetworkStream(Socket socket) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException(nameof(socket)); } InitNetworkStream(socket); #if DEBUG } #endif } public NetworkStream(Socket socket, bool ownsSocket) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException(nameof(socket)); } InitNetworkStream(socket); _ownsSocket = ownsSocket; #if DEBUG } #endif } internal NetworkStream(NetworkStream networkStream, bool ownsSocket) { Socket socket = networkStream.Socket; if (socket == null) { throw new ArgumentNullException(nameof(networkStream)); } InitNetworkStream(socket); _ownsSocket = ownsSocket; } // Socket - provides access to socket for stream closing protected Socket Socket { get { return _streamSocket; } } internal Socket InternalSocket { get { Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { throw new ObjectDisposedException(this.GetType().FullName); } return chkSocket; } } internal void InternalAbortSocket() { if (!_ownsSocket) { throw new InvalidOperationException(); } Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { return; } try { chkSocket.Dispose(); } catch (ObjectDisposedException) { } } internal void ConvertToNotSocketOwner() { _ownsSocket = false; // Suppress for finialization still allow proceed the requests GC.SuppressFinalize(this); } // Used by the class to indicate that the stream is m_Readable. protected bool Readable { get { return _readable; } set { _readable = value; } } // Used by the class to indicate that the stream is writable. protected bool Writeable { get { return _writeable; } set { _writeable = value; } } // Indicates that data can be read from the stream. // We return the readability of this stream. This is a read only property. public override bool CanRead { get { return _readable; } } // Indicates that the stream can seek a specific location // in the stream. This property always returns false. public override bool CanSeek { get { return false; } } // Indicates that data can be written to the stream. public override bool CanWrite { get { return _writeable; } } // Indicates whether we can timeout public override bool CanTimeout { get { return true; // should we check for Connected state? } } // Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int ReadTimeout { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Receive, value, false); #if DEBUG } #endif } } // Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int WriteTimeout { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Send, value, false); #if DEBUG } #endif } } // Indicates data is available on the stream to be read. // This property checks to see if at least one byte of data is currently available public virtual bool DataAvailable { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } // Ask the socket how many bytes are available. If it's // not zero, return true. return chkStreamSocket.Available != 0; #if DEBUG } #endif } } // The length of data available on the stream. Always throws NotSupportedException. public override long Length { get { throw new NotSupportedException(SR.net_noseek); } } // Gets or sets the position in the stream. Always throws NotSupportedException. public override long Position { get { throw new NotSupportedException(SR.net_noseek); } set { throw new NotSupportedException(SR.net_noseek); } } // Seeks a specific position in the stream. This method is not supported by the // NetworkStream class. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } internal void InitNetworkStream(Socket socket) { if (!socket.Blocking) { throw new IOException(SR.net_sockets_blocking); } if (!socket.Connected) { throw new IOException(SR.net_notconnected); } if (socket.SocketType != SocketType.Stream) { throw new IOException(SR.net_notstream); } _streamSocket = socket; _readable = true; _writeable = true; } internal bool PollRead() { if (_cleanedUp) { return false; } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return false; } return chkStreamSocket.Poll(0, SelectMode.SelectRead); } internal bool Poll(int microSeconds, SelectMode mode) { if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } return chkStreamSocket.Poll(microSeconds, mode); } // Read - provide core Read functionality. // // Provide core read functionality. All we do is call through to the // socket Receive functionality. // // Input: // // Buffer - Buffer to read into. // Offset - Offset into the buffer where we're to read. // Count - Number of bytes to read. // // Returns: // // Number of bytes we read, or 0 if the socket is closed. public override int Read([In, Out] byte[] buffer, int offset, int size) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.Receive(buffer, offset, size, 0); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // Write - provide core Write functionality. // // Provide core write functionality. All we do is call through to the // socket Send method.. // // Input: // // Buffer - Buffer to write from. // Offset - Offset into the buffer from where we'll start writing. // Count - Number of bytes to write. // // Returns: // // Number of bytes written. We'll throw an exception if we // can't write everything. It's brutal, but there's no other // way to indicate an error. public override void Write(byte[] buffer, int offset, int size) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Since the socket is in blocking mode this will always complete // after ALL the requested number of bytes was transferred. chkStreamSocket.Send(buffer, offset, size, SocketFlags.None); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } private volatile bool _cleanedUp = false; protected override void Dispose(bool disposing) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif // Mark this as disposed before changing anything else. bool cleanedUp = _cleanedUp; _cleanedUp = true; if (!cleanedUp && disposing) { // The only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. if (_streamSocket != null) { _readable = false; _writeable = false; if (_ownsSocket) { // If we own the Socket (false by default), close it // ignoring possible exceptions (eg: the user told us // that we own the Socket but it closed at some point of time, // here we would get an ObjectDisposedException) Socket chkStreamSocket = _streamSocket; if (chkStreamSocket != null) { chkStreamSocket.InternalShutdown(SocketShutdown.Both); chkStreamSocket.Dispose(); } } } } #if DEBUG } #endif base.Dispose(disposing); } ~NetworkStream() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Finalization); #endif Dispose(false); } // Indicates whether the stream is still connected internal bool Connected { get { Socket socket = _streamSocket; if (!_cleanedUp && socket != null && socket.Connected) { return true; } else { return false; } } } // BeginRead - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the underlying socket async read. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // // Returns: // // An IASyncResult, representing the read. public IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.BeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } } // EndRead - handle the end of an async read. // // This method is called when an async read is completed. All we // do is call through to the core socket EndReceive functionality. // // Returns: // // The number of bytes read. May throw an exception. public int EndRead(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.EndReceive(asyncResult); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // BeginWrite - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the underlying socket async send. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to written. // // Returns: // // An IASyncResult, representing the write. public IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.BeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // Handle the end of an asynchronous write. // This method is called when an async write is completed. All we // do is call through to the core socket EndSend functionality. // Returns: The number of bytes read. May throw an exception. public void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { chkStreamSocket.EndSend(asyncResult); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // ReadAsync - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the Begin/EndRead methods. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task<int> representing the read. public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginRead(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndRead(iar), buffer, offset, size, this); } // WriteAsync - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the Begin/EndWrite methods. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to write. // cancellationToken - Token used to request cancellation of the operation // // Returns: // // A Task representing the write. public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginWrite(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndWrite(iar), buffer, offset, size, this); } // Flushes data from the stream. This is meaningless for us, so it does nothing. public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } // Sets the length of the stream. Always throws NotSupportedException public override void SetLength(long value) { throw new NotSupportedException(SR.net_noseek); } private int _currentReadTimeout = -1; private int _currentWriteTimeout = -1; internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { if (GlobalLog.IsEnabled) { GlobalLog.Print("NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption() mode:" + mode + " silent:" + silent + " timeout:" + timeout + " m_CurrentReadTimeout:" + _currentReadTimeout + " m_CurrentWriteTimeout:" + _currentWriteTimeout); } GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + LoggingHash.HashString(this) + "::SetSocketTimeoutOption"); if (timeout < 0) { timeout = 0; // -1 becomes 0 for the winsock stack } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return; } if (mode == SocketShutdown.Send || mode == SocketShutdown.Both) { if (timeout != _currentWriteTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent); _currentWriteTimeout = timeout; } } if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both) { if (timeout != _currentReadTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent); _currentReadTimeout = timeout; } } } [System.Diagnostics.Conditional("TRACE_VERBOSE")] internal void DebugMembers() { if (_streamSocket != null) { if (GlobalLog.IsEnabled) { GlobalLog.Print("_streamSocket:"); } _streamSocket.DebugMembers(); } } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.IO; using System.Text.RegularExpressions; namespace UMA.AssetBundles { public class UMAAssetBundleManagerSettings : EditorWindow { #region PUBLIC FIELDS public const string DEFAULT_ENCRYPTION_SUFFIX = "encrypted"; #endregion #region PRIVATE FIELDS //AssetBundle settings related string currentEncryptionPassword = ""; string newEncryptionPassword = ""; string currentEncryptionSuffix = ""; string newEncryptionSuffix = ""; bool currentEncodeNamesSetting = false; #if ENABLE_IOS_APP_SLICING bool currentAppSlicingSetting = false; #endif bool newEncodeNamesSetting = false; //DOS MODIFIED 14/11/2017 added a ability to set the new bundlesPlayerVersion value bool _enableBundleIndexVersioning; //either automatically use the Buildversion from player settings or specify a value here UMAABMSettingsStore.BundleIndexVersioningOpts _bundleIndexVersioningMethod = UMAABMSettingsStore.BundleIndexVersioningOpts.UseBuildVersion; //if useBundlesVersioning is set to Custom this value is used when the bundles are built string _bundleIndexCustomValue = "0.0"; //server related bool _enableLocalAssetBundleServer; int _port; string _statusMessage; string[] _hosts; string _activeHost; bool portError = false; bool serverException = false; //Testing Build related bool developmentBuild = false; //GUI related Vector2 scrollPos; bool serverRequestLogOpen = true; bool manualEditEncryptionKey = false; bool encryptionSaveButEnabled = false; bool manualEditEncryptionSuffix = false; bool encryptionKeysEnabled = false; #endregion #region PUBLIC PROPERTIES #endregion #region PRIVATE PROPERTIES //server related bool EnableLocalAssetBundleServer { get { return _enableLocalAssetBundleServer; } set { if (_enableLocalAssetBundleServer == value) return; _enableLocalAssetBundleServer = value; EditorPrefs.SetBool(Application.dataPath+"LocalAssetBundleServerEnabled", value); UpdateServer(); } } int Port { get { return _port; } set { if (_port == value) return; _port = value; EditorPrefs.SetInt(Application.dataPath+"LocalAssetBundleServerPort", _port); UpdateServer(); } } string ActiveHost { get { return _activeHost; } set { if (_activeHost == value) return; _activeHost = value; EditorPrefs.SetString(Application.dataPath+"LocalAssetBundleServerURL", _activeHost); } } #endregion #region BASE METHODS [MenuItem("Assets/AssetBundles/UMA Asset Bundle Manager Settings")] [MenuItem("UMA/UMA Asset Bundle Manager Settings")] static void Init() { UMAAssetBundleManagerSettings window = (UMAAssetBundleManagerSettings)EditorWindow.GetWindow<UMAAssetBundleManagerSettings>("UMA AssetBundle Manager"); window.Show(); } void OnFocus() { encryptionKeysEnabled = UMAABMSettings.GetEncryptionEnabled(); currentEncryptionPassword = newEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); currentEncryptionSuffix = newEncryptionSuffix = UMAABMSettings.GetEncryptionSuffix(); if (currentEncryptionSuffix == "") currentEncryptionSuffix = newEncryptionSuffix = DEFAULT_ENCRYPTION_SUFFIX; currentEncodeNamesSetting = newEncodeNamesSetting = UMAABMSettings.GetEncodeNames(); #if ENABLE_IOS_APP_SLICING currentAppSlicingSetting = UMAABMSettings.GetBuildForSlicing(); #endif _enableBundleIndexVersioning = UMAABMSettings.EnableBundleIndexVersioning; } void OnEnable() { encryptionKeysEnabled = UMAABMSettings.GetEncryptionEnabled(); currentEncryptionPassword = newEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); currentEncryptionSuffix = newEncryptionSuffix = UMAABMSettings.GetEncryptionSuffix(); if (currentEncryptionSuffix == "") currentEncryptionSuffix = newEncryptionSuffix = DEFAULT_ENCRYPTION_SUFFIX; currentEncodeNamesSetting = newEncodeNamesSetting = UMAABMSettings.GetEncodeNames(); #if ENABLE_IOS_APP_SLICING currentAppSlicingSetting = UMAABMSettings.GetBuildForSlicing(); #endif _enableBundleIndexVersioning = UMAABMSettings.EnableBundleIndexVersioning; //localAssetBundleServer status _enableLocalAssetBundleServer = EditorPrefs.GetBool(Application.dataPath+"LocalAssetBundleServerEnabled"); _port = EditorPrefs.GetInt(Application.dataPath + "LocalAssetBundleServerPort", 7888); //When the window is opened we still need to tell the user if the port is available so if (!_enableLocalAssetBundleServer) { UpdateServer(true); ServerStop(); if (serverException) portError = true; } else { UpdateServer(); } } void Start() { ServerStart(); } void OnDisable() { //Makes the Local server stop when the window is closed //also prevents the 'Listener already in use' error when the window is closed and opened ServerStop(); } #endregion #region SERVER RELATED METHODS void ServerStart() { SimpleWebServer.Start(_port); _statusMessage = "Server Running"; UpdateHosts(); if (_activeHost == null) { ActiveHost = _hosts[0]; } SimpleWebServer.ServerURL = ActiveHost; } void ServerStop() { if (SimpleWebServer.Instance != null) { SimpleWebServer.Instance.Stop(); SimpleWebServer.ServerURL = ""; _statusMessage = "Server Stopped"; _hosts = null; } } void UpdateHosts() { var strHostName = System.Net.Dns.GetHostName(); var list = new System.Collections.Generic.List<string>(); try { var ipEntry = System.Net.Dns.GetHostEntry(strHostName); foreach (var addr in ipEntry.AddressList) { if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { list.Add(string.Format("http://{0}:{1}/", addr, Port)); } } } catch(Exception ex) { if (Debug.isDebugBuild) Debug.Log(ex.Message); strHostName = "localhost"; } if (list.Count == 0) { list.Add(string.Format("http://localhost:{0}/", Port)); } portError = false; _hosts = list.ToArray(); } private void UpdateServer(bool test = false) { serverException = false; try { if (SimpleWebServer.Instance != null) { if (!EnableLocalAssetBundleServer) { ServerStop(); if (Debug.isDebugBuild) Debug.Log("Server Stopped"); } else if (SimpleWebServer.Instance.Port != _port) { ServerStop(); ServerStart(); if (Debug.isDebugBuild) Debug.Log("Server Started"); } } else if (EnableLocalAssetBundleServer || test) { ServerStart(); if (!test) { if (Debug.isDebugBuild) Debug.Log("Server Started"); } } } catch (Exception e) { _statusMessage = string.Format("Simple Webserver Exception: {0}\nStack Trace\n{1}", e.ToString(), e.StackTrace); if (Debug.isDebugBuild) Debug.LogException(e); EditorPrefs.SetBool(Application.dataPath + "LocalAssetBundleServerEnabled", false); EnableLocalAssetBundleServer = false; serverException = true; ServerStop(); } } #endregion void OnGUI() { scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, true); EditorGUILayout.BeginVertical(GUILayout.Width(EditorGUIUtility.currentViewWidth - 20f)); EditorGUILayout.Space(); GUILayout.Label("UMA AssetBundle Manager", EditorStyles.boldLabel); BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f)); GUILayout.Label("AssetBundle Options", EditorStyles.boldLabel); //AssetBundle Build versioning EditorGUI.BeginChangeCheck(); _enableBundleIndexVersioning = EditorGUILayout.ToggleLeft("Enable AssetBundle Index Versioning", _enableBundleIndexVersioning); if (EditorGUI.EndChangeCheck()) { UMAABMSettings.EnableBundleIndexVersioning = _enableBundleIndexVersioning; } if (_enableBundleIndexVersioning) { BeginVerticalIndented(10, new Color(0.75f, 0.875f, 1f)); EditorGUILayout.HelpBox("Sets the 'bundlesPlayerVersion' value of the AssetBundleIndex when you build your bundles. You can use this to determine if your app needs to force the user to go online to update their bundles and/or application (its up to you how you do that though!). ", MessageType.Info); EditorGUI.BeginChangeCheck(); _bundleIndexVersioningMethod = (UMAABMSettingsStore.BundleIndexVersioningOpts)EditorGUILayout.EnumPopup("Bundles Versioning Method", _bundleIndexVersioningMethod); if (EditorGUI.EndChangeCheck()) { UMAABMSettings.BundleIndexVersioningMethod = _bundleIndexVersioningMethod; } if(_bundleIndexVersioningMethod == UMAABMSettingsStore.BundleIndexVersioningOpts.Custom) { EditorGUI.BeginChangeCheck(); _bundleIndexCustomValue = EditorGUILayout.TextField("Bundles Index Player Version", _bundleIndexCustomValue); if (EditorGUI.EndChangeCheck()) { UMAABMSettings.BundleIndexCustomValue = _bundleIndexCustomValue; } } else { var currentBuildVersion = Application.version; if (string.IsNullOrEmpty(currentBuildVersion)) { EditorGUILayout.HelpBox("Please be sure to set a 'Version' number (eg 1.0, 2.1.0) in Edit->ProjectSettings->Player->Version", MessageType.Warning); } else { EditorGUILayout.HelpBox("Current 'Version' number ("+currentBuildVersion+ ") will be used. You can change this in Edit->ProjectSettings->Player->Version.", MessageType.Info); } } EditorGUILayout.Space(); EndVerticalIndented(); } //Asset Bundle Encryption //defined here so we can modify the message if encryption settings change string buildBundlesMsg = ""; MessageType buildBundlesMsgType = MessageType.Info; EditorGUI.BeginChangeCheck(); encryptionKeysEnabled = EditorGUILayout.ToggleLeft("Enable AssetBundle Encryption", encryptionKeysEnabled); if (EditorGUI.EndChangeCheck()) { //If encryption was turned ON generate the encryption password if necessary if (encryptionKeysEnabled) { if (currentEncryptionPassword == "") { if (UMAABMSettings.GetEncryptionPassword() != "") currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); else currentEncryptionPassword = EncryptionUtil.GenerateRandomPW(); } UMAABMSettings.SetEncryptionPassword(currentEncryptionPassword); buildBundlesMsg = "You have turned on encryption and need to Rebuild your bundles to encrypt them."; buildBundlesMsgType = MessageType.Warning; } else { UMAABMSettings.DisableEncryption(); currentEncryptionPassword = ""; } } if (encryptionKeysEnabled) { BeginVerticalIndented(10, new Color(0.75f, 0.875f, 1f)); //tip EditorGUILayout.HelpBox("Make sure you turn on 'Use Encrypted Bundles' in the 'DynamicAssetLoader' components in your scenes.", MessageType.Info); //Encryption key //If we can work out a way for people to download a key we can use this tip and the 'EncryptionKeyURL' field //string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt. If you use the 'Encryption Key URL' field below you MUST ensure this field is set to the same key the url will return."; string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt."; EditorGUILayout.LabelField(new GUIContent("Bundle Encryption Password", encryptionKeyToolTip)); EditorGUILayout.BeginHorizontal(); if (!manualEditEncryptionKey) { if(GUILayout.Button(new GUIContent("Edit", encryptionKeyToolTip))) { manualEditEncryptionKey = true; } EditorGUI.BeginDisabledGroup(!manualEditEncryptionKey); EditorGUILayout.TextField("", UMAABMSettings.GetEncryptionPassword());//THis bloody field WILL NOT update when you click edit, then canel, the value stays EditorGUI.EndDisabledGroup(); } else { EditorGUI.BeginChangeCheck(); newEncryptionPassword = EditorGUILayout.TextArea(newEncryptionPassword); if (EditorGUI.EndChangeCheck()) { encryptionSaveButEnabled = EncryptionUtil.PasswordValid(newEncryptionPassword); } if (encryptionSaveButEnabled) { if (GUILayout.Button(new GUIContent("Save"), GUILayout.MaxWidth(60))) { currentEncryptionPassword = newEncryptionPassword; UMAABMSettings.SetEncryptionPassword(newEncryptionPassword); EditorGUIUtility.keyboardControl = 0; manualEditEncryptionKey = false; } } else { GUI.enabled = false; if (GUILayout.Button(new GUIContent("Save", "Your Encryptiom Password should be at least 16 characters long"), GUILayout.MaxWidth(60))) { //Do nothing } GUI.enabled = true; } if (GUILayout.Button(new GUIContent("Cancel", "Reset to previous value: "+ currentEncryptionPassword), GUILayout.MaxWidth(60))) { manualEditEncryptionKey = false; newEncryptionPassword = currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); encryptionSaveButEnabled = false; EditorGUIUtility.keyboardControl = 0; } } EditorGUILayout.EndHorizontal(); //EncryptionKey URL //not sure how this would work- the delivered key would itself need to be encrypted probably //Encrypted bundle suffix string encryptionSuffixToolTip = "This suffix is appled to the end of your encrypted bundle names when they are built. Must be lower case and alphaNumeric. Cannot be empty. Defaults to "+DEFAULT_ENCRYPTION_SUFFIX; EditorGUILayout.LabelField(new GUIContent("Encrypted Bundle Suffix", encryptionSuffixToolTip)); EditorGUILayout.BeginHorizontal(); if (!manualEditEncryptionSuffix) { if (GUILayout.Button(new GUIContent("Edit", encryptionSuffixToolTip))) { manualEditEncryptionSuffix = true; } EditorGUI.BeginDisabledGroup(!manualEditEncryptionSuffix); EditorGUILayout.TextField(new GUIContent("", encryptionSuffixToolTip), currentEncryptionSuffix); EditorGUI.EndDisabledGroup(); } else { newEncryptionSuffix = EditorGUILayout.TextArea(newEncryptionSuffix); if (GUILayout.Button(new GUIContent("Save"))) { if (newEncryptionSuffix != "") { Regex rgx = new Regex("[^a-zA-Z0-9 -]"); var suffixToSend = rgx.Replace(newEncryptionSuffix, ""); currentEncryptionSuffix = suffixToSend; UMAABMSettings.SetEncryptionSuffix(suffixToSend.ToLower()); EditorGUIUtility.keyboardControl = 0; manualEditEncryptionSuffix = false; } } } EditorGUILayout.EndHorizontal(); //Encode Bundle Names string encodeBundleNamesTooltip = "If true encrypted bundle names will be base64 encoded"; EditorGUI.BeginChangeCheck(); newEncodeNamesSetting = EditorGUILayout.ToggleLeft(new GUIContent("Encode Bundle Names", encodeBundleNamesTooltip), currentEncodeNamesSetting); if (EditorGUI.EndChangeCheck()) { currentEncodeNamesSetting = newEncodeNamesSetting; UMAABMSettings.SetEncodeNames(newEncodeNamesSetting); } EndVerticalIndented(); } #if ENABLE_IOS_APP_SLICING string AppSlicingTooltip = "If true will build bundles uncompressed for use with iOS Resources Catalogs"; EditorGUI.BeginChangeCheck(); bool newAppSlicingSetting = EditorGUILayout.ToggleLeft(new GUIContent("Build for iOS App Slicing", AppSlicingTooltip), currentAppSlicingSetting); if (EditorGUI.EndChangeCheck()) { currentAppSlicingSetting = newAppSlicingSetting; UMAABMSettings.SetBuildForSlicing(newAppSlicingSetting); } #endif //Asset Bundle Building EditorGUILayout.Space(); string buttonBuildAssetBundlesText = "Build AssetBundles"; //Now defined above the encryption //string buildBundlesText = "Click the button below to build your bundles if you have not done so already."; string fullPathToBundles = Path.Combine(Directory.GetParent(Application.dataPath).FullName, Utility.AssetBundlesOutputPath); string fullPathToPlatformBundles = Path.Combine(fullPathToBundles, Utility.GetPlatformName()); //if we have not built any asset bundles there wont be anything in the cache to clear bool showClearCache = false; if (Directory.Exists(fullPathToPlatformBundles)) { buttonBuildAssetBundlesText = "Rebuild AssetBundles"; buildBundlesMsg = buildBundlesMsg == "" ? "Rebuild your assetBundles to reflect your latest changes" : buildBundlesMsg; showClearCache = true; } else { buildBundlesMsg = "You have not built your asset bundles for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " yet. Click this button to build them."; buildBundlesMsgType = MessageType.Warning; showClearCache = false; } EditorGUILayout.HelpBox(buildBundlesMsg, buildBundlesMsgType); if (GUILayout.Button(buttonBuildAssetBundlesText)) { BuildScript.BuildAssetBundles(); #if UNITY_2017_1_OR_NEWER Caching.ClearCache (); #else Caching.CleanCache(); #endif GUIUtility.ExitGUI(); } EndVerticalPadded(5); EditorGUILayout.Space(); //Local AssetBundleServer BeginVerticalPadded(5f, new Color(0.75f, 0.875f, 1f)); GUILayout.Label("AssetBundle Testing Server", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Once you have built your bundles this local Testing Server can be enabled and it will load those AssetBundles rather than the files inside the project.", MessageType.Info); if (!BuildScript.CanRunLocally(EditorUserBuildSettings.activeBuildTarget)) { EditorGUILayout.HelpBox("Builds for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " cannot access this local server, but you can still use it in the editor.", MessageType.Warning); } bool updateURL = false; EnableLocalAssetBundleServer = EditorGUILayout.Toggle("Start Server", EnableLocalAssetBundleServer); //If the server is off we need to show the user a message telling them that they will have to have uploaded their bundles to an external server //and that they need to set the address of that server in DynamicAssetLoader int newPort = Port; EditorGUI.BeginChangeCheck(); newPort = EditorGUILayout.IntField("Port", Port); if (EditorGUI.EndChangeCheck()) { if (newPort != Port) { if (_activeHost != null && _activeHost != "") ActiveHost = _activeHost.Replace(":" + Port.ToString(), ":" + newPort.ToString()); Port = newPort; UpdateHosts(); //we need to start the server to see if it works with this port- regardless of whether it is turned on or not. if (!EnableLocalAssetBundleServer) { UpdateServer(true); } else { UpdateServer(); } if (serverException == false) { //We can use the set IP with this port so update it if (EnableLocalAssetBundleServer) SimpleWebServer.ServerURL = ActiveHost; } else { //We CANT use the set IP with this port so set the saved URL to "" and tell the user the Port is in use elsewhere SimpleWebServer.ServerURL = ""; EnableLocalAssetBundleServer = false; portError = true; } } } if (!EnableLocalAssetBundleServer) { if (portError) EditorGUILayout.HelpBox("There are no hosts available for that port. Its probably in use by another application. Try another.", MessageType.Warning); else { EditorGUILayout.HelpBox("When the local server is not running the game will play in Simulation Mode OR if you have set the 'RemoteServerURL' for each DynamicAssetLoader, bundles will be downloaded from that location.", MessageType.Warning); if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebGL) { EditorGUILayout.HelpBox("WARNING: AssetBundles in WebGL builds that you run locally WILL NOT WORK unless the local server is turned on, and you build using the button below!", MessageType.Warning); } } } EditorGUILayout.Space(); if (_hosts != null && _hosts.Length > 0 && EnableLocalAssetBundleServer) { if (_activeHost == null || _activeHost == "") { ActiveHost = _hosts[0]; } int activeHostInt = 0; string[] hostsStrings = new string[_hosts.Length]; for (int i = 0; i < _hosts.Length; i++) { hostsStrings[i] = _hosts[i].Replace("http://", "").TrimEnd(new char[] { '/' }); if (_hosts[i] == _activeHost) { activeHostInt = i; } } EditorGUI.BeginChangeCheck(); int newActiveHostInt = EditorGUILayout.Popup("Host Address: http://", activeHostInt, hostsStrings); if (EditorGUI.EndChangeCheck()) { if (newActiveHostInt != activeHostInt) { ActiveHost = _hosts[newActiveHostInt]; updateURL = true; } } } EditorGUILayout.Space(); if (showClearCache)//no point in showing a button for bundles that dont exist - or is there? The user might be using a remote url to download assetbundles without the localserver? { EditorGUILayout.HelpBox("You can clear the cache to force asset bundles to be redownloaded.", MessageType.Info); if (GUILayout.Button("Clean the Cache")) { #if UNITY_2017_1_OR_NEWER _statusMessage = Caching.ClearCache() ? "Cache Cleared." : "Error clearing cache."; #else _statusMessage = Caching.CleanCache() ? "Cache Cleared." : "Error clearing cache."; #endif } EditorGUILayout.Space(); } EditorGUILayout.Space(); GUILayout.Label("Server Status"); if (_statusMessage != null) { EditorGUILayout.HelpBox(_statusMessage, MessageType.None); } if (SimpleWebServer.Instance != null) { //GUILayout.Label("Server Request Log"); serverRequestLogOpen = EditorGUILayout.Foldout(serverRequestLogOpen, "Server Request Log"); if(serverRequestLogOpen) EditorGUILayout.HelpBox(SimpleWebServer.Instance.GetLog(), MessageType.Info); } if (updateURL) { SimpleWebServer.ServerURL = ActiveHost; } EndVerticalPadded(5); EditorGUILayout.Space(); //Testing Build- only show this if we can run a build for the current platform (i.e. if its not iOS or Android) if (BuildScript.CanRunLocally (EditorUserBuildSettings.activeBuildTarget)) { BeginVerticalPadded (5, new Color (0.75f, 0.875f, 1f)); GUILayout.Label ("Local Testing Build", EditorStyles.boldLabel); //if the bundles are built and the server is turned on then the user can use this option otherwise there is no point //But we will show them that this option is available even if this is not the case if (!showClearCache || !EnableLocalAssetBundleServer) { EditorGUI.BeginDisabledGroup (true); } EditorGUILayout.HelpBox ("Make a testing Build that uses the Local Server using the button below.", MessageType.Info); developmentBuild = EditorGUILayout.Toggle ("Development Build", developmentBuild); if (GUILayout.Button("Build and Run!")) { BuildScript.BuildAndRunPlayer(developmentBuild); GUIUtility.ExitGUI(); } else { if (!showClearCache || !EnableLocalAssetBundleServer) { EditorGUI.EndDisabledGroup(); } } } EditorGUILayout.Space(); EndVerticalPadded(5); EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } #region GUI HELPERS //these are copied from UMAs GUI Helper- but that is in an editor folder public static void BeginVerticalPadded(float padding, Color backgroundColor) { GUI.color = backgroundColor; GUILayout.BeginHorizontal(EditorStyles.textField); GUI.color = Color.white; GUILayout.Space(padding); GUILayout.BeginVertical(); GUILayout.Space(padding); } public static void EndVerticalPadded(float padding) { GUILayout.Space(padding); GUILayout.EndVertical(); GUILayout.Space(padding); GUILayout.EndHorizontal(); } public static void BeginVerticalIndented(float indentation, Color backgroundColor) { GUI.color = backgroundColor; GUILayout.BeginHorizontal(); GUILayout.Space(indentation); GUI.color = Color.white; GUILayout.BeginVertical(); } public static void EndVerticalIndented() { GUILayout.EndVertical(); GUILayout.EndHorizontal(); } #endregion } [System.Serializable] public class UMAABMSettingsStore { public enum BundleIndexVersioningOpts { UseBuildVersion, Custom } public bool encryptionEnabled = false; public string encryptionPassword = ""; public string encryptionSuffix = ""; public bool encodeNames = false; [Tooltip("If true will build uncompressed assetBundles for use with iOS resource catalogs")] public bool buildForAppSlicing = false; public bool enableBundleIndexVersioning; //either automatically use the Buildversion from player settings or specify a value here public BundleIndexVersioningOpts bundleIndexVersioningMethod = BundleIndexVersioningOpts.UseBuildVersion; //if useBundlesVersioning is set to Custom this value is used when the bundles are built public string bundleIndexCustomValue = "0.0"; public UMAABMSettingsStore() { } public UMAABMSettingsStore(bool _encryptionEnabled, string _encryptionPassword, string _encryptionSuffix, bool _encodeNames) { _encryptionEnabled = encryptionEnabled; encryptionPassword = _encryptionPassword; encryptionSuffix = _encryptionSuffix; encodeNames = _encodeNames; } } public static class UMAABMSettings { #region PUBLIC FIELDS //This is not just for Encryption settings any more so it has the wrong name- its editor only so we can change it... public const string SETTINGS_FILENAME = "UMAABMSettings-DoNotDelete.txt"; public const string SETTINGS_OLD_FILENAME = "UMAEncryptionSettings-DoNotDelete.txt"; private static UMAABMSettingsStore thisSettings; #endregion #region PROPERTIES //pretty much all of these should have been properties- sorry I didn't uderstand those very well at the time //This is better but we dont want to be doing GetThisSettings() either we want another property that does it once /// <summary> /// Is BundlesIndexVersioning enabled /// </summary> public static bool EnableBundleIndexVersioning { get { return GetThisSettings().enableBundleIndexVersioning; } set{ GetThisSettings().enableBundleIndexVersioning = value; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } } /// <summary> /// Does BundlesIndexversioning use a custom value or the Player build Value /// </summary> public static UMAABMSettingsStore.BundleIndexVersioningOpts BundleIndexVersioningMethod { get { return GetThisSettings().bundleIndexVersioningMethod; } set { GetThisSettings().bundleIndexVersioningMethod = value; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } } /// <summary> /// A custom value for bundleIndexVersioning /// </summary> public static string BundleIndexCustomValue { get { return GetThisSettings().bundleIndexCustomValue; } set { GetThisSettings().bundleIndexCustomValue = value; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } } #endregion #region STATIC LOAD SAVE Methods private static UMAABMSettingsStore GetThisSettings() { thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); return thisSettings; } private static string GetSettingsFolderPath() { return FileUtils.GetInternalDataStoreFolder(false,true); } //we are saving the encryptions settings to a text file so that teams working on the same project/ github etc/ can all use the same settings public static UMAABMSettingsStore GetEncryptionSettings() { if(File.Exists(Path.Combine(GetSettingsFolderPath(), SETTINGS_OLD_FILENAME))) { //we need to write the data from the old file into the new file and delete the old one... File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), File.ReadAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_OLD_FILENAME))); File.Delete(Path.Combine(GetSettingsFolderPath(), SETTINGS_OLD_FILENAME)); } if (!File.Exists(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME))) return null; else return JsonUtility.FromJson<UMAABMSettingsStore>(File.ReadAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME))); } public static bool GetEncryptionEnabled() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else if (thisSettings.encryptionEnabled && thisSettings.encryptionPassword != "") return true; else return false; } public static string GetEncryptionPassword() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return ""; else return thisSettings.encryptionPassword; } public static string GetEncryptionSuffix() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return ""; else return thisSettings.encryptionSuffix; } public static bool GetEncodeNames() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else return thisSettings.encodeNames; } /// <summary> /// Should the bundles be built for use with iOS app slicing /// </summary> public static bool GetBuildForSlicing() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else return thisSettings.buildForAppSlicing; } public static void ClearEncryptionSettings() { var thisSettings = GetEncryptionSettings(); var newSettings = new UMAABMSettingsStore(); newSettings.buildForAppSlicing = thisSettings.buildForAppSlicing; newSettings.bundleIndexCustomValue = thisSettings.bundleIndexCustomValue; newSettings.bundleIndexVersioningMethod = thisSettings.bundleIndexVersioningMethod; newSettings.enableBundleIndexVersioning = thisSettings.enableBundleIndexVersioning; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(newSettings)); } public static void SetEncryptionSettings(bool encryptionEnabled, string encryptionPassword = "", string encryptionSuffix = "", bool? encodeNames = null) { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.encryptionEnabled = encryptionEnabled; thisSettings.encryptionPassword = encryptionPassword != "" ? encryptionPassword : thisSettings.encryptionPassword; thisSettings.encryptionSuffix = encryptionSuffix != "" ? encryptionSuffix : thisSettings.encryptionSuffix; thisSettings.encodeNames = encodeNames != null ? (bool)encodeNames : thisSettings.encodeNames; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } /// <summary> /// Turns encryption OFF /// </summary> public static void DisableEncryption() { SetEncryptionSettings(false); } /// <summary> /// Turns encryption ON ands sets the given password (cannot be blank) /// </summary> public static void SetEncryptionPassword(string encryptionPassword) { if (encryptionPassword != "") { SetEncryptionSettings(true, encryptionPassword); } } /// <summary> /// Turns encryption OFF ands unsets any existing password /// </summary> public static void UnsetEncryptionPassword() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.encryptionEnabled = false; thisSettings.encryptionPassword = ""; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } /// <summary> /// Turns encryption ON ands sets the given encryption suffix (cannot be blank) /// </summary> public static void SetEncryptionSuffix(string encryptionSuffix) { if (encryptionSuffix != "") { SetEncryptionSettings(true, "", encryptionSuffix); } } /// <summary> /// Turns encryption ON ands sets the encode names setting /// </summary> public static void SetEncodeNames(bool encodeNames) { SetEncryptionSettings(true,"", "", encodeNames); } /// <summary> /// Should the bundles be built for use with iOS app slicing /// </summary> public static void SetBuildForSlicing(bool enabled) { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.buildForAppSlicing = enabled; } #endregion } } #endif
/* * * (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. * */ namespace ASC.Mail.Net.IMAP.Client { #region usings using System; using System.IO; using System.Text; using Mime; using Server; #endregion /// <summary> /// IMAP fetch item. /// </summary> public class IMAP_FetchItem { #region Members private readonly string m_BodyStructure = ""; private readonly byte[] m_Data; private readonly string m_Envelope = ""; private readonly IMAP_FetchItem_Flags m_FetchFlags = IMAP_FetchItem_Flags.MessageFlags; private readonly IMAP_MessageFlags m_Flags = IMAP_MessageFlags.Recent; private readonly string m_InternalDate = ""; private readonly int m_No; private readonly int m_Size; private readonly int m_UID; #endregion #region Properties /// <summary> /// Specifies what data this IMAP_FetchItem contains. This is flagged value and can contain multiple values. /// </summary> public IMAP_FetchItem_Flags FetchFlags { get { return m_FetchFlags; } } /// <summary> /// Gets number of message in folder. /// </summary> public int MessageNumber { get { return m_No; } } /// <summary> /// Gets message UID. This property is available only if IMAP_FetchItem_Flags.UID was specified, /// otherwise throws exception. /// </summary> public int UID { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.UID) == 0) { throw new Exception( "IMAP_FetchItem_Flags.UID wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_UID; } } /// <summary> /// Gets message size. This property is available only if IMAP_FetchItem_Flags.Size was specified, /// otherwise throws exception. /// </summary> public int Size { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.Size) == 0) { throw new Exception( "IMAP_FetchItem_Flags.Size wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_Size; } } /// <summary> /// Gets message IMAP server INTERNAL date. This property is available only if IMAP_FetchItem_Flags.InternalDate was specified, /// otherwise throws exception. /// </summary> public DateTime InternalDate { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.InternalDate) == 0) { throw new Exception( "IMAP_FetchItem_Flags.InternalDate wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return IMAP_Utils.ParseDate(m_InternalDate); } } /// <summary> /// Gets message flags. This property is available only if IMAP_FetchItem_Flags.MessageFlags was specified, /// otherwise throws exception. /// </summary> public IMAP_MessageFlags MessageFlags { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.MessageFlags) == 0) { throw new Exception( "IMAP_FetchItem_Flags.MessageFlags wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_Flags; } } /// <summary> /// Gets message IMAP ENVELOPE. This property is available only if IMAP_FetchItem_Flags.Envelope was specified, /// otherwise throws exception. /// </summary> public IMAP_Envelope Envelope { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.Envelope) == 0) { throw new Exception( "IMAP_FetchItem_Flags.Envelope wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } IMAP_Envelope envelope = new IMAP_Envelope(); envelope.Parse(m_Envelope); return envelope; } } /// <summary> /// Gets message IMAP BODYSTRUCTURE. This property is available only if IMAP_FetchItem_Flags.BodyStructure was specified, /// otherwise throws exception. /// </summary> public IMAP_BODY BodyStructure { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.BodyStructure) == 0) { throw new Exception( "IMAP_FetchItem_Flags.BodyStructure wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } IMAP_BODY bodyStructure = new IMAP_BODY(); bodyStructure.Parse(m_BodyStructure); return bodyStructure; } } /// <summary> /// Gets message header data. This property is available only if IMAP_FetchItem_Flags.Header was specified, /// otherwise throws exception. /// </summary> public byte[] HeaderData { get { if ( !((m_FetchFlags & IMAP_FetchItem_Flags.Header) != 0 || (m_FetchFlags & IMAP_FetchItem_Flags.Message) != 0)) { throw new Exception( "IMAP_FetchItem_Flags.Header wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } if ((m_FetchFlags & IMAP_FetchItem_Flags.Message) != 0) { return Encoding.ASCII.GetBytes(MimeUtils.ParseHeaders(new MemoryStream(m_Data))); } else { return m_Data; } } } /// <summary> /// Gets message data. This property is available only if IMAP_FetchItem_Flags.Message was specified, /// otherwise throws exception. /// </summary> public byte[] MessageData { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.Message) == 0) { throw new Exception( "IMAP_FetchItem_Flags.Message wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return m_Data; } } /// <summary> /// Gets if message is unseen. This property is available only if IMAP_FetchItem_Flags.MessageFlags was specified, /// otherwise throws exception. /// </summary> public bool IsNewMessage { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.MessageFlags) == 0) { throw new Exception( "IMAP_FetchItem_Flags.MessageFlags wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return (m_Flags & IMAP_MessageFlags.Seen) == 0; } } /// <summary> /// Gets if message is answered. This property is available only if IMAP_FetchItem_Flags.MessageFlags was specified, /// otherwise throws exception. /// </summary> public bool IsAnswered { get { if ((m_FetchFlags & IMAP_FetchItem_Flags.MessageFlags) == 0) { throw new Exception( "IMAP_FetchItem_Flags.MessageFlags wasn't specified in FetchMessages command, becuse of it this property is unavailable."); } return (m_Flags & IMAP_MessageFlags.Answered) != 0; } } /// <summary> /// Gets message data(headers or full message), it depends on HeadersOnly property. /// </summary> [Obsolete("Use HeaderData or MessageData data instead.")] public byte[] Data { get { return m_Data; } } /// <summary> /// Gets if headers or full message requested in fetch. /// </summary> [Obsolete("Use FetchFlags property instead !")] public bool HeadersOnly { get { return (m_FetchFlags & IMAP_FetchItem_Flags.Header) != 0; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="no">Number of message in folder.</param> /// <param name="uid">Message UID.</param> /// <param name="size">Message size.</param> /// <param name="data">Message data.</param> /// <param name="flags">Message flags.</param> /// <param name="internalDate">Message INTERNALDATE.</param> /// <param name="envelope">Envelope string.</param> /// <param name="bodyStructure">BODYSTRUCTURE string.</param> /// <param name="fetchFlags">Specifies what data fetched from IMAP server.</param> internal IMAP_FetchItem(int no, int uid, int size, byte[] data, IMAP_MessageFlags flags, string internalDate, string envelope, string bodyStructure, IMAP_FetchItem_Flags fetchFlags) { m_No = no; m_UID = uid; m_Size = size; m_Data = data; m_Flags = flags; m_InternalDate = internalDate; m_Envelope = envelope; m_FetchFlags = fetchFlags; m_BodyStructure = bodyStructure; } #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. /** This testcase attempts to delete some directories in a mounted volume - Different drive is mounted on the current drive - Current drive is mounted on a different drive - Current drive is mounted on current directory - refer to the directory in a recursive manner in addition to the normal one **/ using System; using System.IO; using System.Text; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; public class Directory_Delete_MountVolume { private delegate void ExceptionCode(); private static bool s_pass = true; [Fact] [ActiveIssue(1221)] [PlatformSpecific(TestPlatforms.Windows)] // testing volumes / mounts / drive letters public static void RunTest() { try { const String MountPrefixName = "LaksMount"; String mountedDirName; String dirName; String dirNameWithoutRoot; String dirNameReferedFromMountedDrive; //Adding debug info since this test hangs sometime in RTS runs String debugFileName = "Co7604Delete_MountVolume_Debug.txt"; DeleteFile(debugFileName); String scenarioDescription; scenarioDescription = "Scenario 1: Vanilla - Different drive is mounted on the current drive"; try { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent(); //out labs use UIP tools in one drive and don't expect this drive to be used by others. We avoid this problem by not testing if the other drive is not NTFS if (FileSystemDebugInfo.IsCurrentDriveNTFS() && otherDriveInMachine != null) { Console.WriteLine(scenarioDescription); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", otherDriveInMachine.Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(otherDriveInMachine.Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(otherDriveInMachine, ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_3974g! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_20387g! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } else File.AppendAllText(debugFileName, String.Format("Scenario 1 - Vanilla - NOT RUN: Different drive is mounted on the current drive {0}", Environment.NewLine)); } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_768lme! Exception caught in scenario: {0}", ex); } scenarioDescription = "Scenario 2: Current drive is mounted on a different drive"; Console.WriteLine(scenarioDescription); File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); try { string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent(); if (otherDriveInMachine != null) { mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(otherDriveInMachine.Substring(0, 3), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_239ufz! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_794aiu! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_231vwf! Exception caught in scenario: {0}", ex); } //scenario 3.1: Current drive is mounted on current drive scenarioDescription = "Scenario 3.1 - Current drive is mounted on current drive"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_324eez! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_195whv! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_493ojg! Exception caught in scenario: {0}", ex); } //scenario 3.2: Current drive is mounted on current directory scenarioDescription = "Scenario 3.2 - Current drive is mounted on current directory"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100)) { Eval(Directory.Exists(dirName), "Err_951ipb! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); //Lets refer to these via mounted drive and check dirNameWithoutRoot = dirName.Substring(3); dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot); Directory.Delete(dirNameReferedFromMountedDrive, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_493yin! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); } } finally { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_432qcp! Exception caught in scenario: {0}", ex); } //@WATCH - potentially dangerous code - can delete the whole drive!! //scenario 3.3: we call delete on the mounted volume - this should only delete the mounted drive? //Current drive is mounted on current directory scenarioDescription = "Scenario 3.3 - we call delete on the mounted volume"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName)); try { Directory.CreateDirectory(mountedDirName); File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); Directory.Delete(mountedDirName, true); Task.Delay(300).Wait(); } finally { if (!Eval(!Directory.Exists(mountedDirName), "Err_001yph! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName))) { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_386rpj! Exception caught in scenario: {0}", ex); } //@WATCH - potentially dangerous code - can delete the whole drive!! //scenario 3.4: we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files //Current drive is mounted on current directory scenarioDescription = "Scenario 3.4 - we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = null; try { dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 2, 20)) { Eval(Directory.Exists(dirName), "Err_469yvh! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); String[] dirs = fileManager.GetDirectories(1); mountedDirName = Path.GetFullPath(dirs[0]); if (Eval(Directory.GetDirectories(mountedDirName).Length == 0, "Err_974tsg! the sub directory has directories: {0}", mountedDirName)) { foreach (String file in Directory.GetFiles(mountedDirName)) File.Delete(file); if (Eval(Directory.GetFiles(mountedDirName).Length == 0, "Err_13ref! the mounted directory has files: {0}", mountedDirName)) { File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); //now lets call delete on the parent directory Directory.Delete(dirName, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_006jsf! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); Console.WriteLine("Completed Scenario 3.4"); } } } } finally { if (!Eval(!Directory.Exists(mountedDirName), "Err_625ckx! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName))) { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_578tni! Exception caught in scenario: {0}", ex); } //@WATCH - potentially dangerous code - can delete the whole drive!! //scenario 3.5: we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files //we call a different directory than the first //Current drive is mounted on current directory scenarioDescription = "Scenario 3.5 - we call delete on parent directory of the mounted volume, the parent directory will have some other directories and files"; try { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) { File.AppendAllText(debugFileName, String.Format("{0}{1}", scenarioDescription, Environment.NewLine)); mountedDirName = null; try { dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName); File.AppendAllText(debugFileName, String.Format("Creating a sub tree at: {0}{1}", dirName, Environment.NewLine)); using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 2, 30)) { Eval(Directory.Exists(dirName), "Err_715tdq! Directory {0} doesn't exist: {1}", dirName, Directory.Exists(dirName)); String[] dirs = fileManager.GetDirectories(1); mountedDirName = Path.GetFullPath(dirs[0]); if (dirs.Length > 1) mountedDirName = Path.GetFullPath(dirs[1]); if (Eval(Directory.GetDirectories(mountedDirName).Length == 0, "Err_492qwl! the sub directory has directories: {0}", mountedDirName)) { foreach (String file in Directory.GetFiles(mountedDirName)) File.Delete(file); if (Eval(Directory.GetFiles(mountedDirName).Length == 0, "Err_904kij! the mounted directory has files: {0}", mountedDirName)) { File.AppendAllText(debugFileName, String.Format("Mounting on {0}{1}{2}", Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName, Environment.NewLine)); MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName); //now lets call delete on the parent directory Directory.Delete(dirName, true); Task.Delay(300).Wait(); Eval(!Directory.Exists(dirName), "Err_900edl! Directory {0} still exist: {1}", dirName, Directory.Exists(dirName)); Console.WriteLine("Completed Scenario 3.5: {0}", mountedDirName); } } } } finally { if (!Eval(!Directory.Exists(mountedDirName), "Err_462xtc! Directory {0} still exist: {1}", mountedDirName, Directory.Exists(mountedDirName))) { MountHelper.Unmount(mountedDirName); DeleteDir(mountedDirName, true); } } File.AppendAllText(debugFileName, String.Format("Completed scenario {0}", Environment.NewLine)); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_471jli! Exception caught in scenario: {0}", ex); } } catch (Exception ex) { s_pass = false; Console.WriteLine("Err_234rsgf! Uncaught exception in RunTest: {0}", ex); } finally { Assert.True(s_pass); } } private static void DeleteFile(String debugFileName) { if (File.Exists(debugFileName)) File.Delete(debugFileName); } private static void DeleteDir(String debugFileName, bool sub) { bool deleted = false; int maxAttempts = 5; while (!deleted && maxAttempts > 0) { if (Directory.Exists(debugFileName)) { try { Directory.Delete(debugFileName, sub); deleted = true; } catch (Exception) { if (--maxAttempts == 0) throw; else Task.Delay(300).Wait(); } } } } //Checks for error private static bool Eval(bool expression, String msg, params Object[] values) { return Eval(expression, String.Format(msg, values)); } private static bool Eval<T>(T actual, T expected, String errorMsg) { bool retValue = expected == null ? actual == null : expected.Equals(actual); if (!retValue) Eval(retValue, errorMsg + " Expected:" + (null == expected ? "<null>" : expected.ToString()) + " Actual:" + (null == actual ? "<null>" : actual.ToString())); return retValue; } private static bool Eval(bool expression, String msg) { if (!expression) { s_pass = false; Console.WriteLine(msg); } return expression; } //Checks for a particular type of exception private static void CheckException<E>(ExceptionCode test, string error) { CheckException<E>(test, error, null); } //Checks for a particular type of exception and an Exception msg in the English locale private static void CheckException<E>(ExceptionCode test, string error, String msgExpected) { bool exception = false; try { test(); error = String.Format("{0} Exception NOT thrown ", error); } catch (Exception e) { if (e.GetType() == typeof(E)) { exception = true; if (System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && msgExpected != null && e.Message != msgExpected) { exception = false; error = String.Format("{0} Message Different: <{1}>", error, e.Message); } } else error = String.Format("{0} Exception type: {1}", error, e.GetType().Name); } Eval(exception, error); } }