context
stringlengths
2.52k
185k
gt
stringclasses
1 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. using System; using System.Runtime.InteropServices; using System.Security.Cryptography; using Internal.Cryptography; using Microsoft.Win32.SafeHandles; using Internal.NativeCrypto; internal static partial class Interop { internal static partial class NCrypt { /// <summary> /// Generate a key from a secret agreement /// </summary> [DllImport(Interop.Libraries.NCrypt, CharSet = CharSet.Unicode)] private static extern ErrorCode NCryptDeriveKey( SafeNCryptSecretHandle hSharedSecret, string pwszKDF, [In] ref NCryptBufferDesc pParameterList, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbDerivedKey, int cbDerivedKey, [Out] out int pcbResult, SecretAgreementFlags dwFlags); /// <summary> /// Derive key material from a hash or HMAC KDF /// </summary> /// <returns></returns> private static byte[] DeriveKeyMaterial( SafeNCryptSecretHandle secretAgreement, string kdf, string hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend, SecretAgreementFlags flags) { // First marshal the hash algoritm IntPtr hashAlgorithmString = IntPtr.Zero; try { hashAlgorithmString = Marshal.StringToCoTaskMemUni(hashAlgorithm); Span<NCryptBuffer> parameters = stackalloc NCryptBuffer[4]; int parameterCount = 0; // We always need to marshal the hashing function NCryptBuffer hashAlgorithmBuffer = new NCryptBuffer(); hashAlgorithmBuffer.cbBuffer = (hashAlgorithm.Length + 1) * sizeof(char); hashAlgorithmBuffer.BufferType = BufferType.KdfHashAlgorithm; hashAlgorithmBuffer.pvBuffer = hashAlgorithmString; parameters[parameterCount] = hashAlgorithmBuffer; parameterCount++; unsafe { fixed (byte* pHmacKey = hmacKey, pSecretPrepend = secretPrepend, pSecretAppend = secretAppend) { // // Now marshal the other parameters // if (pHmacKey != null) { NCryptBuffer hmacKeyBuffer = new NCryptBuffer(); hmacKeyBuffer.cbBuffer = hmacKey.Length; hmacKeyBuffer.BufferType = BufferType.KdfHmacKey; hmacKeyBuffer.pvBuffer = new IntPtr(pHmacKey); parameters[parameterCount] = hmacKeyBuffer; parameterCount++; } if (pSecretPrepend != null) { NCryptBuffer secretPrependBuffer = new NCryptBuffer(); secretPrependBuffer.cbBuffer = secretPrepend.Length; secretPrependBuffer.BufferType = BufferType.KdfSecretPrepend; secretPrependBuffer.pvBuffer = new IntPtr(pSecretPrepend); parameters[parameterCount] = secretPrependBuffer; parameterCount++; } if (pSecretAppend != null) { NCryptBuffer secretAppendBuffer = new NCryptBuffer(); secretAppendBuffer.cbBuffer = secretAppend.Length; secretAppendBuffer.BufferType = BufferType.KdfSecretAppend; secretAppendBuffer.pvBuffer = new IntPtr(pSecretAppend); parameters[parameterCount] = secretAppendBuffer; parameterCount++; } return DeriveKeyMaterial( secretAgreement, kdf, parameters.Slice(0, parameterCount), flags); } } } finally { if (hashAlgorithmString != IntPtr.Zero) { Marshal.FreeCoTaskMem(hashAlgorithmString); } } } /// <summary> /// Derive key material using a given KDF and secret agreement /// </summary> private static unsafe byte[] DeriveKeyMaterial( SafeNCryptSecretHandle secretAgreement, string kdf, ReadOnlySpan<NCryptBuffer> parameters, SecretAgreementFlags flags) { fixed (NCryptBuffer* pParameters = &MemoryMarshal.GetReference(parameters)) { NCryptBufferDesc parameterDesc = new NCryptBufferDesc(); parameterDesc.ulVersion = 0; parameterDesc.cBuffers = parameters.Length; parameterDesc.pBuffers = new IntPtr(pParameters); // Figure out how big the key material is ErrorCode error = NCryptDeriveKey( secretAgreement, kdf, ref parameterDesc, null, 0, out int keySize, flags); if (error != ErrorCode.ERROR_SUCCESS && error != ErrorCode.NTE_BUFFER_TOO_SMALL) { throw error.ToCryptographicException(); } // Allocate memory for the key material and generate it byte[] keyMaterial = new byte[keySize]; error = NCryptDeriveKey( secretAgreement, kdf, ref parameterDesc, keyMaterial, keyMaterial.Length, out keySize, flags); if (error != ErrorCode.ERROR_SUCCESS) { throw error.ToCryptographicException(); } // Just in case it shrank the answer once it had a buffer. Array.Resize(ref keyMaterial, Math.Min(keySize, keyMaterial.Length)); return keyMaterial; } } /// <summary> /// Derive key material from a secret agreement using a hash KDF /// </summary> internal static byte[] DeriveKeyMaterialHash( SafeNCryptSecretHandle secretAgreement, string hashAlgorithm, byte[] secretPrepend, byte[] secretAppend, SecretAgreementFlags flags) { return DeriveKeyMaterial( secretAgreement, BCryptNative.KeyDerivationFunction.Hash, hashAlgorithm, null, secretPrepend, secretAppend, flags); } /// <summary> /// Derive key material from a secret agreement using a HMAC KDF /// </summary> internal static byte[] DeriveKeyMaterialHmac( SafeNCryptSecretHandle secretAgreement, string hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend, SecretAgreementFlags flags) { return DeriveKeyMaterial( secretAgreement, BCryptNative.KeyDerivationFunction.Hmac, hashAlgorithm, hmacKey, secretPrepend, secretAppend, flags); } /// <summary> /// Derive key material from a secret agreeement using the TLS KDF /// </summary> internal static byte[] DeriveKeyMaterialTls( SafeNCryptSecretHandle secretAgreement, byte[] label, byte[] seed, SecretAgreementFlags flags) { Span<NCryptBuffer> buffers = stackalloc NCryptBuffer[2]; unsafe { fixed (byte* pLabel = label, pSeed = seed) { NCryptBuffer labelBuffer = new NCryptBuffer(); labelBuffer.cbBuffer = label.Length; labelBuffer.BufferType = BufferType.KdfTlsLabel; labelBuffer.pvBuffer = new IntPtr(pLabel); buffers[0] = labelBuffer; NCryptBuffer seedBuffer = new NCryptBuffer(); seedBuffer.cbBuffer = seed.Length; seedBuffer.BufferType = BufferType.KdfTlsSeed; seedBuffer.pvBuffer = new IntPtr(pSeed); buffers[1] = seedBuffer; return DeriveKeyMaterial( secretAgreement, BCryptNative.KeyDerivationFunction.Tls, buffers, flags); } } } } }
// // ToolManager.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using Gtk; namespace Pinta.Core { public class ToolManager : IEnumerable<BaseTool> { int index = -1; int prev_index = -1; private List<BaseTool> Tools; public event EventHandler<ToolEventArgs> ToolAdded; public event EventHandler<ToolEventArgs> ToolRemoved; public ToolManager () { Tools = new List<BaseTool> (); } public void AddTool (BaseTool tool) { tool.ToolItem.Clicked += HandlePbToolItemClicked; tool.ToolItem.Sensitive = tool.Enabled; Tools.Add (tool); Tools.Sort (new ToolSorter ()); OnToolAdded (tool); if (CurrentTool == null) SetCurrentTool (tool); } public void RemoveInstanceOfTool (System.Type tool_type) { foreach (BaseTool tool in Tools) { if (tool.GetType () == tool_type) { tool.ToolItem.Clicked -= HandlePbToolItemClicked; tool.ToolItem.Active = false; tool.ToolItem.Sensitive = false; Tools.Remove (tool); Tools.Sort (new ToolSorter ()); SetCurrentTool(new DummyTool()); OnToolRemoved (tool); return; } } } void HandlePbToolItemClicked (object sender, EventArgs e) { ToggleToolButton tb = (ToggleToolButton)sender; BaseTool t = FindTool (tb.Label); // Don't let the user unselect the current tool if (CurrentTool != null && t.Name == CurrentTool.Name) { if (prev_index != index) tb.Active = true; return; } SetCurrentTool(t); } private BaseTool FindTool (string name) { name = name.ToLowerInvariant (); foreach (BaseTool tool in Tools) { if (tool.Name.ToLowerInvariant () == name) { return tool; } } return null; } public BaseTool CurrentTool { get { if (index >= 0) { return Tools[index];} else { DummyTool dummy = new DummyTool (); SetCurrentTool(dummy); return dummy; } } } public BaseTool PreviousTool { get { return Tools[prev_index]; } } public void Commit () { if (CurrentTool != null) CurrentTool.DoCommit (); } public void SetCurrentTool(BaseTool tool) { int i = Tools.IndexOf (tool); if (index == i) return; // Unload previous tool if needed if (index >= 0) { prev_index = index; Tools[index].DoClearToolBar (PintaCore.Chrome.ToolToolBar); Tools[index].DoDeactivated(tool); Tools[index].ToolItem.Active = false; } // Load new tool index = i; tool.ToolItem.Active = true; tool.DoActivated(); tool.DoBuildToolBar (PintaCore.Chrome.ToolToolBar); PintaCore.Workspace.Invalidate (); PintaCore.Chrome.SetStatusBarText (string.Format (" {0}: {1}", tool.Name, tool.StatusBarText)); } public bool SetCurrentTool (string tool) { BaseTool t = FindTool (tool); if (t != null) { SetCurrentTool(t); return true; } return false; } public void SetCurrentTool (Gdk.Key shortcut) { BaseTool tool = FindNextTool (shortcut); if (tool != null) SetCurrentTool(tool); } private BaseTool FindNextTool (Gdk.Key shortcut) { string key = shortcut.ToString ().ToUpperInvariant (); // Begin looking at the tool after the current one for (int i = index + 1; i < Tools.Count; i++) { if (Tools[i].ShortcutKey.ToString ().ToUpperInvariant () == key) return Tools[i]; } // Begin at the beginning and look up to the current tool for (int i = 0; i < index; i++) { if (Tools[i].ShortcutKey.ToString ().ToUpperInvariant () == key) return Tools[i]; } return null; } private void OnToolAdded (BaseTool tool) { if (ToolAdded != null) ToolAdded (this, new ToolEventArgs (tool)); } private void OnToolRemoved (BaseTool tool) { if (ToolRemoved != null) ToolRemoved (this, new ToolEventArgs (tool)); } #region IEnumerable<BaseTool> implementation public IEnumerator<BaseTool> GetEnumerator () { return Tools.GetEnumerator (); } #endregion #region IEnumerable implementation System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return Tools.GetEnumerator (); } #endregion class ToolSorter : Comparer<BaseTool> { public override int Compare (BaseTool x, BaseTool y) { return x.Priority - y.Priority; } } } //This tool does nothing, is used when no tools are in toolbox. If used seriously will probably // throw a zillion exceptions due to missing overrides public class DummyTool : BaseTool { public override string Name { get { return Mono.Unix.Catalog.GetString ("No tool selected."); } } public override string Icon { get { return Gtk.Stock.MissingImage; } } public override string StatusBarText { get { return Mono.Unix.Catalog.GetString ("No tool selected."); } } protected override void OnBuildToolBar (Toolbar tb) { tool_label = null; tool_image = null; tool_sep = null; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace fyiReporting.RdlDesign { /// <summary> /// Summary description for ReportCtl. /// </summary> internal class ListCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; bool fDataSet, fPBBefore, fPBAfter, fNoRows, fDataInstanceElementOutput, fDataInstanceName; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cbDataSet; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox chkPBBefore; private System.Windows.Forms.CheckBox chkPBAfter; private System.Windows.Forms.Button bGroups; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbNoRows; private System.Windows.Forms.TextBox tbDataInstanceName; private System.Windows.Forms.CheckBox chkXmlInstances; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal ListCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _ReportItems = ris; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { XmlNode riNode = _ReportItems[0]; tbNoRows.Text = _Draw.GetElementValue(riNode, "NoRows", ""); cbDataSet.Items.AddRange(_Draw.DataSetNames); cbDataSet.Text = _Draw.GetDataSetNameValue(riNode); if (_Draw.GetReportItemDataRegionContainer(riNode) != null) cbDataSet.Enabled = false; chkPBBefore.Checked = _Draw.GetElementValue(riNode, "PageBreakAtStart", "false").ToLower()=="true"? true:false; chkPBAfter.Checked = _Draw.GetElementValue(riNode, "PageBreakAtEnd", "false").ToLower()=="true"? true:false; this.chkXmlInstances.Checked = _Draw.GetElementValue(riNode, "DataInstanceElementOutput", "Output")=="Output"?true:false; this.tbDataInstanceName.Text = _Draw.GetElementValue(riNode, "DataInstanceName", "Item"); fNoRows = fDataSet = fPBBefore = fPBAfter = fDataInstanceElementOutput = fDataInstanceName = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label2 = new System.Windows.Forms.Label(); this.cbDataSet = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.chkPBAfter = new System.Windows.Forms.CheckBox(); this.chkPBBefore = new System.Windows.Forms.CheckBox(); this.bGroups = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.tbNoRows = new System.Windows.Forms.TextBox(); this.tbDataInstanceName = new System.Windows.Forms.TextBox(); this.chkXmlInstances = new System.Windows.Forms.CheckBox(); this.label3 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // label2 // this.label2.Location = new System.Drawing.Point(24, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 23); this.label2.TabIndex = 0; this.label2.Text = "DataSet Name"; // // cbDataSet // this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSet.Location = new System.Drawing.Point(120, 16); this.cbDataSet.Name = "cbDataSet"; this.cbDataSet.Size = new System.Drawing.Size(304, 21); this.cbDataSet.TabIndex = 1; this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.chkPBAfter); this.groupBox1.Controls.Add(this.chkPBBefore); this.groupBox1.Location = new System.Drawing.Point(24, 88); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(400, 48); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Page Breaks"; // // chkPBAfter // this.chkPBAfter.Location = new System.Drawing.Point(192, 16); this.chkPBAfter.Name = "chkPBAfter"; this.chkPBAfter.Size = new System.Drawing.Size(128, 24); this.chkPBAfter.TabIndex = 1; this.chkPBAfter.Text = "Insert after List"; this.chkPBAfter.CheckedChanged += new System.EventHandler(this.chkPBAfter_CheckedChanged); // // chkPBBefore // this.chkPBBefore.Location = new System.Drawing.Point(16, 16); this.chkPBBefore.Name = "chkPBBefore"; this.chkPBBefore.Size = new System.Drawing.Size(128, 24); this.chkPBBefore.TabIndex = 0; this.chkPBBefore.Text = "Insert before List"; this.chkPBBefore.CheckedChanged += new System.EventHandler(this.chkPBBefore_CheckedChanged); // // bGroups // this.bGroups.Location = new System.Drawing.Point(24, 240); this.bGroups.Name = "bGroups"; this.bGroups.Size = new System.Drawing.Size(120, 23); this.bGroups.TabIndex = 6; this.bGroups.Text = "Group Expressions..."; this.bGroups.Click += new System.EventHandler(this.bGroups_Click); // // label1 // this.label1.Location = new System.Drawing.Point(24, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(96, 23); this.label1.TabIndex = 2; this.label1.Text = "No rows message"; // // tbNoRows // this.tbNoRows.Location = new System.Drawing.Point(120, 48); this.tbNoRows.Name = "tbNoRows"; this.tbNoRows.Size = new System.Drawing.Size(304, 20); this.tbNoRows.TabIndex = 3; this.tbNoRows.Text = "textBox1"; this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged); // // tbDataInstanceName // this.tbDataInstanceName.Location = new System.Drawing.Point(146, 44); this.tbDataInstanceName.Name = "tbDataInstanceName"; this.tbDataInstanceName.Size = new System.Drawing.Size(238, 20); this.tbDataInstanceName.TabIndex = 2; this.tbDataInstanceName.Text = "textBox1"; this.tbDataInstanceName.TextChanged += new System.EventHandler(this.tbDataInstanceName_TextChanged); // // chkXmlInstances // this.chkXmlInstances.Location = new System.Drawing.Point(16, 16); this.chkXmlInstances.Name = "chkXmlInstances"; this.chkXmlInstances.Size = new System.Drawing.Size(160, 24); this.chkXmlInstances.TabIndex = 0; this.chkXmlInstances.Text = "Render list instances"; this.chkXmlInstances.CheckedChanged += new System.EventHandler(this.chkXmlInstances_CheckedChanged); // // label3 // this.label3.Location = new System.Drawing.Point(16, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(112, 16); this.label3.TabIndex = 1; this.label3.Text = "Data Instance Name"; // // groupBox2 // this.groupBox2.Controls.Add(this.tbDataInstanceName); this.groupBox2.Controls.Add(this.chkXmlInstances); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Location = new System.Drawing.Point(24, 152); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(400, 72); this.groupBox2.TabIndex = 5; this.groupBox2.TabStop = false; this.groupBox2.Text = "XML"; // // ListCtl // this.Controls.Add(this.groupBox2); this.Controls.Add(this.tbNoRows); this.Controls.Add(this.label1); this.Controls.Add(this.bGroups); this.Controls.Add(this.groupBox1); this.Controls.Add(this.cbDataSet); this.Controls.Add(this.label2); this.Name = "ListCtl"; this.Size = new System.Drawing.Size(472, 288); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); // No more changes fNoRows = fDataSet = fPBBefore = fPBAfter= fDataInstanceElementOutput = fDataInstanceName = false; } public void ApplyChanges(XmlNode node) { if (fNoRows) _Draw.SetElement(node, "NoRows", this.tbNoRows.Text); if (fDataSet) _Draw.SetElement(node, "DataSetName", this.cbDataSet.Text); if (fPBBefore) _Draw.SetElement(node, "PageBreakAtStart", this.chkPBBefore.Checked? "true":"false"); if (fPBAfter) _Draw.SetElement(node, "PageBreakAtEnd", this.chkPBAfter.Checked? "true":"false"); if (fDataInstanceElementOutput) _Draw.SetElement(node, "DataInstanceElementOutput", this.chkXmlInstances.Checked? "Output":"NoOutput"); if (fDataInstanceName) { if (this.tbDataInstanceName.Text.Length > 0) _Draw.SetElement(node, "DataInstanceName", this.tbDataInstanceName.Text); else _Draw.RemoveElement(node, "DataInstanceName"); } } private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e) { fDataSet = true; } private void chkPBBefore_CheckedChanged(object sender, System.EventArgs e) { fPBBefore = true; } private void chkPBAfter_CheckedChanged(object sender, System.EventArgs e) { fPBAfter = true; } private void tbNoRows_TextChanged(object sender, System.EventArgs e) { fNoRows = true; } private void bGroups_Click(object sender, System.EventArgs e) { PropertyDialog pd = new PropertyDialog(_Draw, _ReportItems, PropertyTypeEnum.Grouping); try { DialogResult dr = pd.ShowDialog(); if (pd.Changed || dr == DialogResult.OK) { // _DrawPanel.Invalidate(); TODO need to force change somehow????? } } finally { pd.Dispose(); } } private void chkXmlInstances_CheckedChanged(object sender, System.EventArgs e) { fDataInstanceElementOutput = true; } private void tbDataInstanceName_TextChanged(object sender, System.EventArgs e) { fDataInstanceName = true; } } }
//Matt Schoen //5-29-2013 // // This software is the copyrighted material of its author, Matt Schoen, and his company Defective Studios. // It is available for sale on the Unity Asset store and is subject to their restrictions and limitations, as well as // the following: You shall not reproduce or re-distribute this software without the express written (e-mail is fine) // permission of the author. If permission is granted, the code (this file and related files) must bear this license // in its entirety. Anyone who purchases the script is welcome to modify and re-use the code at their personal risk // and under the condition that it not be included in any distribution builds. The software is provided as-is without // warranty and the author bears no responsibility for damages or losses caused by the software. // This Agreement becomes effective from the day you have installed, copied, accessed, downloaded and/or otherwise used // the software. #if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Reflection; using FoldoutDraw = ObjectMerge.EmptyVoid; namespace UniMerge { public static class Util { public static float TAB_SIZE = 15; public static void Foldout(ref bool open, string title, FoldoutDraw draw) { Foldout(ref open, new GUIContent(title), draw, null); } public static void Foldout(ref bool open, GUIContent content, FoldoutDraw draw) { Foldout(ref open, content, draw, null); } public static void Foldout(ref bool open, string title, FoldoutDraw draw, FoldoutDraw moreLabel) { Foldout(ref open, new GUIContent(title), draw, moreLabel); } public static void Foldout(ref bool open, GUIContent content, FoldoutDraw draw, FoldoutDraw moreLabel) { GUILayout.BeginHorizontal(); open = EditorGUILayout.Foldout(open, content); if(moreLabel != null) moreLabel.Invoke(); GUILayout.EndHorizontal(); if(open) { Indent(draw); } } public static void Indent(FoldoutDraw draw) { Indent(TAB_SIZE, draw); } public static void Indent(float width, FoldoutDraw draw) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(GUILayout.Width(width)); GUILayout.Label(""); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); draw.Invoke(); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } public static void Center(FoldoutDraw element) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); element(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } //Not used but a nice little gem :) public static void ClearLog() { Assembly assembly = Assembly.GetAssembly(typeof(SceneView)); System.Type type = assembly.GetType("UnityEditorInternal.LogEntries"); MethodInfo method = type.GetMethod("Clear"); method.Invoke(new object(), null); } public static void PingButton(string content, Object obj) { if(GUILayout.Button(content)) EditorGUIUtility.PingObject(obj); } //Looks like Unity already has one of these... doesn't work the way I want though public static IEnumerable<bool> PropEqual(SerializedProperty mine, SerializedProperty theirs, GameObject mineParent, GameObject theirsParent) { if(ObjectMerge.refreshWatch.Elapsed.TotalSeconds > ObjectMerge.maxFrameTime) { ObjectMerge.refreshWatch.Reset(); yield return false; ObjectMerge.refreshWatch.Start(); } if(mine != null && theirs != null) { if(mine.propertyType == theirs.propertyType) { switch(mine.propertyType) { case SerializedPropertyType.AnimationCurve: if(mine.animationCurveValue.keys.Length == theirs.animationCurveValue.keys.Length) { for(int i = 0; i < mine.animationCurveValue.keys.Length; i++) { if(mine.animationCurveValue.keys[i].inTangent != theirs.animationCurveValue.keys[i].inTangent) { yield return false; yield break; } if(mine.animationCurveValue.keys[i].outTangent != theirs.animationCurveValue.keys[i].outTangent){ yield return false; yield break; } if(mine.animationCurveValue.keys[i].time != theirs.animationCurveValue.keys[i].time){ yield return false; yield break; } if(mine.animationCurveValue.keys[i].value != theirs.animationCurveValue.keys[i].value){ yield return false; yield break; } } } else { yield return false; yield break; } yield return true; yield break; case SerializedPropertyType.ArraySize: //Haven't handled this one... not sure it will come up //Debug.LogWarning("Got ArraySize type"); break; case SerializedPropertyType.Boolean: yield return mine.boolValue == theirs.boolValue; yield break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Bounds: yield return mine.boundsValue == theirs.boundsValue; yield break; #endif case SerializedPropertyType.Character: //TODO: Character comparison Debug.LogWarning("Got Character type. Need to add comparison function"); break; case SerializedPropertyType.Color: yield return mine.colorValue == theirs.colorValue;yield break; case SerializedPropertyType.Enum: yield return mine.enumValueIndex == theirs.enumValueIndex;yield break; case SerializedPropertyType.Float: yield return mine.floatValue == theirs.floatValue;yield break; case SerializedPropertyType.Generic: //Override equivalence for some types that will never be equal switch(mine.type) { case "NetworkViewID": yield return true; yield break; case "GUIStyle": //Having trouble with this one yield return true; yield break; } #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) bool equal; if(mine.isArray) { if(mine.arraySize == theirs.arraySize) { for(int i = 0; i < mine.arraySize; i++) { equal = false; foreach(bool e in PropEqual(mine.GetArrayElementAtIndex(i), theirs.GetArrayElementAtIndex(i), mineParent, theirsParent)) { yield return e; equal = e; } if(!equal) yield break; } yield return true; yield break; } yield return false; yield break; } equal = false; foreach(var e in CheckChildren(mine, theirs, mineParent, theirsParent)) equal = e; if (!equal) yield break; #endif break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Gradient: Debug.LogWarning("Got Gradient type"); break; #endif case SerializedPropertyType.Integer: yield return mine.intValue == theirs.intValue; yield break; case SerializedPropertyType.LayerMask: yield return mine.intValue == theirs.intValue; yield break; case SerializedPropertyType.ObjectReference: if(mine.objectReferenceValue && theirs.objectReferenceValue) { System.Type t = mine.objectReferenceValue.GetType(); //If the property is a gameObject or component, compare equivalence by comparing names, and whether they're both children of the same parent (from different sides) if(t == typeof(GameObject)) { if(theirs.objectReferenceValue.GetType() != t) { Debug.LogWarning("EH? two properties of different types?"); yield return false; yield break; } if(ChildOfParent((GameObject)mine.objectReferenceValue, mineParent) && ChildOfParent((GameObject)theirs.objectReferenceValue, theirsParent)) { yield return mine.objectReferenceValue.name == theirs.objectReferenceValue.name; yield break; } } if(t.IsSubclassOf(typeof(Component))) { if(theirs.objectReferenceValue.GetType() != t) { Debug.LogWarning("EH? two properties of different types?"); yield return false; yield break; } if(ChildOfParent(((Component)mine.objectReferenceValue).gameObject, mineParent) && ChildOfParent(((Component)theirs.objectReferenceValue).gameObject, theirsParent)) { yield return mine.objectReferenceValue.name == theirs.objectReferenceValue.name; yield break; } } } yield return mine.objectReferenceValue == theirs.objectReferenceValue; yield break; case SerializedPropertyType.Rect: yield return mine.rectValue == theirs.rectValue; yield break; case SerializedPropertyType.String: yield return mine.stringValue == theirs.stringValue; yield break; case SerializedPropertyType.Vector2: yield return mine.vector2Value == theirs.vector2Value; yield break; case SerializedPropertyType.Vector3: yield return mine.vector3Value == theirs.vector3Value; yield break; #if UNITY_4_5 || UNITY_4_5_0 case SerializedPropertyType.Quaternion: yield return mine.quaternionValue.Equals(theirs.quaternionValue); yield break; #elif !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) // case (SerializedPropertyType)16: // yield return mine.quaternionValue.Equals(theirs.quaternionValue); // yield break; #endif default: Debug.LogWarning("Unknown SeralizedPropertyType encountered: " + mine.propertyType); break; } } else Debug.LogWarning("Not same type?"); } yield return true; } private static IEnumerable<bool> CheckChildren(SerializedProperty mine, SerializedProperty theirs, GameObject mineParent, GameObject theirsParent) { bool enter = true; if(mine == null && theirs == null) yield break; if(mine == null || theirs == null) { yield return false; yield break; } SerializedProperty mTmp = mine.Copy(); SerializedProperty tTmp = theirs.Copy(); //I'm really not sure what's going on here. This seems to work differently for different types of properties while(mTmp.Next(enter)) { tTmp.Next(enter); enter = false; //Maybe we want this? if(mTmp.depth != mine.depth) //Once we're back in the same depth, we've gone too far break; bool equal = false; foreach (bool e in PropEqual(mTmp, tTmp, mineParent, theirsParent)) { yield return e; equal = e; } if(!equal) yield break; } yield return true; } //U3: Had to define out some types of components. Default case will warn me about this //Looks like this is already implemented... public static void SetProperty(SerializedProperty from, SerializedProperty to) { switch(from.propertyType) { case SerializedPropertyType.AnimationCurve: to.animationCurveValue = from.animationCurveValue; break; case SerializedPropertyType.ArraySize: Debug.LogWarning("Got ArraySize type"); break; case SerializedPropertyType.Boolean: to.boolValue = from.boolValue; break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Bounds: to.boundsValue = from.boundsValue; break; #endif case SerializedPropertyType.Character: Debug.LogWarning("Got Character type"); break; case SerializedPropertyType.Color: to.colorValue = from.colorValue; break; case SerializedPropertyType.Enum: to.enumValueIndex = from.enumValueIndex; break; case SerializedPropertyType.Float: to.floatValue = from.floatValue; break; case SerializedPropertyType.Generic: #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 Debug.LogWarning("How to copy generic properties in Unity 3?"); #else to.serializedObject.CopyFromSerializedProperty(from); to.serializedObject.ApplyModifiedProperties(); #endif break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Gradient: Debug.LogWarning("Got Gradient type"); break; #endif case SerializedPropertyType.Integer: to.intValue = from.intValue; break; case SerializedPropertyType.LayerMask: to.intValue = from.intValue; break; case SerializedPropertyType.ObjectReference: Debug.Log("blah"); to.objectReferenceValue = from.objectReferenceValue; break; case SerializedPropertyType.Rect: to.rectValue = from.rectValue; break; case SerializedPropertyType.String: to.stringValue = from.stringValue; break; case SerializedPropertyType.Vector2: to.vector2Value = from.vector2Value; break; case SerializedPropertyType.Vector3: to.vector3Value = from.vector3Value; break; #if UNITY_4_5 || UNITY_4_5_0 case SerializedPropertyType.Quaternion: to.quaternionValue = from.quaternionValue; break; #elif !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) // case (SerializedPropertyType)16: // to.quaternionValue = from.quaternionValue; // break; #endif default: Debug.LogWarning("Unknown SeralizedPropertyType encountered: " + to.propertyType); break; } } public static bool ChildOfParent(GameObject obj, GameObject parent) { while(true) { if(obj == parent) return true; if(obj.transform.parent == null) break; obj = obj.transform.parent.gameObject; } return false; } public static void GameObjectToList(GameObject obj, List<GameObject> list) { list.Add(obj); foreach(Transform t in obj.transform) GameObjectToList(t.gameObject, list); } /// <summary> /// Determine whether the object is part of a prefab, and if it is the root of the prefab tree /// </summary> /// <param name="g"></param> /// <returns></returns> public static bool IsPrefabParent(GameObject g) { #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 return EditorUtility.FindPrefabRoot(g) == g; #else return PrefabUtility.FindPrefabRoot(g) == g; #endif } } } #endif
using System; using System.Data.SqlClient; using System.Text; //using System.Web.Mail; using System.Web.UI; using Appleseed.Framework; using Appleseed.Framework.Content.Security; using Appleseed.Framework.DataTypes; using Appleseed.Framework.Helpers; using Appleseed.Framework.Security; using Appleseed.Framework.Settings; using Appleseed.Framework.Users.Data; using Appleseed.Framework.Web.UI.WebControls; using Appleseed.Framework.Providers.AppleseedMembershipProvider; namespace Appleseed.Content.Web.Modules { using System.Web.UI.WebControls; using Localize = Appleseed.Framework.Web.UI.WebControls.Localize; using System.Net.Mail; /// <summary> /// The SignIn User Control enables clients to authenticate themselves using /// the ASP.NET Forms based authentication system. /// /// When a client enters their username/password within the appropriate /// textboxes and clicks the "Login" button, the LoginBtn_Click event /// handler executes on the server and attempts to validate their /// credentials against a SQL database. /// /// If the password check succeeds, then the LoginBtn_Click event handler /// sets the customers username in an encrypted cookieID and redirects /// back to the portal home page. /// /// If the password check fails, then an appropriate error message /// is displayed. /// This cool version is placed orizontally and allows a descriptive text on the right /// </summary> public partial class SigninCool : PortalModuleControl { #region Controls /// <summary> /// /// </summary> protected Localize LoginTitle; #endregion /// <summary> /// Handles the Click event of the LoginBtn control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LoginBtn_Click(Object sender, EventArgs e) { if (PortalSecurity.SignOn(email.Text, password.Text, RememberCheckBox.Checked, Request.QueryString["ReturnUrl"]) == null) { Message.Text = "Login failed"; Message.TextKey = "LOGIN_FAILED"; //Get Failed Password Attampt Counter //e.g. ((AppleseedUser)((AppleseedMembershipProvider)System.Web.Security.Membership.Provider).GetUser(PortalSettings.PortalAlias, email.Text, true)).FailedPasswordAttemptCount } } /// <summary> /// Handles the Click event of the RegisterBtn control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void RegisterBtn_Click(object sender, EventArgs e) { Response.Redirect(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Register/Register.aspx")); } private void SendPasswordBtnClickLink(object sender, EventArgs e) { var url = HttpUrlBuilder.BuildUrl("~/Password/ForgotPassword"); if (!string.IsNullOrEmpty(this.email.Text)) { url += "?email=" + this.email.Text; } this.Response.Redirect(url); } /// <summary> /// Handles the Click event of the SendPasswordBtn control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void SendPasswordBtn_Click( object sender, EventArgs e ) { if ( email.Text == string.Empty ) { Message.Text = "Please enter you email address"; Message.TextKey = "SIGNIN_ENTER_EMAIL_ADDR"; return; } // generate random password string randomPassword = RandomPassword.Generate( 8, 10 ); CryptoHelper crypthelp = new CryptoHelper(); UsersDB usersDB = new UsersDB(); //Obtain single row of User information AppleseedUser user = usersDB.GetSingleUser( email.Text, this.PortalSettings.PortalAlias ); if ( user != null ) { string Pswrd; string AppName = this.PortalSettings.PortalName; bool encrypted = Config.EncryptPassword; string Name = user.Email; if ( encrypted ) { Pswrd = randomPassword; crypthelp.ResetPassword( Name, randomPassword ); } else { Pswrd = user.GetPassword(); } crypthelp.ResetPassword( Name, randomPassword ); string LoginUrl = Path.ApplicationFullPath + "DesktopModules/Admin/Logon.aspx?Usr=" + Name + "&Pwd=" + Pswrd + "&Alias=" + this.PortalSettings.PortalAlias; // MailMessage mail = new MailMessage(); // Geert.Audenaert@Syntegra.Com // Date 19 March 2003 // We have to use a correct sender address, // because most SMTP servers reject it otherwise //jes1111 - mail.From = ConfigurationSettings.AppSettings["EmailFrom"].ToString(); //mail.From = Config.EmailFrom; //mail.To = email.Text; //mail.Subject = AppName + " - " + General.GetString( "SIGNIN_SEND_PWD", "Send me password", this ); StringBuilder sb = new StringBuilder(); sb.Append( Name ); sb.Append( "," ); sb.Append( "\r\n\r\n" ); sb.Append( General.GetString( "SIGNIN_PWD_REQUESTED", "This is the password you requested", this ) ); sb.Append( " " ); sb.Append( Pswrd ); sb.Append( "\r\n\r\n" ); sb.Append( General.GetString( "SIGNIN_THANK_YOU", "Thanks for your visit.", this ) ); sb.Append( " " ); sb.Append( AppName ); sb.Append( "\r\n\r\n" ); sb.Append( General.GetString( "SIGNIN_YOU_CAN_LOGIN_FROM", "You can login from", this ) ); sb.Append( ":" ); sb.Append( "\r\n" ); sb.Append( Path.ApplicationFullPath ); sb.Append( "\r\n\r\n" ); sb.Append( General.GetString( "SIGNIN_USE_DIRECT_URL", "Or using direct url", this ) ); sb.Append( "\r\n" ); sb.Append( LoginUrl ); sb.Append( "\r\n\r\n" ); sb.Append( General.GetString( "SIGNIN_URL_WARNING", "NOTE: The address above may not show up on your screen as one line. This would prevent you from using the link to access the web page. If this happens, just use the 'cut' and 'paste' options to join the pieces of the URL.", this ) ); //mail.Body = sb.ToString(); //mail.BodyFormat = MailFormat.Text; //SmtpMail.SmtpServer = Config.SmtpServer; //SmtpMail.Send( mail ); string subject = AppName + " - " + General.GetString("SIGNIN_SEND_PWD", "Send me password", this); MailMessage newmail = new MailMessage(Config.EmailFrom.ToString(),email.Text,subject,sb.ToString()); SmtpClient client = new SmtpClient(Config.SmtpServer); client.Send(newmail); Message.Text = General.GetString( "SIGNIN_PWD_WAS_SENT", "Your password was sent to the addess you provided", this ); Message.TextKey = "SIGNIN_PWD_WAS_SENT"; } else { Message.Text = General.GetString( "SIGNIN_PWD_MISSING_IN_DB", "The email you specified does not exists on our database", this ); Message.TextKey = "SIGNIN_PWD_MISSING_IN_DB"; } } /// <summary> /// Overrides ModuleSetting to render this module type un-cacheable /// </summary> /// <value></value> public override bool Cacheable { get { return false; } } /// <summary> /// Initializes a new instance of the <see cref="SigninCool"/> class. /// </summary> public SigninCool() { var coolText = new SettingItem<string, TextBox> { Order = 10 }; this.BaseSettings.Add("CoolText", coolText); var hideAutomatically = new SettingItem<bool, CheckBox> { Value = true, EnglishName = "Hide automatically", Order = 20 }; this.BaseSettings.Add("SIGNIN_AUTOMATICALLYHIDE", hideAutomatically); //1.2.8.1743b - 09/10/2003 //New setting on Signin fo disable IE autocomplete by Mike Stone //If you uncheck this setting IE will not remember user name and passwords. //Note that users who have memorized passwords will not be effected until their computer //is reset, only new users and/or computers will honor this. var autoComplete = new SettingItem<bool, CheckBox> { Value = true, EnglishName = "Allow IE Autocomplete", Description = "If Checked IE Will try to remember logins", Order = 30 }; this.BaseSettings.Add("SIGNIN_ALLOW_AUTOCOMPLETE", autoComplete); var rememberLogin = new SettingItem<bool, CheckBox> { Value = true, EnglishName = "Allow Remember Login", Description = "If Checked allows to remember logins", Order = 40 }; this.BaseSettings.Add("SIGNIN_ALLOW_REMEMBER_LOGIN", rememberLogin); var sendPassword = new SettingItem<bool, CheckBox> { Value = true, EnglishName = "Allow Send Password", Description = "If Checked allows user to ask to get password by email if he forgotten", Order = 50 }; this.BaseSettings.Add("SIGNIN_ALLOW_SEND_PASSWORD", sendPassword); } #region General Implementation /// <summary> /// GUID of module (mandatory) /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid("{99F3511F-737C-4b57-87C0-9A010AF40A9C}"); } } #endregion #region Web Form Designer generated code /// <summary> /// On init /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { this.LoginBtn.Click += new EventHandler(this.LoginBtn_Click); this.SendPasswordBtn.Click += new EventHandler(this.SendPasswordBtnClickLink); this.RegisterBtn.Click += new EventHandler(this.RegisterBtn_Click); this.Load += new EventHandler(this.Signin_Load); base.OnInit(e); } #endregion /// <summary> /// Handles the Load event of the Signin control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Signin_Load(object sender, EventArgs e) { bool hide = true; bool autocomplete = false; if (this.PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_ALLOW_NEW_REGISTRATION") && !(string.IsNullOrEmpty(this.PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_ALLOW_NEW_REGISTRATION").ToString()))) if (!bool.Parse(this.PortalSettings.CustomSettings["SITESETTINGS_ALLOW_NEW_REGISTRATION"].ToString())) RegisterBtn.Visible = false; if (this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_AUTOMATICALLYHIDE") && !(string.IsNullOrEmpty(this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_AUTOMATICALLYHIDE").ToString()))) hide = bool.Parse(Settings["SIGNIN_AUTOMATICALLYHIDE"].ToString()); if (this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_ALLOW_AUTOCOMPLETE") && !(string.IsNullOrEmpty(this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_ALLOW_AUTOCOMPLETE").ToString()))) autocomplete = bool.Parse(Settings["SIGNIN_ALLOW_AUTOCOMPLETE"].ToString()); if (this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_ALLOW_REMEMBER_LOGIN") && !(string.IsNullOrEmpty(this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_ALLOW_REMEMBER_LOGIN").ToString()))) RememberCheckBox.Visible = bool.Parse(Settings["SIGNIN_ALLOW_REMEMBER_LOGIN"].ToString()); if (this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_ALLOW_SEND_PASSWORD") && !(string.IsNullOrEmpty(this.PortalSettings.CustomSettings.ContainsKey("SIGNIN_ALLOW_SEND_PASSWORD").ToString()))) SendPasswordBtn.Visible = bool.Parse(Settings["SIGNIN_ALLOW_SEND_PASSWORD"].ToString()); if (hide && Request.IsAuthenticated) { this.Visible = false; } else if (!autocomplete) { //New setting on Signin fo disable IE autocomplete by Mike Stone password.Attributes.Add("autocomplete", "off"); } // Update cool text if(Settings.ContainsKey("CoolText")) CoolTextPlaceholder.Controls.Add(new LiteralControl(Settings["CoolText"].ToString())); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; #if logging #endif namespace Encog.MathUtil.Matrices { /// <summary> /// MatrixMath: This class can perform many different mathematical /// operations on matrixes. /// </summary> public class MatrixMath { /// <summary> /// Private constructor. All methods are static. /// </summary> private MatrixMath() { } /// <summary> /// Add two matrixes together, producing a third. /// </summary> /// <param name="a">The first matrix to add.</param> /// <param name="b">The second matrix to add.</param> /// <returns>The two matrixes added together.</returns> public static Matrix Add(Matrix a, Matrix b) { if (a.Rows != b.Rows) { throw new MatrixError( "To add the matrixes they must have the same number of rows and columns. Matrix a has " + a.Rows + " rows and matrix b has " + b.Rows + " rows."); } if (a.Cols != b.Cols) { throw new MatrixError( "To add the matrixes they must have the same number of rows and columns. Matrix a has " + a.Cols + " cols and matrix b has " + b.Cols + " cols."); } var result = new double[a.Rows][]; double[][] aData = a.Data; double[][] bData = b.Data; for (int resultRow = 0; resultRow < a.Rows; resultRow++) { result[resultRow] = new double[a.Cols]; for (int resultCol = 0; resultCol < a.Cols; resultCol++) { result[resultRow][resultCol] = aData[resultRow][resultCol] + bData[resultRow][resultCol]; } } return new Matrix(result); } /// <summary> /// Copy the source matrix to the target matrix. Both matrixes must have the same dimensions. /// </summary> /// <param name="source">The source matrix.</param> /// <param name="target">The target matrix.</param> public static void Copy(Matrix source, Matrix target) { double[][] sourceData = source.Data; double[][] targetData = target.Data; for (int row = 0; row < source.Rows; row++) { for (int col = 0; col < source.Cols; col++) { targetData[row][col] = sourceData[row][col]; } } } /// <summary> /// Delete a single column from a matrix. A new matrix, with the delete is returned. /// </summary> /// <param name="matrix">The matrix to delete from.</param> /// <param name="deleted">The column to delete.</param> /// <returns>The matrix, with the delete.</returns> public static Matrix DeleteCol(Matrix matrix, int deleted) { if (deleted >= matrix.Cols) { throw new MatrixError("Can't delete column " + deleted + " from matrix, it only has " + matrix.Cols + " columns."); } var newMatrix = new double[matrix.Rows][]; double[][] matrixData = matrix.Data; for (int row = 0; row < matrix.Rows; row++) { int targetCol = 0; newMatrix[row] = new double[matrix.Cols - 1]; for (int col = 0; col < matrix.Cols; col++) { if (col != deleted) { newMatrix[row][targetCol] = matrixData[row][col]; targetCol++; } } } return new Matrix(newMatrix); } /// <summary> /// Delete a row from a matrix. A new matrix, with the row deleted, is returned. /// </summary> /// <param name="matrix">The matrix to delete from.</param> /// <param name="deleted">The row to delete.</param> /// <returns>The matrix, with the row deleted.</returns> public static Matrix DeleteRow(Matrix matrix, int deleted) { if (deleted >= matrix.Rows) { throw new MatrixError("Can't delete row " + deleted + " from matrix, it only has " + matrix.Rows + " rows."); } var newMatrix = new double[matrix.Rows - 1][]; double[][] matrixData = matrix.Data; int targetRow = 0; for (int row = 0; row < matrix.Rows; row++) { if (row != deleted) { newMatrix[targetRow] = new double[matrix.Cols]; for (int col = 0; col < matrix.Cols; col++) { newMatrix[targetRow][col] = matrixData[row][col]; } targetRow++; } } return new Matrix(newMatrix); } /// <summary> /// Divide every cell in the matrix by the specified number. /// </summary> /// <param name="a">The matrix to divide.</param> /// <param name="b">The number to divide by.</param> /// <returns>The divided matrix.</returns> public static Matrix Divide(Matrix a, double b) { var result = new double[a.Rows][]; double[][] aData = a.Data; for (int row = 0; row < a.Rows; row++) { result[row] = new double[a.Cols]; for (int col = 0; col < a.Cols; col++) { result[row][col] = aData[row][col]/b; } } return new Matrix(result); } /// <summary> /// Compute the dot product for two matrixes. Note: both matrixes must be vectors. /// </summary> /// <param name="a">The first matrix, must be a vector.</param> /// <param name="b">The second matrix, must be a vector.</param> /// <returns>The dot product of the two matrixes.</returns> public static double DotProduct(Matrix a, Matrix b) { if (!a.IsVector() || !b.IsVector()) { throw new MatrixError( "To take the dot product, both matrixes must be vectors."); } Double[] aArray = a.ToPackedArray(); Double[] bArray = b.ToPackedArray(); if (aArray.Length != bArray.Length) { throw new MatrixError( "To take the dot product, both matrixes must be of the same length."); } double result = 0; int length = aArray.Length; for (int i = 0; i < length; i++) { result += aArray[i]*bArray[i]; } return result; } /// <summary> /// Create an identiry matrix, of the specified size. An identity matrix is always square. /// </summary> /// <param name="size"></param> /// <returns></returns> public static Matrix Identity(int size) { if (size < 1) { throw new MatrixError("Identity matrix must be at least of size 1."); } var result = new Matrix(size, size); double[][] resultData = result.Data; for (int i = 0; i < size; i++) { resultData[i][i] = 1; } return result; } /// <summary> /// Multiply every cell in the matrix by the specified value. /// </summary> /// <param name="a">Multiply every cell in a matrix by the specified value.</param> /// <param name="b">The value to multiply by.</param> /// <returns>The new multiplied matrix.</returns> public static Matrix Multiply(Matrix a, double b) { var result = new double[a.Rows][]; double[][] aData = a.Data; for (int row = 0; row < a.Rows; row++) { result[row] = new double[a.Cols]; for (int col = 0; col < a.Cols; col++) { result[row][col] = aData[row][col]*b; } } return new Matrix(result); } /// <summary> /// Multiply two matrixes. /// </summary> /// <param name="a">The first matrix.</param> /// <param name="b">The second matrix.</param> /// <returns>The resulting matrix.</returns> public static Matrix Multiply(Matrix a, Matrix b) { if (a.Cols != b.Rows) { throw new MatrixError( "To use ordinary matrix multiplication the number of columns on the first matrix must mat the number of rows on the second."); } var result = new double[a.Rows][]; double[][] aData = a.Data; double[][] bData = b.Data; for (int resultRow = 0; resultRow < a.Rows; resultRow++) { result[resultRow] = new double[b.Cols]; for (int resultCol = 0; resultCol < b.Cols; resultCol++) { double value = 0; for (int i = 0; i < a.Cols; i++) { value += aData[resultRow][i]*bData[i][resultCol]; } result[resultRow][resultCol] = value; } } return new Matrix(result); } /// <summary> /// Subtract one matrix from another. The two matrixes must have the same number of rows and columns. /// </summary> /// <param name="a">The first matrix.</param> /// <param name="b">The second matrix.</param> /// <returns>The subtracted matrix.</returns> public static Matrix Subtract(Matrix a, Matrix b) { if (a.Rows != b.Rows) { throw new MatrixError( "To subtract the matrixes they must have the same number of rows and columns. Matrix a has " + a.Rows + " rows and matrix b has " + b.Rows + " rows."); } if (a.Cols != b.Cols) { throw new MatrixError( "To subtract the matrixes they must have the same number of rows and columns. Matrix a has " + a.Cols + " cols and matrix b has " + b.Cols + " cols."); } var result = new double[a.Rows][]; double[][] aData = a.Data; double[][] bData = b.Data; for (int resultRow = 0; resultRow < a.Rows; resultRow++) { result[resultRow] = new double[a.Cols]; for (int resultCol = 0; resultCol < a.Cols; resultCol++) { result[resultRow][resultCol] = aData[resultRow][resultCol] - bData[resultRow][resultCol]; } } return new Matrix(result); } /// <summary> /// Transpose the specified matrix. /// </summary> /// <param name="input">The matrix to transpose.</param> /// <returns>The transposed matrix.</returns> public static Matrix Transpose(Matrix input) { var inverseMatrix = new double[input.Cols][]; double[][] inputData = input.Data; for (int r = 0; r < input.Cols; r++) { inverseMatrix[r] = new double[input.Rows]; for (int c = 0; c < input.Rows; c++) { inverseMatrix[r][c] = inputData[c][r]; } } return new Matrix(inverseMatrix); } /// <summary> /// Calculate the vector length of the matrix. /// </summary> /// <param name="input">The vector to calculate for.</param> /// <returns>The vector length.</returns> public static double VectorLength(Matrix input) { if (!input.IsVector()) { throw new MatrixError( "Can only take the vector length of a vector."); } Double[] v = input.ToPackedArray(); double rtn = 0.0; for (int i = 0; i < v.Length; i++) { rtn += Math.Pow(v[i], 2); } return Math.Sqrt(rtn); } /// <summary> /// Multiply the matrix by a vector. /// </summary> /// <param name="a">The matrix.</param> /// <param name="d">The vector.</param> /// <returns>The resulting vector.</returns> public static double[] Multiply(Matrix a, double[] d) { double[] p = new double[a.Rows]; double[][] aData = a.Data; for (int r = 0; r < a.Rows; r++) for (int i = 0; i < a.Cols; i++) p[r] += aData[r][i] * d[i]; return p; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia.Controls; using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.AstNodes; using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers; using Avalonia.Media; using XamlX.Ast; using XamlX.Transform; using XamlX.TypeSystem; namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions { class AvaloniaXamlIlLanguageParseIntrinsics { public static bool TryConvert(AstTransformationContext context, IXamlAstValueNode node, string text, IXamlType type, AvaloniaXamlIlWellKnownTypes types, out IXamlAstValueNode result) { if (type.FullName == "System.TimeSpan") { var tsText = text.Trim(); if (!TimeSpan.TryParse(tsText, CultureInfo.InvariantCulture, out var timeSpan)) { // // shorthand seconds format (ie. "0.25") if (!tsText.Contains(":") && double.TryParse(tsText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var seconds)) timeSpan = TimeSpan.FromSeconds(seconds); else throw new XamlX.XamlLoadException($"Unable to parse {text} as a time span", node); } result = new XamlStaticOrTargetedReturnMethodCallNode(node, type.FindMethod("FromTicks", type, false, types.Long), new[] { new XamlConstantNode(node, types.Long, timeSpan.Ticks) }); return true; } if (type.Equals(types.FontFamily)) { result = new AvaloniaXamlIlFontFamilyAstNode(types, text, node); return true; } if (type.Equals(types.Thickness)) { try { var thickness = Thickness.Parse(text); result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Thickness, types.ThicknessFullConstructor, new[] { thickness.Left, thickness.Top, thickness.Right, thickness.Bottom }); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a thickness", node); } } if (type.Equals(types.Point)) { try { var point = Point.Parse(text); result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Point, types.PointFullConstructor, new[] { point.X, point.Y }); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a point", node); } } if (type.Equals(types.Vector)) { try { var vector = Vector.Parse(text); result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Vector, types.VectorFullConstructor, new[] { vector.X, vector.Y }); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a vector", node); } } if (type.Equals(types.Size)) { try { var size = Size.Parse(text); result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Size, types.SizeFullConstructor, new[] { size.Width, size.Height }); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a size", node); } } if (type.Equals(types.Matrix)) { try { var matrix = Matrix.Parse(text); result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.Matrix, types.MatrixFullConstructor, new[] { matrix.M11, matrix.M12, matrix.M21, matrix.M22, matrix.M31, matrix.M32 }); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a matrix", node); } } if (type.Equals(types.CornerRadius)) { try { var cornerRadius = CornerRadius.Parse(text); result = new AvaloniaXamlIlVectorLikeConstantAstNode(node, types, types.CornerRadius, types.CornerRadiusFullConstructor, new[] { cornerRadius.TopLeft, cornerRadius.TopRight, cornerRadius.BottomRight, cornerRadius.BottomLeft }); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a corner radius", node); } } if (type.Equals(types.Color)) { if (!Color.TryParse(text, out Color color)) { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a color", node); } result = new XamlStaticOrTargetedReturnMethodCallNode(node, type.GetMethod( new FindMethodMethodSignature("FromUInt32", type, types.UInt) { IsStatic = true }), new[] { new XamlConstantNode(node, types.UInt, color.ToUint32()) }); return true; } if (type.Equals(types.GridLength)) { try { var gridLength = GridLength.Parse(text); result = new AvaloniaXamlIlGridLengthAstNode(node, types, gridLength); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a grid length", node); } } if (type.Equals(types.Cursor)) { if (TypeSystemHelpers.TryGetEnumValueNode(types.StandardCursorType, text, node, out var enumConstantNode)) { var cursorTypeRef = new XamlAstClrTypeReference(node, types.Cursor, false); result = new XamlAstNewClrObjectNode(node, cursorTypeRef, types.CursorTypeConstructor, new List<IXamlAstValueNode> { enumConstantNode }); return true; } } if (type.Equals(types.ColumnDefinitions)) { return ConvertDefinitionList(node, text, types, types.ColumnDefinitions, types.ColumnDefinition, "column definitions", out result); } if (type.Equals(types.RowDefinitions)) { return ConvertDefinitionList(node, text, types, types.RowDefinitions, types.RowDefinition, "row definitions", out result); } if (type.Equals(types.Classes)) { var classes = text.Split(' '); var classNodes = classes.Select(c => new XamlAstTextNode(node, c, type: types.XamlIlTypes.String)).ToArray(); result = new AvaloniaXamlIlAvaloniaListConstantAstNode(node, types, types.Classes, types.XamlIlTypes.String, classNodes); return true; } if (types.IBrush.IsAssignableFrom(type)) { if (Color.TryParse(text, out Color color)) { var brushTypeRef = new XamlAstClrTypeReference(node, types.ImmutableSolidColorBrush, false); result = new XamlAstNewClrObjectNode(node, brushTypeRef, types.ImmutableSolidColorBrushConstructorColor, new List<IXamlAstValueNode> { new XamlConstantNode(node, types.UInt, color.ToUint32()) }); return true; } } result = null; return false; } private static bool ConvertDefinitionList( IXamlAstValueNode node, string text, AvaloniaXamlIlWellKnownTypes types, IXamlType listType, IXamlType elementType, string errorDisplayName, out IXamlAstValueNode result) { try { var lengths = GridLength.ParseLengths(text); var definitionTypeRef = new XamlAstClrTypeReference(node, elementType, false); var definitionConstructorGridLength = elementType.GetConstructor(new List<IXamlType> {types.GridLength}); IXamlAstValueNode CreateDefinitionNode(GridLength length) { var lengthNode = new AvaloniaXamlIlGridLengthAstNode(node, types, length); return new XamlAstNewClrObjectNode(node, definitionTypeRef, definitionConstructorGridLength, new List<IXamlAstValueNode> {lengthNode}); } var definitionNodes = new List<IXamlAstValueNode>(lengths.Select(CreateDefinitionNode)); result = new AvaloniaXamlIlAvaloniaListConstantAstNode(node, types, listType, elementType, definitionNodes); return true; } catch { throw new XamlX.XamlLoadException($"Unable to parse \"{text}\" as a {errorDisplayName}", node); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebApiLongRunningTask.Sample.Areas.HelpPage.ModelDescriptions; using WebApiLongRunningTask.Sample.Areas.HelpPage.Models; namespace WebApiLongRunningTask.Sample.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* ==================================================================== Licensed to the 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 NPOI.Util; using System.Text; using System; namespace NPOI.HWPF.Model.Types { /** * Table Autoformat Look sPecifier (TLP). * <p> * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 * Binary File Format * * NOTE: This source is automatically generated please do not modify this file. * Either subclass or remove the record in src/records/defInitions. * * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary * File Format Specification [*.doc] */ public abstract class TLPAbstractType : BaseObject { protected short field_1_itl; protected byte field_2_tlp_flags; private static BitField fBorders = new BitField(0x0001); private static BitField fShading = new BitField(0x0002); private static BitField fFont = new BitField(0x0004); private static BitField fColor = new BitField(0x0008); private static BitField fBestFit = new BitField(0x0010); private static BitField fHdrRows = new BitField(0x0020); private static BitField fLastRow = new BitField(0x0040); public TLPAbstractType() { } protected void FillFields(byte[] data, int offset) { field_1_itl = LittleEndian.GetShort(data, 0x0 + offset); field_2_tlp_flags = data[0x2 + offset]; } public void Serialize(byte[] data, int offset) { LittleEndian.PutShort(data, 0x0 + offset, field_1_itl); data[0x2 + offset] = field_2_tlp_flags; } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[TLP]\n"); buffer.Append(" .itl = "); buffer.Append(" (").Append(GetItl()).Append(" )\n"); buffer.Append(" .tlp_flags = "); buffer.Append(" (").Append(GetTlp_flags()).Append(" )\n"); buffer.Append(" .fBorders = ") .Append(IsFBorders()).Append('\n'); buffer.Append(" .fShading = ") .Append(IsFShading()).Append('\n'); buffer.Append(" .fFont = ") .Append(IsFFont()).Append('\n'); buffer.Append(" .fColor = ") .Append(IsFColor()).Append('\n'); buffer.Append(" .fBestFit = ") .Append(IsFBestFit()).Append('\n'); buffer.Append(" .fHdrRows = ") .Append(IsFHdrRows()).Append('\n'); buffer.Append(" .fLastRow = ") .Append(IsFLastRow()).Append('\n'); buffer.Append("[/TLP]\n"); return buffer.ToString(); } /** * Size of record (exluding 4 byte header) */ public int GetSize() { return 4 + +2 + 1; } /** * Get the itl field for the TLP record. */ public short GetItl() { return field_1_itl; } /** * Set the itl field for the TLP record. */ public void SetItl(short field_1_itl) { this.field_1_itl = field_1_itl; } /** * Get the tlp_flags field for the TLP record. */ public byte GetTlp_flags() { return field_2_tlp_flags; } /** * Set the tlp_flags field for the TLP record. */ public void SetTlp_flags(byte field_2_tlp_flags) { this.field_2_tlp_flags = field_2_tlp_flags; } /** * Sets the fBorders field value. When == 1, use the border properties from * the selected table look */ public void SetFBorders(bool value) { field_2_tlp_flags = (byte)fBorders.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, use the border properties from the selected table look * * @return the fBorders field value. */ public bool IsFBorders() { return fBorders.IsSet(field_2_tlp_flags); } /** * Sets the fShading field value. When == 1, use the shading properties from * the selected table look */ public void SetFShading(bool value) { field_2_tlp_flags = (byte)fShading.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, use the shading properties from the selected table look * * @return the fShading field value. */ public bool IsFShading() { return fShading.IsSet(field_2_tlp_flags); } /** * Sets the fFont field value. When == 1, use the font from the selected * table look */ public void SetFFont(bool value) { field_2_tlp_flags = (byte)fFont.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, use the font from the selected table look * * @return the fFont field value. */ public bool IsFFont() { return fFont.IsSet(field_2_tlp_flags); } /** * Sets the fColor field value. When == 1, use the color from the selected * table look */ public void SetFColor(bool value) { field_2_tlp_flags = (byte)fColor.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, use the color from the selected table look * * @return the fColor field value. */ public bool IsFColor() { return fColor.IsSet(field_2_tlp_flags); } /** * Sets the fBestFit field value. When == 1, do best fit from the selected * table look */ public void SetFBestFit(bool value) { field_2_tlp_flags = (byte)fBestFit.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, do best fit from the selected table look * * @return the fBestFit field value. */ public bool IsFBestFit() { return fBestFit.IsSet(field_2_tlp_flags); } /** * Sets the fHdrRows field value. When == 1, apply properties from the * selected table look to the header rows in the table */ public void SetFHdrRows(bool value) { field_2_tlp_flags = (byte)fHdrRows.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, apply properties from the selected table look to the header * rows in the table * * @return the fHdrRows field value. */ public bool IsFHdrRows() { return fHdrRows.IsSet(field_2_tlp_flags); } /** * Sets the fLastRow field value. When == 1, apply properties from the * selected table look to the last row in the table */ public void SetFLastRow(bool value) { field_2_tlp_flags = (byte)fLastRow.SetBoolean(field_2_tlp_flags, value); } /** * When == 1, apply properties from the selected table look to the last row * in the table * * @return the fLastRow field value. */ public bool IsFLastRow() { return fLastRow.IsSet(field_2_tlp_flags); } } }
#region Copyright notice and license // Copyright 2015, Google 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. // * 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.Threading.Tasks; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // TODO(jtattermusch): this field doesn't need to be initialized for unary response calls. // Indicates that response streaming call has finished. TaskCompletionSource<object> streamingCallFinishedTcs = new TaskCompletionSource<object>(); // TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers). // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { var profiler = Profilers.ForCurrentThread(); using (profiler.NewScope("AsyncCall.UnaryCall")) using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create()) { byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) using (var ctx = BatchContextSafeHandle.Create()) { call.StartUnary(ctx, payload, metadataArray, GetWriteFlagsForCall()); var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); } } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(HandleUnaryResponse, payload, metadataArray, GetWriteFlagsForCall()); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(HandleUnaryResponse, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; byte[] payload = UnsafeSerialize(msg); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(HandleFinished, payload, metadataArray, GetWriteFlagsForCall()); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(HandleFinished, metadataArray); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// </summary> public Task<TResponse> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// </summary> public Task SendCloseFromClientAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (disposed || finished) { // In case the call has already been finished by the serverside, // the halfclose has already been done implicitly, so just return // completed task here. halfcloseRequested = true; return Task.FromResult<object>(null); } call.StartSendCloseFromClient(HandleSendFinished); halfcloseRequested = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Get the task that completes once if streaming call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingCallFinishedTask { get { return streamingCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResources() { details.Channel.RemoveCallReference(this); } protected override bool IsClient { get { return true; } } protected override Exception GetRpcExceptionClientOnly() { return new RpcException(finishedStatus.Value.Status); } protected override Task CheckSendAllowedOrEarlyResult() { var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (finishedStatus.HasValue) { // throwing RpcException if we already received status on client // side makes the most sense. // Note that this throws even for StatusCode.OK. // Writing after the call has finished is not a programming error because server can close // the call anytime, so don't throw directly, but let the write task finish with an error. var tcs = new TaskCompletionSource<object>(); tcs.SetException(new RpcException(finishedStatus.Value.Status)); return tcs.Task; } return null; } private Task CheckSendPreconditionsClientSide() { GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time."); if (cancelRequested) { // Return a cancelled task. var tcs = new TaskCompletionSource<object>(); tcs.SetCanceled(); return tcs.Task; } return null; } private void Initialize(CompletionQueueSafeHandle cq) { using (Profilers.ForCurrentThread().NewScope("AsyncCall.Initialize")) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); InitializeInternal(call); RegisterCancellationCallback(); } } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { using (Profilers.ForCurrentThread().NewScope("AsyncCall.CreateNativeCall")) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance; var credentials = details.Options.Credentials; using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null) { var result = details.Channel.Handle.CreateCall( parentCall, ContextPropagationToken.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials); return result; } } } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { var token = details.Options.CancellationToken; if (token.CanBeCanceled) { token.Register(() => this.Cancel()); } } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { // TODO(jtattermusch): handle success==false responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse")) { TaskCompletionSource<object> delayedStreamingWriteTcs = null; TResponse msg = default(TResponse); var deserializeException = TryDeserialize(receivedMessage, out msg); lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } ReleaseResourcesIfPossible(); } responseHeadersTcs.SetResult(responseHeaders); if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status)); return; } unaryResponseTcs.SetResult(msg); } } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; lock (myLock) { finished = true; finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } ReleaseResourcesIfPossible(); } if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { streamingCallFinishedTcs.SetException(new RpcException(status)); return; } streamingCallFinishedTcs.SetResult(null); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class JuiceStreamPathTest { [TestCase(1e3, true, false)] // When the coordinates are large, the slope invariant fails within the specified absolute allowance due to the floating-number precision. [TestCase(1e9, false, false)] // Using discrete values sometimes discover more edge cases. [TestCase(10, true, true)] public void TestRandomInsertSetPosition(double scale, bool checkSlope, bool integralValues) { var rng = new Random(1); var path = new JuiceStreamPath(); for (int iteration = 0; iteration < 100000; iteration++) { if (rng.Next(10) == 0) path.Clear(); int vertexCount = path.Vertices.Count; switch (rng.Next(2)) { case 0: { double distance = rng.NextDouble() * scale * 2 - scale; if (integralValues) distance = Math.Round(distance); float oldX = path.PositionAtDistance(distance); int index = path.InsertVertex(distance); Assert.That(path.Vertices.Count, Is.EqualTo(vertexCount + 1)); Assert.That(path.Vertices[index].Distance, Is.EqualTo(distance)); Assert.That(path.Vertices[index].X, Is.EqualTo(oldX)); break; } case 1: { int index = rng.Next(path.Vertices.Count); double distance = path.Vertices[index].Distance; float newX = (float)(rng.NextDouble() * scale * 2 - scale); if (integralValues) newX = MathF.Round(newX); path.SetVertexPosition(index, newX); Assert.That(path.Vertices.Count, Is.EqualTo(vertexCount)); Assert.That(path.Vertices[index].Distance, Is.EqualTo(distance)); Assert.That(path.Vertices[index].X, Is.EqualTo(newX)); break; } } assertInvariants(path.Vertices, checkSlope); } } [Test] public void TestRemoveVertices() { var path = new JuiceStreamPath(); path.Add(10, 5); path.Add(20, -5); int removeCount = path.RemoveVertices((v, i) => v.Distance == 10 && i == 1); Assert.That(removeCount, Is.EqualTo(1)); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(0, 0), new JuiceStreamPathVertex(20, -5) })); removeCount = path.RemoveVertices((_, i) => i == 0); Assert.That(removeCount, Is.EqualTo(1)); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(20, -5) })); removeCount = path.RemoveVertices((_, i) => true); Assert.That(removeCount, Is.EqualTo(1)); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex() })); } [Test] public void TestResampleVertices() { var path = new JuiceStreamPath(); path.Add(-100, -10); path.Add(100, 50); path.ResampleVertices(new double[] { -50, 0, 70, 120 }); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(-100, -10), new JuiceStreamPathVertex(-50, -5), new JuiceStreamPathVertex(0, 0), new JuiceStreamPathVertex(70, 35), new JuiceStreamPathVertex(100, 50), new JuiceStreamPathVertex(100, 50), })); path.Clear(); path.SetVertexPosition(0, 10); path.ResampleVertices(Array.Empty<double>()); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(0, 10) })); } [Test] public void TestRandomConvertFromSliderPath() { var rng = new Random(1); var path = new JuiceStreamPath(); var sliderPath = new SliderPath(); for (int iteration = 0; iteration < 10000; iteration++) { sliderPath.ControlPoints.Clear(); do { int start = sliderPath.ControlPoints.Count; do { float x = (float)(rng.NextDouble() * 1e3); float y = (float)(rng.NextDouble() * 1e3); sliderPath.ControlPoints.Add(new PathControlPoint(new Vector2(x, y))); } while (rng.Next(2) != 0); int length = sliderPath.ControlPoints.Count - start + 1; sliderPath.ControlPoints[start].Type = length <= 2 ? PathType.Linear : length == 3 ? PathType.PerfectCurve : PathType.Bezier; } while (rng.Next(3) != 0); if (rng.Next(5) == 0) sliderPath.ExpectedDistance.Value = rng.NextDouble() * 3e3; else sliderPath.ExpectedDistance.Value = null; path.ConvertFromSliderPath(sliderPath); Assert.That(path.Vertices[0].Distance, Is.EqualTo(0)); Assert.That(path.Distance, Is.EqualTo(sliderPath.Distance).Within(1e-3)); assertInvariants(path.Vertices, true); double[] sampleDistances = Enumerable.Range(0, 10) .Select(_ => rng.NextDouble() * sliderPath.Distance) .ToArray(); foreach (double distance in sampleDistances) { float expected = sliderPath.PositionAt(distance / sliderPath.Distance).X; Assert.That(path.PositionAtDistance(distance), Is.EqualTo(expected).Within(1e-3)); } path.ResampleVertices(sampleDistances); assertInvariants(path.Vertices, true); foreach (double distance in sampleDistances) { float expected = sliderPath.PositionAt(distance / sliderPath.Distance).X; Assert.That(path.PositionAtDistance(distance), Is.EqualTo(expected).Within(1e-3)); } } } [Test] public void TestRandomConvertToSliderPath() { var rng = new Random(1); var path = new JuiceStreamPath(); var sliderPath = new SliderPath(); for (int iteration = 0; iteration < 10000; iteration++) { path.Clear(); do { double distance = rng.NextDouble() * 1e3; float x = (float)(rng.NextDouble() * 1e3); path.Add(distance, x); } while (rng.Next(5) != 0); float sliderStartY = (float)(rng.NextDouble() * JuiceStreamPath.OSU_PLAYFIELD_HEIGHT); path.ConvertToSliderPath(sliderPath, sliderStartY); Assert.That(sliderPath.Distance, Is.EqualTo(path.Distance).Within(1e-3)); Assert.That(sliderPath.ControlPoints[0].Position.X, Is.EqualTo(path.Vertices[0].X)); assertInvariants(path.Vertices, true); foreach (var point in sliderPath.ControlPoints) { Assert.That(point.Type, Is.EqualTo(PathType.Linear).Or.Null); Assert.That(sliderStartY + point.Position.Y, Is.InRange(0, JuiceStreamPath.OSU_PLAYFIELD_HEIGHT)); } for (int i = 0; i < 10; i++) { double distance = rng.NextDouble() * path.Distance; float expected = path.PositionAtDistance(distance); Assert.That(sliderPath.PositionAt(distance / sliderPath.Distance).X, Is.EqualTo(expected).Within(1e-3)); } } } [Test] public void TestInvalidation() { var path = new JuiceStreamPath(); Assert.That(path.InvalidationID, Is.EqualTo(1)); int previousId = path.InvalidationID; path.InsertVertex(10); checkNewId(); path.SetVertexPosition(1, 5); checkNewId(); path.Add(20, 0); checkNewId(); path.RemoveVertices((v, _) => v.Distance == 20); checkNewId(); path.ResampleVertices(new double[] { 5, 10, 15 }); checkNewId(); path.Clear(); checkNewId(); path.ConvertFromSliderPath(new SliderPath()); checkNewId(); void checkNewId() { Assert.That(path.InvalidationID, Is.Not.EqualTo(previousId)); previousId = path.InvalidationID; } } private void assertInvariants(IReadOnlyList<JuiceStreamPathVertex> vertices, bool checkSlope) { Assert.That(vertices, Is.Not.Empty); for (int i = 0; i < vertices.Count; i++) { Assert.That(double.IsFinite(vertices[i].Distance)); Assert.That(float.IsFinite(vertices[i].X)); } for (int i = 1; i < vertices.Count; i++) { Assert.That(vertices[i].Distance, Is.GreaterThanOrEqualTo(vertices[i - 1].Distance)); if (!checkSlope) continue; float xDiff = Math.Abs(vertices[i].X - vertices[i - 1].X); double distanceDiff = vertices[i].Distance - vertices[i - 1].Distance; Assert.That(xDiff, Is.LessThanOrEqualTo(distanceDiff).Within(Precision.FLOAT_EPSILON)); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace MailPlus { using Models; /// <summary> /// </summary> public partial interface IMailPlusClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Get details of a campaign mailing /// </summary> /// <remarks> /// Returns the details of a given mailing sent by a campaign, /// including details of the used links. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingDetailsWithHttpMessagesAsync(string encryptedMailingId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get bounces for a campaign mailing /// </summary> /// <remarks> /// Returns bounced contacts. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingBouncesWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.DateTime? fromDate = default(System.DateTime?), System.DateTime? toDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get clicks for a campaign mailing /// </summary> /// <remarks> /// Returns contacts who clicked a link in a given mailing. Link /// details can be retrieved by using the GET method /// /campaign-mailing/{encryptedMailingId}. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingClicksWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.DateTime? fromDate = default(System.DateTime?), System.DateTime? toDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get clicks for a campaign mailing for a contact /// </summary> /// <remarks> /// Returns click interactions for a given contact in a specified /// mailing. Link details can be retrieved by using the GET method /// /campaign-mailing/{encryptedMailingId}. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='campaignSubscriptionId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingContactClicksWithHttpMessagesAsync(string encryptedMailingId, int campaignSubscriptionId, int? after = default(int?), int? pageSize = default(int?), System.DateTime? fromDate = default(System.DateTime?), System.DateTime? toDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get opens for a campaign mailing /// </summary> /// <remarks> /// Returns contacts who opened a given mailing. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingOpensWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.DateTime? fromDate = default(System.DateTime?), System.DateTime? toDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get opens for a campaign mailing for a contact /// </summary> /// <remarks> /// Returns open interations for a given contact in a specified /// mailing. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='campaignSubscriptionId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingContactOpensWithHttpMessagesAsync(string encryptedMailingId, int campaignSubscriptionId, int? after = default(int?), int? pageSize = default(int?), System.DateTime? fromDate = default(System.DateTime?), System.DateTime? toDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get recipients for a campaign mailing /// </summary> /// <remarks> /// Returns contacts to which the mailing has been sent. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingRecipientContactsWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.DateTime? fromDate = default(System.DateTime?), System.DateTime? toDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all campaigns /// </summary> /// <remarks> /// Returns a list of all campaigns, including external campaign /// triggers. Other trigger types will not be shown. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Campaign>>> GetCampaignsWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Trigger a campaign for a specific contact /// </summary> /// <remarks> /// Triggers a campaign for a given contact. The encryptedTriggerId /// can be retrieved by using the GET method /campaign/list. /// </remarks> /// <param name='encryptedTriggerId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> TriggerCampaignWithHttpMessagesAsync(string encryptedTriggerId, CampaignTriggerRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all mailings of a campaign /// </summary> /// <remarks> /// Returns all mailings being sent by a given campaign. The /// encryptedCampaignId can be retrieved by using the GET method /// /campaign/list. /// </remarks> /// <param name='encryptedCampaignId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetCampaignMailingsWithHttpMessagesAsync(string encryptedCampaignId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Stop a campaign for a specific contact /// </summary> /// <remarks> /// Stops a running campaign for a given contact. The /// encryptedCampaignId can be retrieved by using the GET method /// /campaign/list. /// </remarks> /// <param name='encryptedCampaignId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> StopCampaignWithHttpMessagesAsync(string encryptedCampaignId, CampaignStopRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add a contact /// </summary> /// <remarks> /// Adds a contact to Mailplus. A unique identifier "externalId" is /// required for each contact. Available properties can be retrieved /// by using the GET methode /contact/properties/list. /// </remarks> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> InsertContactWithHttpMessagesAsync(ContactRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get bounced contacts /// </summary> /// <remarks> /// Returns bounced contacts within a specific period of time. /// </remarks> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetBouncedContactsWithHttpMessagesAsync(System.DateTime fromDate, System.DateTime toDate, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all properties /// </summary> /// <remarks> /// Returns a list of available properties that are part of a contact /// object. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Property>>> GetContactPropertiesWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get contacts by properties /// </summary> /// <remarks> /// Returns a contact based on a given property value. Available /// properties can be retrieved by using the GET methode /// /contact/properties/list. /// </remarks> /// <param name='mPSearchQuery'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Contact>>> SearchContactsWithHttpMessagesAsync(string mPSearchQuery, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get updated contacts /// </summary> /// <remarks> /// Returns contacts which have been updated within a specific period /// of time. /// </remarks> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetUpdatedContactsWithHttpMessagesAsync(System.DateTime fromDate, System.DateTime toDate, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get a contact /// </summary> /// <remarks> /// Returns a given contact, including a list of all properties. /// Properties will only be shown if data is available. /// </remarks> /// <param name='externalId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetContactWithHttpMessagesAsync(string externalId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Update a contact /// </summary> /// <remarks> /// Modifies a existing given contact. /// </remarks> /// <param name='body'> /// </param> /// <param name='externalId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> UpdateContactWithHttpMessagesAsync(ContactRequest body, string externalId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get campaign mailing history for a contact /// </summary> /// <remarks> /// Returns received campaign mailings for a given contact. Default /// pagesize is 50 (Cannot be modified). /// </remarks> /// <param name='externalId'> /// </param> /// <param name='after'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetContactCampaignMailingHistoryWithHttpMessagesAsync(string externalId, int? after = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get form history for a contact /// </summary> /// <remarks> /// Returns submitted forms for a given contact. /// </remarks> /// <param name='externalId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetContactFormHistoryWithHttpMessagesAsync(string externalId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get mailing history for a contact /// </summary> /// <remarks> /// Returns received mailings for a given contact. Default pagesize is /// 50 (Cannot be modified). /// </remarks> /// <param name='externalId'> /// </param> /// <param name='after'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetContactMailingHistoryWithHttpMessagesAsync(string externalId, int? after = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add a conversion interaction /// </summary> /// <remarks> /// Posts created-, converted and abandoned shopping carts to MailPlus /// as a result of click in a sent mailing. The mailplusId is added /// to every trackable URL, that leads to your website. This ID is /// unique for every mailing and contact. /// </remarks> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> CreateConversionInteractionWithHttpMessagesAsync(Conversion body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all forms /// </summary> /// <remarks> /// Returns a list all available forms. /// </remarks> /// <param name='formSubType'> /// Possible values include: 'normal', 'subscribe', 'unSubscribe', /// 'editProfile' /// </param> /// <param name='formState'> /// Possible values include: 'draft', 'proof', 'final' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Form>>> GetFormsWithHttpMessagesAsync(string formSubType = default(string), string formState = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get form results /// </summary> /// <remarks> /// Returns submitted results of a requested form, including all given /// answers for every submit. /// </remarks> /// <param name='formId'> /// </param> /// <param name='completed'> /// </param> /// <param name='startDate'> /// </param> /// <param name='endDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<FormResult>>> GetFormResultsWithHttpMessagesAsync(int formId, bool? completed = default(bool?), System.DateTime? startDate = default(System.DateTime?), System.DateTime? endDate = default(System.DateTime?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Post a form result /// </summary> /// <remarks> /// Submits a form response to a MailPlus form. The post URL needs to /// refer to your own system. /// </remarks> /// <param name='formId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<FormResponse>> SubmitFormWithHttpMessagesAsync(int formId, ParamsModel body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get form result /// </summary> /// <remarks> /// Returns a submitted result of a requested form for a given /// formResultId. A formResultId can be retrieved by using the GET /// method /contact/{externalId}/forms. /// </remarks> /// <param name='formId'> /// </param> /// <param name='formResultId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetFormResultWithHttpMessagesAsync(int formId, int formResultId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get a form /// </summary> /// <remarks> /// Returns a HTML output of the requested form. /// </remarks> /// <param name='formId'> /// </param> /// <param name='postUrl'> /// </param> /// <param name='encId'> /// Unique (MailPlus) id of a contact (when present the form is /// prefilled with contact fields) /// </param> /// <param name='extraParams'> /// </param> /// <param name='outputFormat'> /// Possible values include: 'HTML4STRICT', 'XHTML1STRICT' /// </param> /// <param name='outputMode'> /// Possible values include: 'TABLES', 'DIV' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetFormWithHttpMessagesAsync(int formId, string postUrl, string encId = default(string), string extraParams = default(string), string outputFormat = "HTML4STRICT", string outputMode = "TABLES", System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Post a form /// </summary> /// <remarks> /// Returns a prefilled HTML output of a requested form, based on the /// given parameters for a specific contact. If a contact is present /// in MailPlus, existing data will be prefilled in de used contact /// fields. The post URL needs to refer to your own system. /// </remarks> /// <param name='formId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> PostFormWithHttpMessagesAsync(int formId, FormRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get sent mailings in period /// </summary> /// <remarks> /// Returns a list of all mailings, including a link to the archived /// online version of the sent mailing. /// </remarks> /// <param name='fromDate'> /// </param> /// <param name='toDate'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingsWithHttpMessagesAsync(System.DateTime fromDate, System.DateTime toDate, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get mailing data /// </summary> /// <remarks> /// Returns the details of a given mailing, including details of the /// used links. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingDetailsWithHttpMessagesAsync(string encryptedMailingId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get bounces for mailing /// </summary> /// <remarks> /// Returns bounced contacts. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingBouncesWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get clicks for mailing /// </summary> /// <remarks> /// Returns contacts who clicked a link in a given mailing. Link /// details can be retrieved by using the GET method /// /mailing/{encryptedMailingId}. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingClicksWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get clicks of a mailing for a contact /// </summary> /// <remarks> /// Returns click interactions for a given contact in a specified /// mailing. Link details can be retrieved by using the GET method /// /mailing/{encryptedMailingId}. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='externalId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingContactClicksWithHttpMessagesAsync(string encryptedMailingId, string externalId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get opens for mailing /// </summary> /// <remarks> /// Returns contacts who opened a given mailing. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingOpensWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get opens of a mailing for a contact /// </summary> /// <remarks> /// Returns open interations for a given contact in a specified /// mailing. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='externalId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingContactOpensWithHttpMessagesAsync(string encryptedMailingId, string externalId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get recipients for mailing /// </summary> /// <remarks> /// Returns contacts to which the mailing has been sent. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='after'> /// </param> /// <param name='pageSize'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingRecipientContactsWithHttpMessagesAsync(string encryptedMailingId, int? after = default(int?), int? pageSize = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get mailing statistics /// </summary> /// <remarks> /// Returns a summary of the results for a sent mailing, such as the /// opens, clicks, bounces, etc. /// </remarks> /// <param name='encryptedMailingId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetMailingStatsWithHttpMessagesAsync(string encryptedMailingId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add an order /// </summary> /// <remarks> /// Adds an order to MailPlus. /// </remarks> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> InsertOrderWithHttpMessagesAsync(OrderRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete an order /// </summary> /// <remarks> /// Deletes an existing order. /// </remarks> /// <param name='externalOrderId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> DeleteOrderWithHttpMessagesAsync(string externalOrderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Update an order /// </summary> /// <remarks> /// Updates an existing order. /// </remarks> /// <param name='externalOrderId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> UpdateOrderWithHttpMessagesAsync(string externalOrderId, OrderRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add a product /// </summary> /// <remarks> /// Adds a product to MailPlus. /// </remarks> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> InsertProductWithHttpMessagesAsync(ProductRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete a product /// </summary> /// <remarks> /// Deletes an existing given product. /// </remarks> /// <param name='externalProductId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> DeleteProductWithHttpMessagesAsync(string externalProductId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get a product /// </summary> /// <remarks> /// Returns a given product. /// </remarks> /// <param name='externalProductId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<object>> GetProductWithHttpMessagesAsync(string externalProductId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Update a product /// </summary> /// <remarks> /// Updates an existing given product. /// </remarks> /// <param name='externalProductId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> UpdateProductWithHttpMessagesAsync(string externalProductId, ProductRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Subscribe a contact /// </summary> /// <remarks> /// Adds a contact to Mailplus. A unique identifier "externalId" is /// NOT required. Available properties can be retrieved by using the /// GET methode /contact/properties/list. /// </remarks> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> SubscribeContactWithHttpMessagesAsync(Contact body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all temporary lists /// </summary> /// <remarks> /// Returns a list of all available temporary lists. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<TemporaryList>>> GetTemporaryListsWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add a temporary list /// </summary> /// <remarks> /// Adds a set of existing contacts as a temporary list to MailPlus, /// based on external contact id's. /// </remarks> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> CreateTemporaryListWithHttpMessagesAsync(CreateTemporaryListRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete a temporary list /// </summary> /// <remarks> /// Deletes a temporary list. An externalTemporaryListId can be /// retrieved by using the GET method /templist. /// </remarks> /// <param name='externalTemporaryListId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> DeleteTemporaryListWithHttpMessagesAsync(string externalTemporaryListId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Add contacts to a temporary list /// </summary> /// <remarks> /// Adds a set of existing contacts to a given temporary list, based /// on external contact id's. An externalTemporaryListId can be /// retrieved by using the GET method /templist. /// </remarks> /// <param name='externalTemporaryListId'> /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ErrorResponse>> AddContactsToTemporaryListWithHttpMessagesAsync(string externalTemporaryListId, AddContactsToTemporaryListRequest body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Epi.Data; using Epi.Fields; using Epi.Windows.Dialogs; namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs { /// <summary> /// Dialog for selecting the data source of a dropdown field /// </summary> public partial class DataSourceSelector : DialogBase //Form { #region Private Class Members private string fieldName = string.Empty; private DataTable codeTable; private Page page; string tableName; string columnName; private bool isExclusiveTable; private TableBasedDropDownField field; private string sourceTableName = string.Empty; private string textColumnName = string.Empty; private bool isCommentLegal = false; #endregion Private Class Members /// <summary> /// Constructor for the class /// </summary> public DataSourceSelector() { InitializeComponent(); } /// <summary> /// Constructor for the class /// </summary> /// <param name="field">field</param> /// <param name="currentFieldName">The name of the field</param> /// <param name="frm">Form</param> /// <param name="currentPage">Page</param> public DataSourceSelector(TableBasedDropDownField field, string currentFieldName, MainForm frm, Page currentPage) : base(frm) { #region Input Validation if (string.IsNullOrEmpty(currentFieldName)) { throw new ArgumentNullException("currentFieldName"); } #endregion Input validation InitializeComponent(); page = currentPage; TableBasedDropDownField ddlField = (TableBasedDropDownField)field; if (!string.IsNullOrEmpty(field.SourceTableName)) { codeTable = ddlField.GetSourceData(); } this.field = field; if (field.FieldType == MetaFieldType.CommentLegal) { isCommentLegal = true; } else { isCommentLegal = false; } this.fieldName = currentFieldName; dgCodeTable.CaptionText += currentFieldName; try { if (!string.IsNullOrEmpty(field.SourceTableName)) { tableName = field.SourceTableName; columnName = field.TextColumnName; dgCodeTable.PreferredColumnWidth = Convert.ToInt32(dgCodeTable.Width * .87); dgCodeTable.DataSource = field.GetSourceData(); btnCreate.Enabled = false; btnExisting.Enabled = false; } else { btnCreate.Enabled = true; btnExisting.Enabled = true; } } catch { //TODO: move string to sharedstrings.resx throw new SystemException("Error loading data."); } } /// <summary> /// Constructor for the class /// </summary> /// <param name="field">The field</param> /// <param name="currentFieldName">The name of the field</param> public DataSourceSelector(DDLFieldOfLegalValues field, string currentFieldName) { #region Input Validation if (string.IsNullOrEmpty(currentFieldName)) { throw new ArgumentNullException("currentFieldName"); } #endregion Input validation InitializeComponent(); this.field = field; this.fieldName = currentFieldName; dgCodeTable.CaptionText += currentFieldName; try { if (!string.IsNullOrEmpty(field.SourceTableName)) { tableName = field.SourceTableName; columnName = field.TextColumnName; dgCodeTable.PreferredColumnWidth = Convert.ToInt32(dgCodeTable.Width * .87); dgCodeTable.DataSource = field.GetSourceData(); btnCreate.Enabled = false; btnExisting.Enabled = false; } } catch { //TODO: move string to sharedstrings.resx throw new SystemException("Error loading data."); } } private void btnCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } private void btnCreate_Click(object sender, EventArgs e) { CodeTableDefinition codeTableDialog = new CodeTableDefinition(); DialogResult result = codeTableDialog.ShowDialog(); if (result == DialogResult.OK) { DataTable bindingTable = GetProject().CodeData.GetCodeTableNamesForProject(GetProject()); DataView dataView = bindingTable.DefaultView; string display = String.Empty; string kindOfDatabase = GetProject().CodeData.IdentifyDatabase(); //TODO: Will need to rework this section not to be dependant on strings and develop a // more OO solution switch (kindOfDatabase) { case "ACCESS": display = ColumnNames.NAME; break; case "SQLSERVER": display = ColumnNames.SCHEMA_TABLE_NAME; break; case "MYSQL": display = ColumnNames.SCHEMA_TABLE_NAME; break; default: display = ColumnNames.SCHEMA_TABLE_NAME; break; } dataView.Sort = display; // Check if this table already exists. If so, increment a suffix counter. tableName = Util.Squeeze(codeTableDialog.CodeTableName); string newTableName = tableName; int count = 0; while (dataView.Find(newTableName)!=-1) { count++; newTableName = tableName + count; } tableName = newTableName; columnName = Util.Squeeze(codeTableDialog.CodeTableRootName); if(!Util.IsFirstCharacterALetter(columnName)) columnName = "col" + columnName; DataTable table = new DataTable(tableName); table.Columns.Add(columnName); dgCodeTable.PreferredColumnWidth = Convert.ToInt32(dgCodeTable.Width * .87); dgCodeTable.DataSource = table; codeTableDialog.Close(); } } private void btnOk_Click(object sender, EventArgs e) { TableBasedDropDownField ddlField = (TableBasedDropDownField)field; //if this is a new code table, use tableName //otherwise, use sourceTableName if (!string.IsNullOrEmpty(tableName)) { field.SourceTableName = tableName; } else if (!string.IsNullOrEmpty(sourceTableName)) { field.SourceTableName = sourceTableName; } else { throw new ArgumentNullException("Table name for code table"); } //if this is a new code table, use columnName //otherwise, use textColumnName if (!string.IsNullOrEmpty(columnName)) { field.TextColumnName = columnName; } else if (!string.IsNullOrEmpty(textColumnName)) { field.TextColumnName = textColumnName; } else { throw new ArgumentNullException("Column name for code table"); } if ((!string.IsNullOrEmpty(tableName)) && (!string.IsNullOrEmpty(columnName))) { field.GetMetadata().CreateCodeTable(tableName, columnName); field.GetMetadata().SaveCodeTableData((DataTable)dgCodeTable.DataSource, tableName, columnName); } if (!string.IsNullOrEmpty(field.SourceTableName)) { codeTable = ddlField.GetSourceData(); } if (codeTable != null) { foreach (DataRow row in codeTable.Rows) { if (isCommentLegal) { if (((row.ItemArray[0].ToString().IndexOf("-") == -1))) { string msg = SharedStrings.SEPARATE_COMMENT_LEGAL_WITH_HYPEN + ": \n" + row.ItemArray[0].ToString(); MsgBox.ShowError(msg); return; } } } } this.DialogResult = DialogResult.OK; this.Hide(); } /// <summary> /// Gets the table name /// </summary> public string TableName { get { return this.tableName; } } /// <summary> /// Gets the column name /// </summary> public string ColumnName { get { return this.columnName; } } /// <summary> /// Returns boolean to specify whether or not it is an exclusive table /// </summary> public bool IsExclusiveTable { get { return (!isExclusiveTable); } } private void DataSourceSelector_Load(object sender, System.EventArgs e) { DisplayData(); dgCodeTable.Focus(); } private void btnExisting_Click(object sender, EventArgs e) { ViewSelectionDialog dialog = new ViewSelectionDialog(this.MainForm, page.GetProject()); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { sourceTableName = dialog.TableName; dialog.Close(); ShowFieldSelection(sourceTableName); } } private void ShowFieldSelection(string tableName) { FieldSelectionDialog fieldSelection = new FieldSelectionDialog(MainForm, page.GetProject(), tableName); DialogResult result = fieldSelection.ShowDialog(); if (result == DialogResult.OK) { textColumnName = fieldSelection.ColumnName; codeTable = GetProject().GetTableData(tableName, textColumnName, string.Empty); fieldSelection.Close(); DisplayData(); isExclusiveTable = true; } } private Project GetProject() { return page.GetProject(); } private void DisplayData() { if (codeTable != null) { dgCodeTable.Visible = true; btnOk.Enabled = true; btnCreate.Enabled = false; btnExisting.Enabled = false; btnDelete.Enabled = true; codeTable.TableName = sourceTableName; dgCodeTable.PreferredColumnWidth =Convert.ToInt32( dgCodeTable.Width * .87); dgCodeTable.DataSource = codeTable; dgCodeTable.CaptionText = sourceTableName; } } } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System.Collections.Generic; using Voxalia.Shared; using Voxalia.ClientGame.GraphicsSystems; using Voxalia.ClientGame.ClientMainSystem; using FreneticScript; using OpenTK.Graphics; using System.Linq; namespace Voxalia.ClientGame.UISystem { /// <summary> /// Handles the interactive user text console. /// TODO: Make non-static. /// TODO: Support channels. /// TODO: Maybe rewrite entirely!? /// </summary> public class UIConsole { /// <summary> /// Holds the Graphics text object, for rendering. /// </summary> public static string ConsoleText; public static Location ConsoleTextLoc; /// <summary> /// Holds the text currently being typed. /// </summary> public static string Typing; public static Location TypingLoc; /// <summary> /// Holds the "scrolled-up" text. /// </summary> public static string ScrollText; public static Location ScrollTextLoc; /// <summary> /// The background texture to be used. /// </summary> public static Texture ConsoleTexture; /// <summary> /// How many lines the console should have. /// </summary> public static int Lines = 100; /// <summary> /// How long across (in pixels) console text may be. /// </summary> public static int MaxWidth = 1142; /// <summary> /// Whether the console is open. /// </summary> public static bool Open = false; /// <summary> /// The text currently being typed by the user. /// </summary> public static string TypingText = ""; /// <summary> /// Where in the typing text the cursor is at. /// </summary> public static int TypingCursor = 0; /// <summary> /// What line has been scrolled to: /// 0 = farthest down, -LINES = highest up. /// The selected line will be rendered at the bottom of the screen. /// </summary> public static int ScrolledLine = 0; /// <summary> /// How many recent commands to store. /// </summary> public static int MaxRecentCommands = 50; /// <summary> /// A list of all recently execute command-lines. /// </summary> public static List<string> RecentCommands = new List<string>() { "" }; /// <summary> /// What spot in the RecentCommands the user is currently at. /// </summary> public static int RecentSpot = 0; static bool ready = false; static string pre_waiting = ""; static int extralines = 0; static double LineBack = 0; /// <summary> /// Prepares the console. /// </summary> public static void InitConsole() { ready = true; ConsoleText = Utilities.CopyText("\n", Lines); ConsoleTextLoc = new Location(5, 0, 0); Typing = ""; TypingLoc = new Location(5, 0, 0); ScrollText = "^1" + Utilities.CopyText("/\\ ", 150); ScrollTextLoc = new Location(5, 0, 0); MaxWidth = Client.Central.Window.Width - 10; ConsoleTexture = Client.Central.Textures.GetTexture("ui/hud/console"); WriteLine("Console loaded!"); Write(pre_waiting); } /// <summary> /// Writes a line of text to the console. /// </summary> /// <param name="text">The text to be written.</param> public static void WriteLine(string text) { Write(TextStyle.Default + text + "\n"); SysConsole.Output(OutputType.CLIENTINFO, text); } /// <summary> /// Writes text to the console. /// </summary> /// <param name="text">The text to be written.</param> public static void Write(string text) { if (!ready) { pre_waiting += text; return; } if (!ConsoleText.EndsWith("\n")) { for (int x = ConsoleText.Length - 1; x > 0; x--) { if (ConsoleText[x] == '\n') { string snippet = ConsoleText.Substring(x + 1, ConsoleText.Length - (x + 1)); text = snippet + text; ConsoleText = ConsoleText.Substring(0, x + 1); break; } } } text = text.Replace('\r', ' '); if (text.EndsWith("\n") && text.Length > 1) { // SysConsole.Output(OutputType.CLIENTINFO, text.Substring(0, text.Length - 1)); } else { // SysConsole.Output(OutputType.CLIENTINFO, text); } int linestart = 0; int i = 0; for (i = 0; i < text.Length; i++) { if (text[i] == '\n') { linestart = i + 1; i++; continue; } if (Client.Central.FontSets.Standard.MeasureFancyText(text.Substring(linestart, i - linestart)) > MaxWidth) { i -= 1; for (int x = i; x > 0 && x > linestart + 5; x--) { if (text[x] == ' ') { i = x + 1; break; } } text = text.Substring(0, i) + "\n" + (i < text.Length ? text.Substring(i, text.Length - i) : ""); linestart = i + 1; i++; } } int lines = Utilities.CountCharacter(text, '\n'); if (lines > 0) { int linecount = 0; for (i = 0; i < ConsoleText.Length; i++) { if (ConsoleText[i] == '\n') { linecount++; if (linecount >= lines) { break; } } } ConsoleText = ConsoleText.Substring(i + 1, ConsoleText.Length - (i + 1)); } extralines += lines; if (extralines > 3) { extralines = 3; } LineBack = 3f; ConsoleText += text; } static bool keymark_add = false; static double keymark_delta = 0f; /// <summary> /// Whether the mouse was captured before the console was opened. /// </summary> public static bool MouseWasCaptured = false; /// <summary> /// Updates the console, called every tick. /// </summary> public static void Tick() { // Update open/close state if (KeyHandler._TogglerPressed) { KeyHandler.GetKBState(); Open = !Open; if (Open) { MouseWasCaptured = MouseHandler.MouseCaptured; MouseHandler.ReleaseMouse(); RecentSpot = RecentCommands.Count; } else { if (MouseWasCaptured) { MouseHandler.CaptureMouse(); } Typing = ""; TypingText = ""; TypingCursor = 0; } } if (Open) { KeyHandlerState KeyState = KeyHandler.GetKBState(); extralines = 0; LineBack = 0; // flicker the cursor keymark_delta += Client.Central.Delta; if (keymark_delta > 0.5f) { keymark_add = !keymark_add; keymark_delta = 0f; } // handle backspaces if (KeyState.InitBS > 0) { string partone = TypingCursor > 0 ? TypingText.Substring(0, TypingCursor) : ""; string parttwo = TypingCursor < TypingText.Length ? TypingText.Substring(TypingCursor) : ""; if (partone.Length > KeyState.InitBS) { partone = partone.Substring(0, partone.Length - KeyState.InitBS); TypingCursor -= KeyState.InitBS; } else { TypingCursor -= partone.Length; partone = ""; } TypingText = partone + parttwo; } // handle input text KeyState.KeyboardString = KeyState.KeyboardString.Replace("\t", " "); if (KeyState.KeyboardString.Length > 0) { if (TypingText.Length == TypingCursor) { TypingText += Utilities.CleanStringInput(KeyState.KeyboardString); } else { if (KeyState.KeyboardString.Contains('\n')) { string[] lines = KeyState.KeyboardString.SplitFast('\n', 1); TypingText = TypingText.Insert(TypingCursor, Utilities.CleanStringInput(lines[0])) + "\n" + Utilities.CleanStringInput(lines[1]); } else { TypingText = TypingText.Insert(TypingCursor, Utilities.CleanStringInput(KeyState.KeyboardString)); } } TypingCursor += KeyState.KeyboardString.Length; while (TypingText.Contains('\n')) { int index = TypingText.IndexOf('\n'); string input = TypingText.Substring(0, index); if (index + 1 < TypingText.Length) { TypingText = TypingText.Substring(index + 1); TypingCursor = TypingText.Length; } else { TypingText = ""; TypingCursor = 0; } WriteLine("] " + input); RecentCommands.Add(input); if (RecentCommands.Count > MaxRecentCommands) { RecentCommands.RemoveAt(0); } RecentSpot = RecentCommands.Count; Client.Central.Commands.ExecuteCommands(input); } } // handle copying if (KeyState.CopyPressed) { if (TypingText.Length > 0) { System.Windows.Forms.Clipboard.SetText(TypingText); } } // handle cursor left/right movement if (KeyState.LeftRights != 0) { TypingCursor += KeyState.LeftRights; if (TypingCursor < 0) { TypingCursor = 0; } if (TypingCursor > TypingText.Length) { TypingCursor = TypingText.Length; } keymark_add = true; keymark_delta = 0f; } // handle scrolling up/down in the console if (KeyState.Pages != 0) { ScrolledLine -= (int)(KeyState.Pages * ((float)Client.Central.Window.Height / 2 / Client.Central.FontSets.Standard.font_default.Height - 3)); } ScrolledLine -= MouseHandler.MouseScroll; if (ScrolledLine > 0) { ScrolledLine = 0; } if (ScrolledLine < -Lines + 5) { ScrolledLine = -Lines + 5; } // handle scrolling through commands if (KeyState.Scrolls != 0) { RecentSpot -= KeyState.Scrolls; if (RecentSpot < 0) { RecentSpot = 0; TypingText = RecentCommands[0]; } else if (RecentSpot >= RecentCommands.Count) { RecentSpot = RecentCommands.Count; TypingText = ""; } else { TypingText = RecentCommands[RecentSpot]; } TypingCursor = TypingText.Length; } // update the rendered text Typing = ">" + TypingText; } else // !Open { if (extralines > 0) { LineBack -= Client.Central.Delta; if (LineBack <= 0) { extralines--; LineBack = 3f; } } } } public static bool NoLinks = false; /// <summary> /// Renders the console, called every tick. /// </summary> public static void Draw() { // Render the console texture TypingLoc.Y = ((Client.Central.Window.Height / 2) - Client.Central.FontSets.Standard.font_default.Height) - 5; ConsoleTextLoc.Y = (-(Lines + 2) * Client.Central.FontSets.Standard.font_default.Height) - 5 - ScrolledLine * (int)Client.Central.FontSets.Standard.font_default.Height; ScrollTextLoc.Y = ((Client.Central.Window.Height / 2) - Client.Central.FontSets.Standard.font_default.Height * 2) - 5; if (Open) { ConsoleTextLoc.Y += Client.Central.Window.Height / 2; // Standard console box // GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); ConsoleTexture.Bind(); Client.Central.Rendering.SetColor(Color4.White); Client.Central.Rendering.RenderRectangle(0, 0, Client.Central.Window.Width, Client.Central.Window.Height / 2); // Scrollbar Client.Central.Textures.White.Bind(); Client.Central.Rendering.RenderRectangle(0, 0, 2, Client.Central.Window.Height / 2); Client.Central.Rendering.SetColor(Color4.Red); float Y = Client.Central.Window.Height / 2; float percentone = -(float)ScrolledLine / (float)Lines; float percenttwo = -((float)ScrolledLine - (float)Client.Central.Window.Height / Client.Central.FontSets.Standard.font_default.Height) / (float)Lines; Client.Central.Rendering.RenderRectangle(0, (int)(Y - Y * percenttwo), 2, (int)(Y - Y * percentone)); // Bottom line Client.Central.Textures.White.Bind(); Client.Central.Rendering.SetColor(Color4.Cyan); Client.Central.Rendering.RenderRectangle(0, (Client.Central.Window.Height / 2) - 1, Client.Central.Window.Width, Client.Central.Window.Height / 2); // Typing text string typed = Typing; int c = 0; if (!Client.Central.CVars.u_colortyping.ValueB) { for (int i = 0; i < typed.Length && i < TypingCursor; i++) { if (typed[i] == '^') { c++; } } typed = typed.Replace("^", "^^n"); } Client.Central.Rendering.SetColor(Color4.White); Client.Central.FontSets.Standard.DrawColoredText(typed, TypingLoc); // Cursor if (keymark_add) { double XAdd = Client.Central.FontSets.Standard.MeasureFancyText(typed.Substring(0, TypingCursor + 1 + c)) - 1; if (typed.Length > TypingCursor + 1 && typed[TypingCursor + c] == '^' && FontSet.IsColorSymbol(typed[TypingCursor + 1 + c])) { XAdd -= Client.Central.FontSets.Standard.font_default.MeasureString(typed[TypingCursor + c].ToString()); } Client.Central.FontSets.Standard.DrawColoredText("|", new Location(TypingLoc.X + XAdd, TypingLoc.Y, 0)); } // Render the console float maxy = Client.Central.Window.Height / 2 - Client.Central.FontSets.Standard.font_default.Height * 3; Client.Central.FontSets.Standard.DrawColoredText(ConsoleText, ConsoleTextLoc, (int)maxy); if (ScrolledLine != 0) { Client.Central.FontSets.Standard.DrawColoredText(ScrollText, ScrollTextLoc); } double sy = ConsoleTextLoc.Y; float sh = Client.Central.Fonts.Standard.Height; foreach (string str in ConsoleText.Split('\n')) { if (sy + sh > 0) { if (str.Contains("^[")) { List<KeyValuePair<string, Rectangle2F>> rects = new List<KeyValuePair<string, Rectangle2F>>(); Client.Central.FontSets.Standard.MeasureFancyText(str, out rects); foreach (KeyValuePair<string, Rectangle2F> rectent in rects) { rectent.Value.Y += (float)sy; if (MouseHandler.MouseX() >= rectent.Value.X && MouseHandler.MouseX() <= rectent.Value.X + rectent.Value.Width && MouseHandler.MouseY() >= rectent.Value.Y && MouseHandler.MouseY() <= rectent.Value.Y + rectent.Value.Height) { bool isUrl = (rectent.Key.StartsWith("url=http://") || rectent.Key.StartsWith("url=https://")); bool isHover = (rectent.Key.StartsWith("hover=")); bool clicked = Client.Central.Window.Focused && OpenTK.Input.Mouse.GetState().LeftButton == OpenTK.Input.ButtonState.Pressed; if (isUrl && clicked && !NoLinks) { System.Diagnostics.Process.Start(rectent.Key.Substring("url=".Length)); } NoLinks = clicked; string renderme; if (isUrl) { string url = rectent.Key.StartsWith("url=http://") ? rectent.Key.After("url=http://") : rectent.Key.After("url=https://"); renderme = "Click:URL<" + FontSet.EscapeFancyText(url) + ">"; } else if (isHover) { renderme = "<" + FontSet.EscapeFancyText(rectent.Key.Substring("hover=".Length).Replace("\\n", "\n")) + ">"; } else { continue; } Location lens = Client.Central.FontSets.Standard.MeasureFancyLinesOfText(renderme); float len = (float)lens.X; float hei = (float)lens.Y; float x = (rectent.Value.X + len > Client.Central.Window.Width) ? 0 : rectent.Value.X; float y = rectent.Value.Y + sh; Client.Central.Rendering.SetColor(Color4.Blue); Client.Central.Rendering.RenderRectangle(x, y, x + len + 5, y + 5 + hei); Client.Central.Rendering.SetColor(Color4.LightGray); Client.Central.Rendering.RenderRectangle(x + 1, y + 1, x + len + 4, y + 4 + hei); Client.Central.Rendering.SetColor(Color4.White); Client.Central.FontSets.Standard.DrawColoredText("^)" + renderme, new Location(x, y, 0)); } } } } sy += sh; if (sy > maxy) { break; } } } else { if (Client.Central.CVars.u_showhud.ValueB) { ConsoleTextLoc.Y += (int)(Client.Central.FontSets.Standard.font_default.Height * (2 + extralines)) + 4; Client.Central.FontSets.Standard.DrawColoredText(ConsoleText, ConsoleTextLoc, (int)(Client.Central.Window.Height / 2 - Client.Central.FontSets.Standard.font_default.Height * 3), 1, true); ConsoleTextLoc.Y -= (int)(Client.Central.FontSets.Standard.font_default.Height * (2 + extralines)) + 4; } } } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data.Objects.DataClasses; using System.Diagnostics; namespace ESRI.ArcLogistics.Data { /// <summary> /// Class that wraps data object collection and represents it sorted. It listens to the base collection for /// changes and updates itself accordingly. /// </summary> public class SortedDataObjectCollection<T> : IDataObjectCollection<T> where T : DataObject { #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <c>SortedDataObjectCollection</c> class. /// </summary> public SortedDataObjectCollection(IDataObjectCollection<T> coll, IComparer<T> comparer) { Debug.Assert(coll != null); Debug.Assert(comparer != null); _Init(coll, comparer); coll.CollectionChanged += new NotifyCollectionChangedEventHandler( _coll_CollectionChanged); _coll = coll; _comparer = comparer; } #endregion constructors #region INotifyCollectionChanged members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public event NotifyCollectionChangedEventHandler CollectionChanged; #endregion INotifyCollectionChanged members #region IDisposable interface members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Stops listening to the base collection for changes. /// </summary> public void Dispose() { if (_coll != null) { _coll.CollectionChanged -= new NotifyCollectionChangedEventHandler( _coll_CollectionChanged); } } #endregion IDisposable interface members #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public override string ToString() { return CollectionHelper.ToString(this as IList<T>); } /// <summary> /// Returns wrapped not sorted collection. /// </summary> public IDataObjectCollection<T> InternalCollection { get { return _coll; } } #endregion public methods #region IList<T> interface members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public T this[int index] { get { return (T)_sortedList[index]; } set { throw new InvalidOperationException(); } } public int Count { get { return _sortedList.Count; } } public void Add(T dataObject) { _coll.Add(dataObject); } public bool Remove(T dataObject) { return _coll.Remove(dataObject); } public void Clear() { _coll.Clear(); } public bool Contains(T dataObject) { if (dataObject == null) throw new ArgumentNullException(); return _sortedList.Contains(dataObject); } public void CopyTo(T[] dataObjectArray, int index) { _sortedList.CopyTo(dataObjectArray, index); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return _sortedList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _sortedList.GetEnumerator(); } public bool IsReadOnly { get { return _coll.IsReadOnly; } } public int IndexOf(T item) { return _sortedList.IndexOf(item); } public void Insert(int index, T item) { throw new InvalidOperationException(); } public void RemoveAt(int index) { if (index < 0 || index >= _sortedList.Count) throw new ArgumentException(); _coll.Remove(_sortedList[index]); } #endregion IList interface members #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private void _Init(IDataObjectCollection<T> coll, IComparer<T> comparer) { // fill collection _sortedList.AddRange(coll); // sort _sortedList.Sort(comparer); } private void _Reset() { _sortedList.Clear(); _Init(_coll, _comparer); } private void _coll_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: _OnAddItems(e.NewItems); break; case NotifyCollectionChangedAction.Remove: _OnRemoveItems(e.OldItems); break; case NotifyCollectionChangedAction.Reset: _OnResetItems(); break; } } private void _NotifyCollectionChanged(NotifyCollectionChangedEventArgs e) { if (CollectionChanged != null) CollectionChanged(this, e); } private void _OnAddItems(IList items) { foreach (object item in items) { int index = _InsertItem(item as T); _NotifyCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, item, index)); } } private void _OnRemoveItems(IList items) { foreach (object item in items) { //int index = _sortedList.BinarySearch(item as T, _comparer); int index = _sortedList.IndexOf(item as T); if (index >= 0) { Object obj = _sortedList[index]; _sortedList.RemoveAt(index); _NotifyCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, obj, index)); } } } private void _OnResetItems() { _Reset(); _NotifyCollectionChanged(new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset)); } private int _InsertItem(T item) { int index = _sortedList.BinarySearch(item, _comparer); if (index < 0) index = ~index; _sortedList.Insert(index, item); return index; } #endregion private methods #region private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private List<T> _sortedList = new List<T>(); private IDataObjectCollection<T> _coll; private IComparer<T> _comparer; #endregion private fields } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Its.Domain.Testing; using Microsoft.Its.Recipes; using NUnit.Framework; using Sample.Domain; using Sample.Domain.Ordering; using System; using System.Reactive.Disposables; using System.Threading.Tasks; namespace Microsoft.Its.Domain.Tests { [TestFixture] public abstract class ReservationServiceTests { private CompositeDisposable disposables; protected abstract void Configure(Configuration configuration, Action onSave = null); protected abstract IEventSourcedRepository<TAggregate> CreateRepository<TAggregate>( Action onSave = null) where TAggregate : class, IEventSourced; private IReservationService CreateReservationService() { return Configuration.Current.ReservationService; } private IReservationQuery CreateReservationQuery() { return Configuration.Current.ReservationQuery(); } [SetUp] public void SetUp() { // disable authorization checks Command<Order>.AuthorizeDefault = (order, command) => true; Command<CustomerAccount>.AuthorizeDefault = (account, command) => true; var configuration = new Configuration(); Configure(configuration); disposables = new CompositeDisposable { ConfigurationContext.Establish(configuration), configuration, VirtualClock.Start() }; } [TearDown] public virtual void TearDown() { disposables.Dispose(); } [Test] public void When_a_command_reserves_a_unique_value_then_a_subsequent_request_by_the_same_owner_succeeds() { // arrange var username = Any.CamelCaseName(5); // act var account1 = new CustomerAccount(); var principal = new Customer { Name = Any.CamelCaseName() }; account1.Apply(new RequestUserName { UserName = username, Principal = principal }); account1.ConfirmSave(); var account2 = new CustomerAccount(); var secondAttempt = account2.Validate(new RequestUserName { UserName = username, Principal = principal }); // assert secondAttempt.ShouldBeValid(); } [Test] public void When_a_command_reserves_a_unique_value_then_a_subsequent_request_by_a_different_owner_fails() { // arrange var username = Any.CamelCaseName(5); // act var account1 = new CustomerAccount(); account1.Apply(new RequestUserName { UserName = username, Principal = new Customer { Name = Any.CamelCaseName() } }); account1.ConfirmSave(); var account2 = new CustomerAccount(); var secondPrincipal = new Customer { Name = Any.CamelCaseName() }; var secondAttempt = account2.Validate(new RequestUserName { UserName = username, Principal = secondPrincipal }); // assert secondAttempt.ShouldBeInvalid(string.Format("The user name {0} is taken. Please choose another.", username)); } [Test] public async Task When_a_value_is_confirmed_then_it_can_be_re_reserved_using_the_same_owner_token_because_idempotency() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken); await reservationService.Confirm(value, scope, ownerToken); // act var succeeded = await reservationService.Reserve(value, scope, ownerToken); // assert succeeded.Should().BeTrue("because idempotency"); } [Test] public async Task When_a_value_is_confirmed_then_an_attempt_using_a_different_owner_token_to_reserve_it_again_throws() { // arrange var username = Any.Email(); var ownerToken = Any.Email(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(username, scope, ownerToken); await reservationService.Confirm(username, scope, ownerToken); // act var succeeded = await reservationService.Reserve(username, scope, ownerToken + "!"); // assert succeeded.Should().BeFalse(); } [Test] public async Task A_reservation_cannot_be_confirmed_using_the_wrong_owner_token() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken, TimeSpan.FromMinutes(5)); // act var wrongOwnerToken = Any.Guid(); var confirmed = reservationService.Confirm(value, scope, wrongOwnerToken.ToString()).Result; // assert confirmed.Should().BeFalse(); } [Test] public async Task When_Confirm_is_called_for_a_nonexistent_reservation_then_it_returns_false() { var reservationService = CreateReservationService(); var value = await reservationService.Confirm(Any.CamelCaseName(), Any.CamelCaseName(), Any.CamelCaseName()); value.Should().BeFalse(); } [Test] public async Task A_reservation_can_be_cancelled_using_its_owner_token() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken, TimeSpan.FromMinutes(5)); // act await reservationService.Cancel( value: value, scope: scope, ownerToken: ownerToken); // assert // check that someone else can now reserve the same value var succeeded = await reservationService.Reserve(value, scope, Any.Guid().ToString(), TimeSpan.FromMinutes(5)); succeeded.Should().BeTrue(); } [Test] public async Task An_attempt_to_cancel_a_reservation_without_the_correct_owner_token_fails() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken, TimeSpan.FromMinutes(5)); // act var wrongOwnerToken = Any.Guid().ToString(); var cancelled = reservationService.Cancel(value, scope, wrongOwnerToken).Result; // assert cancelled.Should().BeFalse(); } [Test] public async Task If_a_fixed_quantity_of_resource_had_been_depleted_then_reservations_cant_be_made() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource where the resource has been used var ownerToken = Any.Guid().ToString(); var promoCode = "promo-code-" + Any.Guid(); var reservedValue = Any.Guid().ToString(); var userConfirmationCode = Any.Guid().ToString(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); //act var result = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(-2), confirmationToken: userConfirmationCode); result.Should().Be(reservedValue); await reservationService.Confirm(userConfirmationCode, promoCode, ownerToken); //assert result = await reservationService.ReserveAny( scope: promoCode, ownerToken: Any.FullName(), lease: TimeSpan.FromMinutes(2), confirmationToken: Any.Guid().ToString()); result.Should().BeNull(); } [Test] public async Task Confirmation_token_cant_be_used_twice_by_different_owners_for_the_same_resource() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource where the resource has been used var word = Any.Word(); var ownerToken = Any.Guid().ToString(); var promoCode = "promo-code-" + word; var reservedValue = Any.Guid().ToString(); var confirmationToken = Any.Guid().ToString(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); await reservationService.Reserve(Any.Guid().ToString(), promoCode, reservedValue, TimeSpan.FromDays(-1)); //act await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, confirmationToken: confirmationToken); //assert var result = await reservationService.ReserveAny( scope: promoCode, ownerToken: Any.FullName(), lease: TimeSpan.FromMinutes(2), confirmationToken: confirmationToken); result.Should().BeNull(); } [Test] public async Task When_confirmation_token_is_used_twice_for_the_same_unconfirmed_reservation_then_ReserveAny_extends_the_lease() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource where the resource has been used //todo:(this needs to be done via an interface rather then just calling reserve multiple times) var word = Any.Word(); var ownerToken = Any.Guid().ToString(); var promoCode = "promo-code-" + word; var reservedValue = Any.Guid().ToString(); var confirmationToken = Any.Guid().ToString(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); await reservationService.Reserve(Any.Guid().ToString(), promoCode, reservedValue, TimeSpan.FromDays(-1)); //act var firstAttempt = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, confirmationToken: confirmationToken); //assert var secondAttempt = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(2), confirmationToken: confirmationToken); secondAttempt.Should() .NotBeNull() .And .Be(firstAttempt); } [Test] public async Task When_ReserveAny_is_called_for_a_scope_that_has_no_entries_at_all_then_it_returns_false() { var reservationService = CreateReservationService(); var value = await reservationService.ReserveAny(Any.CamelCaseName(), Any.CamelCaseName(), TimeSpan.FromMinutes(1)); value.Should().BeNull(); } [Test] public async Task When_a_command_reserves_a_unique_value_but_it_expires_then_a_subsequent_request_by_a_different_actor_succeeds() { // arrange var username = Any.CamelCaseName(5); var scope = "UserName"; await CreateReservationService().Reserve(username, scope, Any.CamelCaseName(), TimeSpan.FromMinutes(30)); // act VirtualClock.Current.AdvanceBy(TimeSpan.FromMinutes(32)); var attempt = new CustomerAccount() .Validate(new RequestUserName { UserName = username, Principal = new Customer { Name = Any.CamelCaseName() } }); // assert attempt.ShouldBeValid(); var reservation = await CreateReservationQuery().GetReservedValue(username, scope); reservation.Expiration.Should().Be(Clock.Now().AddMinutes(1)); } [Test] public async Task Reservations_can_be_placed_for_one_of_a_fixed_quantity_of_a_resource() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource, e.g. promo codes: var ownerToken = "ownerToken-" + Any.Guid(); var promoCode = "promo-code-" + Any.Guid(); var reservedValue = "reservedValue-" + Any.Guid(); var confirmationToken = "userConfirmationCode-" + Any.Guid(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); //act var result = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(2), confirmationToken: confirmationToken); result.Should().Be(reservedValue); await reservationService.Confirm(confirmationToken, promoCode, ownerToken); // assert var reservation = await CreateReservationQuery().GetReservedValue(reservedValue, promoCode); reservation.Expiration.Should().BeNull(); } [Test] public async Task The_value_returned_by_the_reservation_service_can_be_used_for_confirmation() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource, e.g. promo codes: var ownerToken = "owner-token-" + Any.Email(); var promoCode = "promo-code-" + Any.Guid(); var reservedValue = Any.Email(); await reservationService.Reserve(reservedValue, scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromDays(-1)); //act var value = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(2)); value.Should().NotBeNull(); await reservationService.Confirm(value, promoCode, ownerToken); // assert var reservation = await CreateReservationQuery().GetReservedValue(reservedValue, promoCode); reservation.Expiration.Should().BeNull(); reservation.ConfirmationToken.Should().Be(value); } [Test] public async Task When_the_aggregate_is_saved_then_the_reservation_is_confirmed() { // arrange var username = Any.Email(); var account = new CustomerAccount(); account.Apply(new RequestUserName { UserName = username, Principal = new Customer(username) }); Configuration.Current.EventBus.Subscribe(new UserNameConfirmer()); var repository = CreateRepository<CustomerAccount>(); // act await repository.Save(account); // assert var reservation = await CreateReservationQuery().GetReservedValue(username, "UserName"); reservation.Expiration.Should().BeNull(); } } public class UserNameConfirmer : IHaveConsequencesWhen<CustomerAccount.UserNameAcquired> { public void HaveConsequences(CustomerAccount.UserNameAcquired @event) { Configuration.Current.ReservationService.Confirm( @event.UserName, "UserName", @event.UserName).Wait(); } } }
using System; using System.Collections; using System.Globalization; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Pkix { internal class Rfc3281CertPathUtilities { internal static void ProcessAttrCert7( IX509AttributeCertificate attrCert, PkixCertPath certPath, PkixCertPath holderCertPath, PkixParameters pkixParams) { // TODO: // AA Controls // Attribute encryption // Proxy ISet critExtOids = attrCert.GetCriticalExtensionOids(); // 7.1 // process extensions // target information checked in step 6 / X509AttributeCertStoreSelector if (critExtOids.Contains(X509Extensions.TargetInformation.Id)) { try { TargetInformation.GetInstance(PkixCertPathValidatorUtilities .GetExtensionValue(attrCert, X509Extensions.TargetInformation)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Target information extension could not be read.", e); } } critExtOids.Remove(X509Extensions.TargetInformation.Id); foreach (PkixAttrCertChecker checker in pkixParams.GetAttrCertCheckers()) { checker.Check(attrCert, certPath, holderCertPath, critExtOids); } if (!critExtOids.IsEmpty) { throw new PkixCertPathValidatorException( "Attribute certificate contains unsupported critical extensions: " + critExtOids); } } /** * Checks if an attribute certificate is revoked. * * @param attrCert Attribute certificate to check if it is revoked. * @param paramsPKIX PKIX parameters. * @param issuerCert The issuer certificate of the attribute certificate * <code>attrCert</code>. * @param validDate The date when the certificate revocation status should * be checked. * @param certPathCerts The certificates of the certification path to be * checked. * * @throws CertPathValidatorException if the certificate is revoked or the * status cannot be checked or some error occurs. */ internal static void CheckCrls( IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, X509Certificate issuerCert, DateTime validDate, IList certPathCerts) { if (paramsPKIX.IsRevocationEnabled) { // check if revocation is available if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) == null) { CrlDistPoint crldp = null; try { crldp = CrlDistPoint.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue( attrCert, X509Extensions.CrlDistributionPoints)); } catch (Exception e) { throw new PkixCertPathValidatorException( "CRL distribution point extension could not be read.", e); } try { PkixCertPathValidatorUtilities .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX); } catch (Exception e) { throw new PkixCertPathValidatorException( "No additional CRL locations could be decoded from CRL distribution point extension.", e); } CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); Exception lastException = null; bool validCrlFound = false; // for each distribution point if (crldp != null) { DistributionPoint[] dps = null; try { dps = crldp.GetDistributionPoints(); } catch (Exception e) { throw new PkixCertPathValidatorException( "Distribution points could not be read.", e); } try { for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++) { PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX .Clone(); CheckCrl(dps[i], attrCert, paramsPKIXClone, validDate, issuerCert, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } } catch (Exception e) { lastException = new Exception( "No valid CRL for distribution point found.", e); } } /* * If the revocation status has not been determined, repeat the * process above with any available CRLs not specified in a * distribution point but issued by the certificate issuer. */ if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons) { try { /* * assume a DP with both the reasons and the cRLIssuer * fields omitted and a distribution point name of the * certificate issuer. */ Asn1Object issuer = null; try { issuer = new Asn1InputStream( attrCert.Issuer.GetPrincipals()[0].GetEncoded()).ReadObject(); } catch (Exception e) { throw new Exception( "Issuer from certificate for CRL could not be reencoded.", e); } DistributionPoint dp = new DistributionPoint( new DistributionPointName(0, new GeneralNames( new GeneralName(GeneralName.DirectoryName, issuer))), null, null); PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX.Clone(); CheckCrl(dp, attrCert, paramsPKIXClone, validDate, issuerCert, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) { lastException = new Exception( "No valid CRL for distribution point found.", e); } } if (!validCrlFound) { throw new PkixCertPathValidatorException( "No valid CRL found.", lastException); } if (certStatus.Status != CertStatus.Unrevoked) { // TODO This format is forced by the NistCertPath tests string formattedDate = certStatus.RevocationDate.Value.ToString( "G", new CultureInfo("en-us")); string message = "Attribute certificate revocation after " + formattedDate; message += ", reason: " + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status]; throw new PkixCertPathValidatorException(message); } if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked) { certStatus.Status = CertStatus.Undetermined; } if (certStatus.Status == CertStatus.Undetermined) { throw new PkixCertPathValidatorException( "Attribute certificate status could not be determined."); } } else { if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null) { throw new PkixCertPathValidatorException( "No rev avail extension is set, but also an AC revocation pointer."); } } } } internal static void AdditionalChecks( IX509AttributeCertificate attrCert, PkixParameters pkixParams) { // 1 foreach (string oid in pkixParams.GetProhibitedACAttributes()) { if (attrCert.GetAttributes(oid) != null) { throw new PkixCertPathValidatorException( "Attribute certificate contains prohibited attribute: " + oid + "."); } } foreach (string oid in pkixParams.GetNecessaryACAttributes()) { if (attrCert.GetAttributes(oid) == null) { throw new PkixCertPathValidatorException( "Attribute certificate does not contain necessary attribute: " + oid + "."); } } } internal static void ProcessAttrCert5( IX509AttributeCertificate attrCert, PkixParameters pkixParams) { try { attrCert.CheckValidity(PkixCertPathValidatorUtilities.GetValidDate(pkixParams)); } catch (CertificateExpiredException e) { throw new PkixCertPathValidatorException( "Attribute certificate is not valid.", e); } catch (CertificateNotYetValidException e) { throw new PkixCertPathValidatorException( "Attribute certificate is not valid.", e); } } internal static void ProcessAttrCert4( X509Certificate acIssuerCert, PkixParameters pkixParams) { ISet set = pkixParams.GetTrustedACIssuers(); bool trusted = false; foreach (TrustAnchor anchor in set) { IDictionary symbols = X509Name.RFC2253Symbols; if (acIssuerCert.SubjectDN.ToString(false, symbols).Equals(anchor.CAName) || acIssuerCert.Equals(anchor.TrustedCert)) { trusted = true; } } if (!trusted) { throw new PkixCertPathValidatorException( "Attribute certificate issuer is not directly trusted."); } } internal static void ProcessAttrCert3( X509Certificate acIssuerCert, PkixParameters pkixParams) { if (acIssuerCert.GetKeyUsage() != null && (!acIssuerCert.GetKeyUsage()[0] && !acIssuerCert.GetKeyUsage()[1])) { throw new PkixCertPathValidatorException( "Attribute certificate issuer public key cannot be used to validate digital signatures."); } if (acIssuerCert.GetBasicConstraints() != -1) { throw new PkixCertPathValidatorException( "Attribute certificate issuer is also a public key certificate issuer."); } } internal static PkixCertPathValidatorResult ProcessAttrCert2( PkixCertPath certPath, PkixParameters pkixParams) { PkixCertPathValidator validator = new PkixCertPathValidator(); try { return validator.Validate(certPath, pkixParams); } catch (PkixCertPathValidatorException e) { throw new PkixCertPathValidatorException( "Certification path for issuer certificate of attribute certificate could not be validated.", e); } } /** * Searches for a holder public key certificate and verifies its * certification path. * * @param attrCert the attribute certificate. * @param pkixParams The PKIX parameters. * @return The certificate path of the holder certificate. * @throws Exception if * <ul> * <li>no public key certificate can be found although holder * information is given by an entity name or a base certificate * ID</li> * <li>support classes cannot be created</li> * <li>no certification path for the public key certificate can * be built</li> * </ul> */ internal static PkixCertPath ProcessAttrCert1( IX509AttributeCertificate attrCert, PkixParameters pkixParams) { PkixCertPathBuilderResult result = null; // find holder PKCs ISet holderPKCs = new HashSet(); if (attrCert.Holder.GetIssuer() != null) { X509CertStoreSelector selector = new X509CertStoreSelector(); selector.SerialNumber = attrCert.Holder.SerialNumber; X509Name[] principals = attrCert.Holder.GetIssuer(); for (int i = 0; i < principals.Length; i++) { try { // if (principals[i] is X500Principal) { selector.Issuer = principals[i]; } holderPKCs.AddAll(PkixCertPathValidatorUtilities .FindCertificates(selector, pkixParams.GetStores())); } catch (Exception e) { throw new PkixCertPathValidatorException( "Public key certificate for attribute certificate cannot be searched.", e); } } if (holderPKCs.IsEmpty) { throw new PkixCertPathValidatorException( "Public key certificate specified in base certificate ID for attribute certificate cannot be found."); } } if (attrCert.Holder.GetEntityNames() != null) { X509CertStoreSelector selector = new X509CertStoreSelector(); X509Name[] principals = attrCert.Holder.GetEntityNames(); for (int i = 0; i < principals.Length; i++) { try { // if (principals[i] is X500Principal) { selector.Issuer = principals[i]; } holderPKCs.AddAll(PkixCertPathValidatorUtilities .FindCertificates(selector, pkixParams.GetStores())); } catch (Exception e) { throw new PkixCertPathValidatorException( "Public key certificate for attribute certificate cannot be searched.", e); } } if (holderPKCs.IsEmpty) { throw new PkixCertPathValidatorException( "Public key certificate specified in entity name for attribute certificate cannot be found."); } } // verify cert paths for PKCs PkixBuilderParameters parameters = (PkixBuilderParameters) PkixBuilderParameters.GetInstance(pkixParams); PkixCertPathValidatorException lastException = null; foreach (X509Certificate cert in holderPKCs) { X509CertStoreSelector selector = new X509CertStoreSelector(); selector.Certificate = cert; parameters.SetTargetConstraints(selector); PkixCertPathBuilder builder = new PkixCertPathBuilder(); try { result = builder.Build(PkixBuilderParameters.GetInstance(parameters)); } catch (PkixCertPathBuilderException e) { lastException = new PkixCertPathValidatorException( "Certification path for public key certificate of attribute certificate could not be build.", e); } } if (lastException != null) { throw lastException; } return result.CertPath; } /** * * Checks a distribution point for revocation information for the * certificate <code>attrCert</code>. * * @param dp The distribution point to consider. * @param attrCert The attribute certificate which should be checked. * @param paramsPKIX PKIX parameters. * @param validDate The date when the certificate revocation status should * be checked. * @param issuerCert Certificate to check if it is revoked. * @param reasonMask The reasons mask which is already checked. * @param certPathCerts The certificates of the certification path to be * checked. * @throws Exception if the certificate is revoked or the status * cannot be checked or some error occurs. */ private static void CheckCrl( DistributionPoint dp, IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, DateTime validDate, X509Certificate issuerCert, CertStatus certStatus, ReasonsMask reasonMask, IList certPathCerts) { /* * 4.3.6 No Revocation Available * * The noRevAvail extension, defined in [X.509-2000], allows an AC * issuer to indicate that no revocation information will be made * available for this AC. */ if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null) { return; } DateTime currentDate = DateTime.UtcNow; if (validDate.CompareTo(currentDate) > 0) { throw new Exception("Validation time is in future."); } // (a) /* * We always get timely valid CRLs, so there is no step (a) (1). * "locally cached" CRLs are assumed to be in getStore(), additional * CRLs must be enabled in the ExtendedPkixParameters and are in * getAdditionalStore() */ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; IEnumerator crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons) { try { X509Crl crl = (X509Crl) crl_iter.Current; // (d) ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); // (e) /* * The reasons mask is updated at the end, so only valid CRLs * can update it. If this CRL does not contain new reasons it * must be ignored. */ if (!interimReasonsMask.HasNewReasons(reasonMask)) { continue; } // (f) ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert, null, null, paramsPKIX, certPathCerts); // (g) AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); X509Crl deltaCRL = null; if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls( currentDate, paramsPKIX, crl); // we only want one valid delta CRL // (h) deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey); } /* * CRL must be be valid at the current time, not the validation * time. If a certificate is revoked with reason keyCompromise, * cACompromise, it can be used for forgery, also for the past. * This reason may not be contained in older CRLs. */ /* * in the chain model signatures stay valid also after the * certificate has been expired, so they do not have to be in * the CRL vality time */ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel) { /* * if a certificate has expired, but was revoked, it is not * more in the CRL, so it would be regarded as valid if the * first check is not done */ if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0) { throw new Exception( "No valid CRL for current time found."); } } Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl); // (b) (2) Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, crl); // (c) Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX); // (i) Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, attrCert, certStatus, paramsPKIX); // (j) Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, attrCert, certStatus); // (k) if (certStatus.Status == CrlReason.RemoveFromCrl) { certStatus.Status = CertStatus.Unrevoked; } // update reasons mask reasonMask.AddReasons(interimReasonsMask); validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="KeywordThemeConstantServiceClient"/> instances.</summary> public sealed partial class KeywordThemeConstantServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="KeywordThemeConstantServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="KeywordThemeConstantServiceSettings"/>.</returns> public static KeywordThemeConstantServiceSettings GetDefault() => new KeywordThemeConstantServiceSettings(); /// <summary> /// Constructs a new <see cref="KeywordThemeConstantServiceSettings"/> object with default settings. /// </summary> public KeywordThemeConstantServiceSettings() { } private KeywordThemeConstantServiceSettings(KeywordThemeConstantServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetKeywordThemeConstantSettings = existing.GetKeywordThemeConstantSettings; SuggestKeywordThemeConstantsSettings = existing.SuggestKeywordThemeConstantsSettings; OnCopy(existing); } partial void OnCopy(KeywordThemeConstantServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordThemeConstantServiceClient.GetKeywordThemeConstant</c> and /// <c>KeywordThemeConstantServiceClient.GetKeywordThemeConstantAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetKeywordThemeConstantSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>KeywordThemeConstantServiceClient.SuggestKeywordThemeConstants</c> and /// <c>KeywordThemeConstantServiceClient.SuggestKeywordThemeConstantsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings SuggestKeywordThemeConstantsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="KeywordThemeConstantServiceSettings"/> object.</returns> public KeywordThemeConstantServiceSettings Clone() => new KeywordThemeConstantServiceSettings(this); } /// <summary> /// Builder class for <see cref="KeywordThemeConstantServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class KeywordThemeConstantServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordThemeConstantServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public KeywordThemeConstantServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public KeywordThemeConstantServiceClientBuilder() { UseJwtAccessWithScopes = KeywordThemeConstantServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref KeywordThemeConstantServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordThemeConstantServiceClient> task); /// <summary>Builds the resulting client.</summary> public override KeywordThemeConstantServiceClient Build() { KeywordThemeConstantServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<KeywordThemeConstantServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<KeywordThemeConstantServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private KeywordThemeConstantServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return KeywordThemeConstantServiceClient.Create(callInvoker, Settings); } private async stt::Task<KeywordThemeConstantServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return KeywordThemeConstantServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => KeywordThemeConstantServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordThemeConstantServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordThemeConstantServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>KeywordThemeConstantService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch Smart Campaign keyword themes. /// </remarks> public abstract partial class KeywordThemeConstantServiceClient { /// <summary> /// The default endpoint for the KeywordThemeConstantService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default KeywordThemeConstantService scopes.</summary> /// <remarks> /// The default KeywordThemeConstantService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="KeywordThemeConstantServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordThemeConstantServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="KeywordThemeConstantServiceClient"/>.</returns> public static stt::Task<KeywordThemeConstantServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new KeywordThemeConstantServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="KeywordThemeConstantServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="KeywordThemeConstantServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="KeywordThemeConstantServiceClient"/>.</returns> public static KeywordThemeConstantServiceClient Create() => new KeywordThemeConstantServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="KeywordThemeConstantServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="KeywordThemeConstantServiceSettings"/>.</param> /// <returns>The created <see cref="KeywordThemeConstantServiceClient"/>.</returns> internal static KeywordThemeConstantServiceClient Create(grpccore::CallInvoker callInvoker, KeywordThemeConstantServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } KeywordThemeConstantService.KeywordThemeConstantServiceClient grpcClient = new KeywordThemeConstantService.KeywordThemeConstantServiceClient(callInvoker); return new KeywordThemeConstantServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC KeywordThemeConstantService client</summary> public virtual KeywordThemeConstantService.KeywordThemeConstantServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordThemeConstant GetKeywordThemeConstant(GetKeywordThemeConstantRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(GetKeywordThemeConstantRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(GetKeywordThemeConstantRequest request, st::CancellationToken cancellationToken) => GetKeywordThemeConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the keyword theme constant to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordThemeConstant GetKeywordThemeConstant(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordThemeConstant(new GetKeywordThemeConstantRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the keyword theme constant to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordThemeConstantAsync(new GetKeywordThemeConstantRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the keyword theme constant to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(string resourceName, st::CancellationToken cancellationToken) => GetKeywordThemeConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the keyword theme constant to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::KeywordThemeConstant GetKeywordThemeConstant(gagvr::KeywordThemeConstantName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordThemeConstant(new GetKeywordThemeConstantRequest { ResourceNameAsKeywordThemeConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the keyword theme constant to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(gagvr::KeywordThemeConstantName resourceName, gaxgrpc::CallSettings callSettings = null) => GetKeywordThemeConstantAsync(new GetKeywordThemeConstantRequest { ResourceNameAsKeywordThemeConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the keyword theme constant to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(gagvr::KeywordThemeConstantName resourceName, st::CancellationToken cancellationToken) => GetKeywordThemeConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns KeywordThemeConstant suggestions by keyword themes. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual SuggestKeywordThemeConstantsResponse SuggestKeywordThemeConstants(SuggestKeywordThemeConstantsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns KeywordThemeConstant suggestions by keyword themes. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SuggestKeywordThemeConstantsResponse> SuggestKeywordThemeConstantsAsync(SuggestKeywordThemeConstantsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns KeywordThemeConstant suggestions by keyword themes. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<SuggestKeywordThemeConstantsResponse> SuggestKeywordThemeConstantsAsync(SuggestKeywordThemeConstantsRequest request, st::CancellationToken cancellationToken) => SuggestKeywordThemeConstantsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>KeywordThemeConstantService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch Smart Campaign keyword themes. /// </remarks> public sealed partial class KeywordThemeConstantServiceClientImpl : KeywordThemeConstantServiceClient { private readonly gaxgrpc::ApiCall<GetKeywordThemeConstantRequest, gagvr::KeywordThemeConstant> _callGetKeywordThemeConstant; private readonly gaxgrpc::ApiCall<SuggestKeywordThemeConstantsRequest, SuggestKeywordThemeConstantsResponse> _callSuggestKeywordThemeConstants; /// <summary> /// Constructs a client wrapper for the KeywordThemeConstantService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="KeywordThemeConstantServiceSettings"/> used within this client. /// </param> public KeywordThemeConstantServiceClientImpl(KeywordThemeConstantService.KeywordThemeConstantServiceClient grpcClient, KeywordThemeConstantServiceSettings settings) { GrpcClient = grpcClient; KeywordThemeConstantServiceSettings effectiveSettings = settings ?? KeywordThemeConstantServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetKeywordThemeConstant = clientHelper.BuildApiCall<GetKeywordThemeConstantRequest, gagvr::KeywordThemeConstant>(grpcClient.GetKeywordThemeConstantAsync, grpcClient.GetKeywordThemeConstant, effectiveSettings.GetKeywordThemeConstantSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetKeywordThemeConstant); Modify_GetKeywordThemeConstantApiCall(ref _callGetKeywordThemeConstant); _callSuggestKeywordThemeConstants = clientHelper.BuildApiCall<SuggestKeywordThemeConstantsRequest, SuggestKeywordThemeConstantsResponse>(grpcClient.SuggestKeywordThemeConstantsAsync, grpcClient.SuggestKeywordThemeConstants, effectiveSettings.SuggestKeywordThemeConstantsSettings); Modify_ApiCall(ref _callSuggestKeywordThemeConstants); Modify_SuggestKeywordThemeConstantsApiCall(ref _callSuggestKeywordThemeConstants); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetKeywordThemeConstantApiCall(ref gaxgrpc::ApiCall<GetKeywordThemeConstantRequest, gagvr::KeywordThemeConstant> call); partial void Modify_SuggestKeywordThemeConstantsApiCall(ref gaxgrpc::ApiCall<SuggestKeywordThemeConstantsRequest, SuggestKeywordThemeConstantsResponse> call); partial void OnConstruction(KeywordThemeConstantService.KeywordThemeConstantServiceClient grpcClient, KeywordThemeConstantServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC KeywordThemeConstantService client</summary> public override KeywordThemeConstantService.KeywordThemeConstantServiceClient GrpcClient { get; } partial void Modify_GetKeywordThemeConstantRequest(ref GetKeywordThemeConstantRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_SuggestKeywordThemeConstantsRequest(ref SuggestKeywordThemeConstantsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::KeywordThemeConstant GetKeywordThemeConstant(GetKeywordThemeConstantRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordThemeConstantRequest(ref request, ref callSettings); return _callGetKeywordThemeConstant.Sync(request, callSettings); } /// <summary> /// Returns the requested keyword theme constant in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::KeywordThemeConstant> GetKeywordThemeConstantAsync(GetKeywordThemeConstantRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetKeywordThemeConstantRequest(ref request, ref callSettings); return _callGetKeywordThemeConstant.Async(request, callSettings); } /// <summary> /// Returns KeywordThemeConstant suggestions by keyword themes. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override SuggestKeywordThemeConstantsResponse SuggestKeywordThemeConstants(SuggestKeywordThemeConstantsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SuggestKeywordThemeConstantsRequest(ref request, ref callSettings); return _callSuggestKeywordThemeConstants.Sync(request, callSettings); } /// <summary> /// Returns KeywordThemeConstant suggestions by keyword themes. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<SuggestKeywordThemeConstantsResponse> SuggestKeywordThemeConstantsAsync(SuggestKeywordThemeConstantsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SuggestKeywordThemeConstantsRequest(ref request, ref callSettings); return _callSuggestKeywordThemeConstants.Async(request, callSettings); } } }
using System; using System.ComponentModel; using TreeGecko.Library.Geospatial.Geoframeworks.Enums; namespace TreeGecko.Library.Geospatial.Geoframeworks.Objects { /// <summary> /// Represents a collection of interpolated values using realistic acceleration and deceleration. /// </summary> /// <remarks>This enumeration is used by several GeoFramework controls to smoothly transition from /// one value to another. For example, the GPS SatelliteViewer uses acceleration to smoothly /// transition from one bearing to another, giving the appearance of a realistic compass. This /// enumeration, when combined with the <see cref="Interpolator"></see> class lets you add smooth /// transitions to your own controls as well.</remarks> /// <summary>Calculates intermediate values between two bounding values.</summary> /// <remarks> /// This powerful class provides the ability to interpolate values based on varying /// interpolation techniques. This class is used primarily to simulate realistic motion by /// accelerating and decelerating. This class is also used to calculate intermediate values /// for features such as image georeferencing and estimating precision errors. /// </remarks> [TypeConverter(typeof(ExpandableObjectConverter))] public sealed class Interpolator { private int _Count; private double _Minimum; private double _Maximum; private InterpolationMethod _InterpolationMethod; private double[] _Values; private readonly object SyncRoot = new object(); public Interpolator() { lock (SyncRoot) { _Count = 10; _InterpolationMethod = InterpolationMethod.Linear; Recalculate(); } } public Interpolator(int count, InterpolationMethod mode) { lock (SyncRoot) { _Count = count; _InterpolationMethod = mode; Recalculate(); } } public Interpolator(double minimum, double maximum, int count) { lock (SyncRoot) { _Minimum = minimum; _Maximum = maximum; _Count = count; Recalculate(); } } public Interpolator(double minimum, double maximum, int count, InterpolationMethod mode) { lock (SyncRoot) { _Minimum = minimum; _Maximum = maximum; _Count = count; _InterpolationMethod = mode; Recalculate(); } } /// <summary>Controls the smallest number in the sequence.</summary> public double Minimum { get { return _Minimum; } set { lock (SyncRoot) { if (_Minimum == value) return; _Minimum = value; Recalculate(); } } } /// <summary>Controls the largest number in the sequence.</summary> public double Maximum { get { return _Maximum; } set { lock (SyncRoot) { if (_Maximum == value) return; _Maximum = value; Recalculate(); } } } /// <summary>Controls the acceleration and/or deceleration technique used.</summary> public InterpolationMethod InterpolationMethod { get { return _InterpolationMethod; } set { lock (SyncRoot) { if (_InterpolationMethod == value) return; _InterpolationMethod = value; Recalculate(); } } } /// <summary>Controls the number of interpolated values.</summary> public int Count { get { return _Count; } set { lock (SyncRoot) { if (_Count == value) return; _Count = value; // Recalculate the array Recalculate(); } } } /// <summary>Reverses the interpolated sequence.</summary> public void Swap() { lock (SyncRoot) { double Temp = _Minimum; _Minimum = _Maximum; _Maximum = Temp; Recalculate(); } } /// <summary>Returns a number from the interpolated sequence.</summary> public double this[int index] { get { //lock(SyncRoot) { if (index > Count - 1) return _Values[Count - 1]; else if (index < 0) return _Values[0]; else return _Values[index]; } } } // Recalculates all values according to the specified mode private void Recalculate() { // Recalculate the entire array _Values = new double[_Count]; if (_Count == 1) { // If min != max should probably be an error. _Values[0] = _Maximum; } else { for (int i = 0; i < _Count; i++) { _Values[i] = CalculateValue(i); } } } private double CalculateValue(double index) { // The count needs to be zero based, like the index (or we need to calc +1 values to get both poles). int zeroCount = _Count - 1; //adjust formula to selected algoritm from combobox switch (this.InterpolationMethod) { case InterpolationMethod.Snap: return _Maximum; case InterpolationMethod.Linear: // Simple linear values - no acceleration or deceleration return ((_Maximum - _Minimum)*index/zeroCount + _Minimum); case InterpolationMethod.QuadraticEaseIn: // Quadratic (Time ^ 2) easing in - accelerating from zero velocity return ((_Maximum - _Minimum)*(index /= zeroCount)*index + _Minimum); case InterpolationMethod.QuadraticEaseOut: // Quadratic (Index^2) easing out - decelerating to zero velocity return (-(_Maximum - _Minimum)*(index = index/zeroCount)*(index - 2) + _Minimum); case InterpolationMethod.QuadraticEaseInAndOut: // Quadratic easing in/out - acceleration until halfway, then deceleration if ((index /= zeroCount*0.5) < 1) { return ((_Maximum - _Minimum)*0.5*index*index + _Minimum); } else { return (-(_Maximum - _Minimum)*0.5*((--index)*(index - 2) - 1) + _Minimum); } case InterpolationMethod.CubicEaseIn: // Cubic easing in - accelerating from zero velocity return ((_Maximum - _Minimum)*(index /= zeroCount)*index*index + _Minimum); case InterpolationMethod.CubicEaseOut: // Cubic easing in - accelerating from zero velocity return ((_Maximum - _Minimum)*((index = index/zeroCount - 1)*index*index + 1) + _Minimum); case InterpolationMethod.CubicEaseInOut: // Cubic easing in - accelerating from zero velocity if ((index /= zeroCount*0.5) < 1) { return ((_Maximum - _Minimum)*0.5*index*index*index + _Minimum); } else { return ((_Maximum - _Minimum)*0.5*((index -= 2)*index*index + 2) + _Minimum); } case InterpolationMethod.QuarticEaseIn: // Quartic easing in - accelerating from zero velocity return ((_Maximum - _Minimum)*(index /= zeroCount)*index*index*index + _Minimum); case InterpolationMethod.ExponentialEaseIn: // Exponential (2^Index) easing in - accelerating from zero velocity if (index == 0) { return _Minimum; } else { return ((_Maximum - _Minimum)*Math.Pow(2, (10*(index/zeroCount - 1))) + _Minimum); } case InterpolationMethod.ExponentialEaseOut: // exponential (2^Index) easing out - decelerating to zero velocity if (index == zeroCount) { return (_Minimum + (_Maximum - _Minimum)); } else { return ((_Maximum - _Minimum)*(-Math.Pow(2, -10*index/zeroCount) + 1) + _Minimum); } default: return 0; } } } }
// ReSharper disable UnusedMember.Global Used in HappyPathWithAll.PropertyChangedAnalyzersSln // ReSharper disable NotAccessedField.Local // ReSharper disable UnusedVariable // ReSharper disable UnusedParameter.Local // ReSharper disable RedundantAssignment // ReSharper disable ArrangeAccessorOwnerBody // ReSharper disable FunctionRecursiveOnAllPaths // ReSharper disable UnusedParameter.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable ArrangeThisQualifier // ReSharper disable PossibleUnintendedReferenceComparison // ReSharper disable RedundantCheckBeforeAssignment // ReSharper disable UnusedMethodReturnValue.Global #pragma warning disable 1717 #pragma warning disable SA1101 // Prefix local calls with this #pragma warning disable GU0011 // Don't ignore the return value. #pragma warning disable GU0010 // Assigning same value. #pragma warning disable IDE0009 // Member access should be qualified. #pragma warning disable IDE0025 namespace ValidCode { using System; using System.Collections.Generic; internal class RecursiveFoo { private IDisposable bar1; private IDisposable bar2; public RecursiveFoo() { #pragma warning disable GU0015 // Don't assign same more than once. var value = this.RecursiveExpressionBodyProperty; value = this.RecursiveStatementBodyProperty; value = this.RecursiveExpressionBodyMethod(); value = this.RecursiveExpressionBodyMethod(1); value = this.RecursiveStatementBodyMethod(); value = this.RecursiveStatementBodyMethod(1); value = RecursiveStatementBodyMethodWithOptionalParameter(value); value = value; #pragma warning restore GU0015 // Don't assign same more than once. } public IDisposable RecursiveProperty => this.RecursiveProperty; public int Value1 => this.Value1; public int Value2 => this.Value2; public int Value3 => this.Value1; public IDisposable RecursiveExpressionBodyProperty => this.RecursiveExpressionBodyProperty; public IDisposable RecursiveStatementBodyProperty { get { return this.RecursiveStatementBodyProperty; } } public IDisposable Value4 { get { return this.Value4; } set { if (value == this.Value4) { return; } this.Value4 = value; } } public IDisposable Value5 { get => this.Value5; set { if (value == this.Value5) { return; } this.Value5 = value; } } public IDisposable Value6 { get => this.Value5; set { if (value == this.Value5) { return; } this.Value5 = value; } } public IDisposable Bar1 { get { return this.bar1; } set { if (Equals(value, this.bar1)) { return; } if (value != null && this.bar2 != null) { this.Bar2 = null; } this.bar1 = value; } } public IDisposable Bar2 { get { return this.bar2; } set { if (Equals(value, this.bar2)) { return; } if (value != null && this.bar1 != null) { this.Bar1 = null; } this.bar2 = value; } } public static bool RecursiveOut(out IDisposable value) { return RecursiveOut(out value); } public static bool RecursiveOut(int foo, out IDisposable value) { return RecursiveOut(2, out value); } public static bool RecursiveOut(double foo, out IDisposable value) { value = null; return RecursiveOut(3.0, out value); } public static bool RecursiveOut(string foo, out IDisposable value) { if (foo == null) { return RecursiveOut(3.0, out value); } value = null; return true; } public static bool RecursiveRef(ref IDisposable value) { return RecursiveRef(ref value); } public Disposable RecursiveMethod() => this.RecursiveMethod(); public void NotUsingRecursive() { var item1 = this.RecursiveProperty; var item2 = this.RecursiveMethod(); } public void UsingRecursive() { using (var item = new Disposable()) { } using (var item = this.RecursiveProperty) { } using (this.RecursiveProperty) { } using (var item = this.RecursiveMethod()) { } using (this.RecursiveMethod()) { } } public IDisposable RecursiveExpressionBodyMethod() => this.RecursiveExpressionBodyMethod(); public IDisposable RecursiveExpressionBodyMethod(int value) => this.RecursiveExpressionBodyMethod(value); public IDisposable RecursiveStatementBodyMethod() { return this.RecursiveStatementBodyMethod(); } public IDisposable RecursiveStatementBodyMethod(int value) { return this.RecursiveStatementBodyMethod(value); } public void Meh() { #pragma warning disable GU0015 // Don't assign same more than once. var value = this.RecursiveExpressionBodyProperty; value = this.RecursiveStatementBodyProperty; value = this.RecursiveExpressionBodyMethod(); value = this.RecursiveExpressionBodyMethod(1); value = this.RecursiveStatementBodyMethod(); value = this.RecursiveStatementBodyMethod(1); value = RecursiveStatementBodyMethodWithOptionalParameter(value); RecursiveOut(out value); RecursiveOut(1, out value); RecursiveOut(1.0, out value); RecursiveOut(string.Empty, out value); RecursiveRef(ref value); value = value; #pragma warning restore GU0015 // Don't assign same more than once. } private static IDisposable RecursiveStatementBodyMethodWithOptionalParameter(IDisposable value, IEnumerable<IDisposable> values = null) { if (values == null) { return RecursiveStatementBodyMethodWithOptionalParameter(value, new[] { value }); } return value; } } }
using System; using System.Collections.Generic; using ModestTree; namespace Zenject { public abstract class IFactoryProviderBase<TContract> : IProvider { public IFactoryProviderBase( DiContainer container, Guid factoryId) { Container = container; FactoryId = factoryId; } public bool IsCached { get { return false; } } protected Guid FactoryId { get; private set; } protected DiContainer Container { get; private set; } public bool TypeVariesBasedOnMemberType { get { return false; } } public Type GetInstanceType(InjectContext context) { return typeof(TContract); } public abstract void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer); } // Zero parameters [NoReflectionBaking] public class IFactoryProvider<TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider( DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.That(args.IsEmpty()); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add(((IFactory<TContract>)factory).Create()); } } } // One parameter [NoReflectionBaking] public class IFactoryProvider<TParam1, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 1); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add(((IFactory<TParam1, TContract>)factory).Create((TParam1)args[0].Value)); } } } // Two parameters [NoReflectionBaking] public class IFactoryProvider<TParam1, TParam2, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 2); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TParam2, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add( ((IFactory<TParam1, TParam2, TContract>)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value)); } } } // Three parameters [NoReflectionBaking] public class IFactoryProvider<TParam1, TParam2, TParam3, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 3); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>()); Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TParam2, TParam3, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add( ((IFactory<TParam1, TParam2, TParam3, TContract>)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value)); } } } // Four parameters [NoReflectionBaking] public class IFactoryProvider<TParam1, TParam2, TParam3, TParam4, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 4); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>()); Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>()); Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TParam2, TParam3, TParam4, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add( ((IFactory<TParam1, TParam2, TParam3, TParam4, TContract>)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value)); } } } // Five parameters [NoReflectionBaking] public class IFactoryProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 5); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>()); Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>()); Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>()); Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add( ((IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TContract>)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value, (TParam5)args[4].Value)); } } } // Six parameters [NoReflectionBaking] public class IFactoryProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 6); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>()); Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>()); Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>()); Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>()); Assert.That(args[5].Type.DerivesFromOrEqual<TParam6>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add( ((IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TContract>)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value, (TParam5)args[4].Value, (TParam6)args[5].Value)); } } } // Ten parameters [NoReflectionBaking] public class IFactoryProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TContract> : IFactoryProviderBase<TContract> { public IFactoryProvider(DiContainer container, Guid factoryId) : base(container, factoryId) { } public override void GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer) { Assert.IsEqual(args.Count, 10); Assert.IsNotNull(context); Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>()); Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>()); Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>()); Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>()); Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>()); Assert.That(args[5].Type.DerivesFromOrEqual<TParam6>()); Assert.That(args[6].Type.DerivesFromOrEqual<TParam7>()); Assert.That(args[7].Type.DerivesFromOrEqual<TParam8>()); Assert.That(args[8].Type.DerivesFromOrEqual<TParam9>()); Assert.That(args[9].Type.DerivesFromOrEqual<TParam10>()); // Do this even when validating in case it has its own dependencies var factory = Container.ResolveId(typeof(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TContract>), FactoryId); injectAction = null; if (Container.IsValidating) { // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here buffer.Add(new ValidationMarker(typeof(TContract))); } else { buffer.Add( ((IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TContract>)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value, (TParam5)args[4].Value, (TParam6)args[5].Value, (TParam7)args[6].Value, (TParam8)args[7].Value, (TParam9)args[8].Value, (TParam10)args[9].Value)); } } } }
/* * 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; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Mono.Addins; /***************************************************** * * XMLRPCModule * * Module for accepting incoming communications from * external XMLRPC client and calling a remote data * procedure for a registered data channel/prim. * * * 1. On module load, open a listener port * 2. Attach an XMLRPC handler * 3. When a request is received: * 3.1 Parse into components: channel key, int, string * 3.2 Look up registered channel listeners * 3.3 Call the channel (prim) remote data method * 3.4 Capture the response (llRemoteDataReply) * 3.5 Return response to client caller * 3.6 If no response from llRemoteDataReply within * RemoteReplyScriptTimeout, generate script timeout fault * * Prims in script must: * 1. Open a remote data channel * 1.1 Generate a channel ID * 1.2 Register primid,channelid pair with module * 2. Implement the remote data procedure handler * * llOpenRemoteDataChannel * llRemoteDataReply * remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval) * llCloseRemoteDataChannel * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XMLRPCModule")] public class XMLRPCModule : ISharedRegionModule, IXMLRPC { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_name = "XMLRPCModule"; // <channel id, RPCChannelInfo> private Dictionary<UUID, RPCChannelInfo> m_openChannels; private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses; private int m_remoteDataPort = 0; public int Port { get { return m_remoteDataPort; } } private Dictionary<UUID, RPCRequestInfo> m_rpcPending; private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses; private List<Scene> m_scenes = new List<Scene>(); private int RemoteReplyScriptTimeout = 9000; private int RemoteReplyScriptWait = 300; private object XMLRPCListLock = new object(); #region ISharedRegionModule Members public void Initialise(IConfigSource config) { // We need to create these early because the scripts might be calling // But since this gets called for every region, we need to make sure they // get called only one time (or we lose any open channels) m_openChannels = new Dictionary<UUID, RPCChannelInfo>(); m_rpcPending = new Dictionary<UUID, RPCRequestInfo>(); m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>(); m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>(); if (config.Configs["XMLRPC"] != null) { try { m_remoteDataPort = config.Configs["XMLRPC"].GetInt("XmlRpcPort", m_remoteDataPort); } catch (Exception) { } } } public void PostInitialise() { if (IsEnabled()) { // Start http server // Attach xmlrpc handlers // m_log.InfoFormat( // "[XML RPC MODULE]: Starting up XMLRPC Server on port {0} for llRemoteData commands.", // m_remoteDataPort); IHttpServer httpServer = MainServer.GetHttpServer((uint)m_remoteDataPort); httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData); } } public void AddRegion(Scene scene) { if (!IsEnabled()) return; if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); scene.RegisterModuleInterface<IXMLRPC>(this); } } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (!IsEnabled()) return; if (m_scenes.Contains(scene)) { scene.UnregisterModuleInterface<IXMLRPC>(this); m_scenes.Remove(scene); } } public void Close() { } public string Name { get { return m_name; } } public Type ReplaceableInterface { get { return null; } } #endregion #region IXMLRPC Members public bool IsEnabled() { return (m_remoteDataPort > 0); } /********************************************** * OpenXMLRPCChannel * * Generate a UUID channel key and add it and * the prim id to dictionary <channelUUID, primUUID> * * A custom channel key can be proposed. * Otherwise, passing UUID.Zero will generate * and return a random channel * * First check if there is a channel assigned for * this itemID. If there is, then someone called * llOpenRemoteDataChannel twice. Just return the * original channel. Other option is to delete the * current channel and assign a new one. * * ********************************************/ public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID) { UUID newChannel = UUID.Zero; // This should no longer happen, but the check is reasonable anyway if (null == m_openChannels) { m_log.Warn("[XML RPC MODULE]: Attempt to open channel before initialization is complete"); return newChannel; } //Is a dupe? foreach (RPCChannelInfo ci in m_openChannels.Values) { if (ci.GetItemID().Equals(itemID)) { // return the original channel ID for this item newChannel = ci.GetChannelID(); break; } } if (newChannel == UUID.Zero) { newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID; RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel); lock (XMLRPCListLock) { m_openChannels.Add(newChannel, rpcChanInfo); } } return newChannel; } // Delete channels based on itemID // for when a script is deleted public void DeleteChannels(UUID itemID) { if (m_openChannels != null) { ArrayList tmp = new ArrayList(); lock (XMLRPCListLock) { foreach (RPCChannelInfo li in m_openChannels.Values) { if (li.GetItemID().Equals(itemID)) { tmp.Add(itemID); } } IEnumerator tmpEnumerator = tmp.GetEnumerator(); while (tmpEnumerator.MoveNext()) m_openChannels.Remove((UUID) tmpEnumerator.Current); } } } /********************************************** * Remote Data Reply * * Response to RPC message * *********************************************/ public void RemoteDataReply(string channel, string message_id, string sdata, int idata) { UUID message_key = new UUID(message_id); UUID channel_key = new UUID(channel); RPCRequestInfo rpcInfo = null; if (message_key == UUID.Zero) { foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values) if (oneRpcInfo.GetChannelKey() == channel_key) rpcInfo = oneRpcInfo; } else { m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo); } if (rpcInfo != null) { rpcInfo.SetStrRetval(sdata); rpcInfo.SetIntRetval(idata); rpcInfo.SetProcessed(true); m_rpcPendingResponses.Remove(message_key); } else { m_log.Warn("[XML RPC MODULE]: Channel or message_id not found"); } } /********************************************** * CloseXMLRPCChannel * * Remove channel from dictionary * *********************************************/ public void CloseXMLRPCChannel(UUID channelKey) { if (m_openChannels.ContainsKey(channelKey)) m_openChannels.Remove(channelKey); } public bool hasRequests() { lock (XMLRPCListLock) { if (m_rpcPending != null) return (m_rpcPending.Count > 0); else return false; } } public IXmlRpcRequestInfo GetNextCompletedRequest() { if (m_rpcPending != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_rpcPending.Keys) { RPCRequestInfo tmpReq; if (m_rpcPending.TryGetValue(luid, out tmpReq)) { if (!tmpReq.IsProcessed()) return tmpReq; } } } } return null; } public void RemoveCompletedRequest(UUID id) { lock (XMLRPCListLock) { RPCRequestInfo tmp; if (m_rpcPending.TryGetValue(id, out tmp)) { m_rpcPending.Remove(id); m_rpcPendingResponses.Add(id, tmp); } else { m_log.Error("[XML RPC MODULE]: UNABLE TO REMOVE COMPLETED REQUEST"); } } } public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { SendRemoteDataRequest req = new SendRemoteDataRequest( localID, itemID, channel, dest, idata, sdata ); m_pendingSRDResponses.Add(req.GetReqID(), req); req.Process(); return req.ReqID; } public IServiceRequest GetNextCompletedSRDRequest() { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_pendingSRDResponses.Keys) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq)) { if (tmpReq.Finished) return tmpReq; } } } } return null; } public void RemoveCompletedSRDRequest(UUID id) { lock (XMLRPCListLock) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(id, out tmpReq)) { m_pendingSRDResponses.Remove(id); } } } public void CancelSRDRequests(UUID itemID) { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values) { if (li.ItemID.Equals(itemID)) m_pendingSRDResponses.Remove(li.GetReqID()); } } } } #endregion public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable) request.Params[0]; bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") && requestData.Contains("StringValue")); if (GoodXML) { UUID channel = new UUID((string) requestData["Channel"]); RPCChannelInfo rpcChanInfo; if (m_openChannels.TryGetValue(channel, out rpcChanInfo)) { string intVal = Convert.ToInt32(requestData["IntValue"]).ToString(); string strVal = (string) requestData["StringValue"]; RPCRequestInfo rpcInfo; lock (XMLRPCListLock) { rpcInfo = new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal, intVal); m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo); } int timeoutCtr = 0; while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout)) { Thread.Sleep(RemoteReplyScriptWait); timeoutCtr += RemoteReplyScriptWait; } if (rpcInfo.IsProcessed()) { Hashtable param = new Hashtable(); param["StringValue"] = rpcInfo.GetStrRetval(); param["IntValue"] = rpcInfo.GetIntRetval(); ArrayList parameters = new ArrayList(); parameters.Add(param); response.Value = parameters; rpcInfo = null; } else { response.SetFault(-1, "Script timeout"); rpcInfo = null; } } else { response.SetFault(-1, "Invalid channel"); } } return response; } } public class RPCRequestInfo: IXmlRpcRequestInfo { private UUID m_ChannelKey; private string m_IntVal; private UUID m_ItemID; private uint m_localID; private UUID m_MessageID; private bool m_processed; private int m_respInt; private string m_respStr; private string m_StrVal; public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal) { m_localID = localID; m_StrVal = strVal; m_IntVal = intVal; m_ItemID = itemID; m_ChannelKey = channelKey; m_MessageID = UUID.Random(); m_processed = false; m_respStr = String.Empty; m_respInt = 0; } public bool IsProcessed() { return m_processed; } public UUID GetChannelKey() { return m_ChannelKey; } public void SetProcessed(bool processed) { m_processed = processed; } public void SetStrRetval(string resp) { m_respStr = resp; } public string GetStrRetval() { return m_respStr; } public void SetIntRetval(int resp) { m_respInt = resp; } public int GetIntRetval() { return m_respInt; } public uint GetLocalID() { return m_localID; } public UUID GetItemID() { return m_ItemID; } public string GetStrVal() { return m_StrVal; } public int GetIntValue() { return int.Parse(m_IntVal); } public UUID GetMessageID() { return m_MessageID; } } public class RPCChannelInfo { private UUID m_ChannelKey; private UUID m_itemID; private uint m_localID; public RPCChannelInfo(uint localID, UUID itemID, UUID channelID) { m_ChannelKey = channelID; m_localID = localID; m_itemID = itemID; } public UUID GetItemID() { return m_itemID; } public UUID GetChannelID() { return m_ChannelKey; } public uint GetLocalID() { return m_localID; } } public class SendRemoteDataRequest: IServiceRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Channel; public string DestURL; private bool _finished; public bool Finished { get { return _finished; } set { _finished = value; } } private Thread httpThread; public int Idata; private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public XmlRpcRequest Request; public int ResponseIdata; public string ResponseSdata; public string Sdata; public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { this.Channel = channel; DestURL = dest; this.Idata = idata; this.Sdata = sdata; ItemID = itemID; LocalID = localID; ReqID = UUID.Random(); } public void Process() { _finished = false; httpThread = WorkManager.StartThread(SendRequest, "HttpRequestThread", ThreadPriority.BelowNormal, true, false); } /* * TODO: More work on the response codes. Right now * returning 200 for success or 499 for exception */ public void SendRequest() { Hashtable param = new Hashtable(); // Check if channel is an UUID // if not, use as method name UUID parseUID; string mName = "llRemoteData"; if (!string.IsNullOrEmpty(Channel)) if (!UUID.TryParse(Channel, out parseUID)) mName = Channel; else param["Channel"] = Channel; param["StringValue"] = Sdata; param["IntValue"] = Convert.ToString(Idata); ArrayList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest(mName, parameters); try { XmlRpcResponse resp = req.Send(DestURL, 30000); if (resp != null) { Hashtable respParms; if (resp.Value.GetType().Equals(typeof(Hashtable))) { respParms = (Hashtable) resp.Value; } else { ArrayList respData = (ArrayList) resp.Value; respParms = (Hashtable) respData[0]; } if (respParms != null) { if (respParms.Contains("StringValue")) { Sdata = (string) respParms["StringValue"]; } if (respParms.Contains("IntValue")) { Idata = Convert.ToInt32(respParms["IntValue"]); } if (respParms.Contains("faultString")) { Sdata = (string) respParms["faultString"]; } if (respParms.Contains("faultCode")) { Idata = Convert.ToInt32(respParms["faultCode"]); } } } } catch (Exception we) { Sdata = we.Message; m_log.Warn("[SendRemoteDataRequest]: Request failed"); m_log.Warn(we.StackTrace); } _finished = true; Watchdog.RemoveThread(); } public void Stop() { try { if (httpThread != null) { Watchdog.AbortThread(httpThread.ManagedThreadId); httpThread = null; } } catch (Exception) { } } public UUID GetReqID() { return ReqID; } } }
//----------------------------------------------------------------------- // <copyright file="InputStreamSourceSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.IO; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.IO { public class InputStreamSourceSpec : AkkaSpec { #region internal classes private sealed class ConstInputStream : Stream { public override void Flush() { throw new System.NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new System.NotImplementedException(); } public override void SetLength(long value) { throw new System.NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { buffer[0] = 42; return 1; } public override void Write(byte[] buffer, int offset, int count) { throw new System.NotImplementedException(); } public override bool CanRead { get; } = true; public override bool CanSeek { get; } public override bool CanWrite { get; } public override long Length { get; } public override long Position { get; set; } } private sealed class ListInputStream : Stream { private List<byte> _buf; public ListInputStream(IEnumerable<string> values) { _buf = values.Select(s => Convert.ToByte(s[0])).ToList(); } public override void Flush() { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { if (_buf.Count == 0) return 0; _buf.CopyTo(buffer); _buf = new List<byte>(); return 3; } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override bool CanRead { get; } = true; public override bool CanSeek { get; } public override bool CanWrite { get; } public override long Length { get; } public override long Position { get; set; } } private sealed class EmittedInputStream : Stream { private readonly TestLatch _latch; private bool _emitted; public EmittedInputStream(TestLatch latch) { _latch = latch; } public override void Flush() { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { if (!_emitted) { _emitted = true; buffer[0] = Convert.ToByte('M'); return 1; } _latch.Ready(); return 0; } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override bool CanRead { get; } = true; public override bool CanSeek { get; } public override bool CanWrite { get; } public override long Length { get; } public override long Position { get; set; } } #endregion private readonly ActorMaterializer _materializer; public InputStreamSourceSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper) { Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig()); var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher"); _materializer = Sys.Materializer(settings); } [Fact] public void InputStreamSource_must_not_signal_when_no_demand() { var f = StreamConverters.FromInputStream(() => new ConstInputStream()); f.TakeWithin(TimeSpan.FromSeconds(5)).RunForeach(it => { }, _materializer).Wait(TimeSpan.FromSeconds(10)); } [Fact] public void InputStreamSource_must_read_bytes_from_InputStream() { this.AssertAllStagesStopped(() => { var f = StreamConverters.FromInputStream(() => new ListInputStream(new[] {"a", "b", "c"})) .RunWith(Sink.First<ByteString>(), _materializer); f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); f.Result.ShouldBeEquivalentTo(ByteString.FromString("abc")); }, _materializer); } [Fact] public void InputStreamSource_must_emit_as_soon_as_read() { this.AssertAllStagesStopped(() => { var latch = new TestLatch(1); var probe = StreamConverters.FromInputStream(() => new EmittedInputStream(latch), chunkSize: 1) .RunWith(this.SinkProbe<ByteString>(), _materializer); probe.Request(4); probe.ExpectNext(ByteString.FromString("M")); latch.CountDown(); probe.ExpectComplete(); }, _materializer); } } }
// <copyright file="PlayGamesPlatform.cs" company="Google Inc."> // Copyright (C) 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. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames { using System; using System.Collections.Generic; using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.Events; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.BasicApi.Nearby; using GooglePlayGames.BasicApi.Quests; using GooglePlayGames.BasicApi.SavedGame; using GooglePlayGames.OurUtils; using UnityEngine; using UnityEngine.SocialPlatforms; /// <summary> /// Provides access to the Google Play Games platform. This is an implementation of /// UnityEngine.SocialPlatforms.ISocialPlatform. Activate this platform by calling /// the <see cref="Activate" /> method, then authenticate by calling /// the <see cref="Authenticate" /> method. After authentication /// completes, you may call the other methods of this class. This is not a complete /// implementation of the ISocialPlatform interface. Methods lacking an implementation /// or whose behavior is at variance with the standard are noted as such. /// </summary> public class PlayGamesPlatform : ISocialPlatform { /// <summary>Singleton instance</summary> private static volatile PlayGamesPlatform sInstance = null; /// <summary>status of nearby connection initialization.</summary> private static volatile bool sNearbyInitializePending; /// <summary>Reference to the nearby client.</summary> /// <remarks>This is static since it can be used without using play game services.</remarks> private static volatile INearbyConnectionClient sNearbyConnectionClient; /// <summary>Configuration used to create this instance.</summary> private readonly PlayGamesClientConfiguration mConfiguration; /// <summary>The local user.</summary> private PlayGamesLocalUser mLocalUser = null; /// <summary>Reference to the platform specific implementation.</summary> private IPlayGamesClient mClient = null; /// <summary>the default leaderboard we show on ShowLeaderboardUI</summary> private string mDefaultLbUi = null; /// <summary>the mapping table from alias to leaderboard/achievement id.</summary> private Dictionary<string, string> mIdMap = new Dictionary<string, string>(); /// <summary> /// Initializes a new instance of the <see cref="GooglePlayGames.PlayGamesPlatform"/> class. /// </summary> /// <param name="client">Implementation client to use for this instance.</param> internal PlayGamesPlatform(IPlayGamesClient client) { this.mClient = Misc.CheckNotNull(client); this.mLocalUser = new PlayGamesLocalUser(this); this.mConfiguration = PlayGamesClientConfiguration.DefaultConfiguration; } /// <summary> /// Initializes a new instance of the <see cref="GooglePlayGames.PlayGamesPlatform"/> class. /// </summary> /// <param name="configuration">Configuration object to use.</param> private PlayGamesPlatform(PlayGamesClientConfiguration configuration) { this.mLocalUser = new PlayGamesLocalUser(this); this.mConfiguration = configuration; } /// <summary> /// Gets or sets a value indicating whether debug logs are enabled. This property /// may be set before calling <see cref="Activate" /> method. /// </summary> /// <returns> /// <c>true</c> if debug log enabled; otherwise, <c>false</c>. /// </returns> public static bool DebugLogEnabled { get { return GooglePlayGames.OurUtils.Logger.DebugLogEnabled; } set { GooglePlayGames.OurUtils.Logger.DebugLogEnabled = value; } } /// <summary> /// Gets the singleton instance of the Play Games platform. /// </summary> /// <returns> /// The instance. /// </returns> public static PlayGamesPlatform Instance { get { if (sInstance == null) { GooglePlayGames.OurUtils.Logger.d( "Instance was not initialized, using default configuration."); InitializeInstance(PlayGamesClientConfiguration.DefaultConfiguration); } return sInstance; } } /// <summary> /// Gets the nearby connection client. NOTE: Can be null until the nearby client /// is initialized. Call InitializeNearby to use callback to be notified when initialization /// is complete. /// </summary> /// <value>The nearby.</value> public static INearbyConnectionClient Nearby { get { if (sNearbyConnectionClient == null && !sNearbyInitializePending) { sNearbyInitializePending = true; InitializeNearby(null); } return sNearbyConnectionClient; } } /// <summary> Gets the real time multiplayer API object</summary> public IRealTimeMultiplayerClient RealTime { get { return mClient.GetRtmpClient(); } } /// <summary> Gets the turn based multiplayer API object</summary> public ITurnBasedMultiplayerClient TurnBased { get { return mClient.GetTbmpClient(); } } /// <summary>Gets the saved game client object.</summary> /// <value>The saved game client.</value> public ISavedGameClient SavedGame { get { return mClient.GetSavedGameClient(); } } /// <summary>Gets the events client object.</summary> /// <value>The events client.</value> public IEventsClient Events { get { return mClient.GetEventsClient(); } } /// <summary>Gets the quests client object.</summary> /// <value>The quests client.</value> public IQuestsClient Quests { get { return mClient.GetQuestsClient(); } } /// <summary> /// Gets the local user. /// </summary> /// <returns> /// The local user. /// </returns> public ILocalUser localUser { get { return mLocalUser; } } /// <summary> /// Initializes the instance of Play Game Services platform. /// </summary> /// <remarks>This creates the singleton instance of the platform. /// Multiple calls to this method are ignored. /// </remarks> /// <param name="configuration">Configuration to use when initializing.</param> public static void InitializeInstance(PlayGamesClientConfiguration configuration) { if (sInstance != null) { GooglePlayGames.OurUtils.Logger.w( "PlayGamesPlatform already initialized. Ignoring this call."); return; } sInstance = new PlayGamesPlatform(configuration); } /// <summary> /// Initializes the nearby connection platform. /// </summary> /// <remarks>This call initializes the nearby connection platform. This /// is independent of the Play Game Services initialization. Multiple /// calls to this method are ignored. /// </remarks> /// <param name="callback">Callback invoked when complete.</param> public static void InitializeNearby(Action<INearbyConnectionClient> callback) { Debug.Log("Calling InitializeNearby!"); if (sNearbyConnectionClient == null) { #if UNITY_ANDROID && !UNITY_EDITOR NearbyConnectionClientFactory.Create(client => { Debug.Log("Nearby Client Created!!"); sNearbyConnectionClient = client; if (callback != null) { callback.Invoke(client); } else { Debug.Log("Initialize Nearby callback is null"); } }); #else sNearbyConnectionClient = new DummyNearbyConnectionClient(); if (callback != null) { callback.Invoke(sNearbyConnectionClient); } #endif } else if (callback != null) { Debug.Log("Nearby Already initialized: calling callback directly"); callback.Invoke(sNearbyConnectionClient); } else { Debug.Log("Nearby Already initialized"); } } /// <summary> /// Activates the Play Games platform as the implementation of Social.Active. /// After calling this method, you can call methods on Social.Active. For /// example, <c>Social.Active.Authenticate()</c>. /// </summary> /// <returns>The singleton <see cref="PlayGamesPlatform" /> instance.</returns> public static PlayGamesPlatform Activate() { GooglePlayGames.OurUtils.Logger.d("Activating PlayGamesPlatform."); Social.Active = PlayGamesPlatform.Instance; GooglePlayGames.OurUtils.Logger.d( "PlayGamesPlatform activated: " + Social.Active); return PlayGamesPlatform.Instance; } /// <summary>Gets pointer to the Google API client.</summary> /// <remarks>This is provided as a helper to making additional JNI calls. /// This connection is initialized and controlled by the underlying SDK. /// </remarks> /// <returns>The pointer of the client. Zero on non-android platforms.</returns> public IntPtr GetApiClient() { return mClient.GetApiClient(); } /// <summary> /// Specifies that the ID <c>fromId</c> should be implicitly replaced by <c>toId</c> /// on any calls that take a leaderboard or achievement ID. /// </summary> /// <remarks> After a mapping is /// registered, you can use <c>fromId</c> instead of <c>toId</c> when making a call. /// For example, the following two snippets are equivalent: /// <code> /// ReportProgress("Cfiwjew894_AQ", 100.0, callback); /// </code> /// ...is equivalent to: /// <code> /// AddIdMapping("super-combo", "Cfiwjew894_AQ"); /// ReportProgress("super-combo", 100.0, callback); /// </code> /// </remarks> /// <param name='fromId'> /// The identifier to map. /// </param> /// <param name='toId'> /// The identifier that <c>fromId</c> will be mapped to. /// </param> public void AddIdMapping(string fromId, string toId) { mIdMap[fromId] = toId; } /// <summary> /// Authenticate the local user with the Google Play Games service. /// </summary> /// <param name='callback'> /// The callback to call when authentication finishes. It will be called /// with <c>true</c> if authentication was successful, <c>false</c> /// otherwise. /// </param> public void Authenticate(Action<bool> callback) { Authenticate(callback, false); } /// <summary> /// Authenticate the local user with the Google Play Games service. /// </summary> /// <param name='callback'> /// The callback to call when authentication finishes. It will be called /// with <c>true</c> if authentication was successful, <c>false</c> /// otherwise. /// </param> /// <param name='silent'> /// Indicates whether authentication should be silent. If <c>false</c>, /// authentication may show popups and interact with the user to obtain /// authorization. If <c>true</c>, there will be no popups or interaction with /// the user, and the authentication will fail instead if such interaction /// is required. A typical pattern is to try silent authentication on startup /// and, if that fails, present the user with a "Sign in" button that then /// triggers normal (not silent) authentication. /// </param> public void Authenticate(Action<bool> callback, bool silent) { // make a platform-specific Play Games client if (mClient == null) { GooglePlayGames.OurUtils.Logger.d( "Creating platform-specific Play Games client."); mClient = PlayGamesClientFactory.GetPlatformPlayGamesClient(mConfiguration); } // authenticate! mClient.Authenticate(callback, silent); } /// <summary> /// Provided for compatibility with ISocialPlatform. /// </summary> /// <seealso cref="Authenticate(Action&lt;bool&gt;,bool)"/> /// <param name="unused">Unused parameter for this implementation.</param> /// <param name="callback">Callback invoked when complete.</param> public void Authenticate(ILocalUser unused, Action<bool> callback) { Authenticate(callback, false); } /// <summary> /// Determines whether the user is authenticated. /// </summary> /// <returns> /// <c>true</c> if the user is authenticated; otherwise, <c>false</c>. /// </returns> public bool IsAuthenticated() { return mClient != null && mClient.IsAuthenticated(); } /// <summary>Sign out. After signing out, /// Authenticate must be called again to sign back in. /// </summary> public void SignOut() { if (mClient != null) { mClient.SignOut(); } mLocalUser = new PlayGamesLocalUser(this); } /// <summary> /// Loads the users. /// </summary> /// <param name="userIds">User identifiers.</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserId() can only be called after authentication."); callback(new IUserProfile[0]); } mClient.LoadUsers(userIds, callback); } /// <summary> /// Returns the user's Google ID. /// </summary> /// <returns> /// The user's Google ID. No guarantees are made as to the meaning or format of /// this identifier except that it is unique to the user who is signed in. /// </returns> public string GetUserId() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserId() can only be called after authentication."); return "0"; } return mClient.GetUserId(); } /// <summary> /// Get an id token for the user. /// </summary> /// <param name="idTokenCallback"> A callback to be invoked after token is retrieved. Will be passed null value /// on failure. </param> public void GetIdToken(Action<string> idTokenCallback) { if (mClient != null) { mClient.GetIdToken(idTokenCallback); } else { GooglePlayGames.OurUtils.Logger.e( "No client available, calling back with null."); idTokenCallback(null); } } /// <summary> /// Returns an id token for the user. /// </summary> /// <returns> /// An id token for the user. /// </returns> public string GetAccessToken() { if (mClient != null) { return mClient.GetAccessToken(); } return null; } /// <summary> /// Gets the server auth code. /// </summary> /// <remarks>This code is used by the server application in order to get /// an oauth token. For how to use this acccess token please see: /// https://developers.google.com/drive/v2/web/auth/web-server /// </remarks> /// <param name="callback">Callback.</param> public void GetServerAuthCode(Action<CommonStatusCodes, string> callback) { if (mClient != null && mClient.IsAuthenticated()) { if (GameInfo.WebClientIdInitialized()) { mClient.GetServerAuthCode(GameInfo.WebClientId, callback); } else { GooglePlayGames.OurUtils.Logger.e( "GetServerAuthCode requires a webClientId."); callback(CommonStatusCodes.DeveloperError, ""); } } else { GooglePlayGames.OurUtils.Logger.e( "GetServerAuthCode can only be called after authentication."); callback(CommonStatusCodes.SignInRequired, ""); } } /// <summary> /// Gets the user's email. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available.</remarks> /// <returns>The user email or null if not authenticated or the permission is /// not available.</returns> public string GetUserEmail() { if (mClient != null) { return mClient.GetUserEmail(); } return null; } /// <summary> /// Gets the user's email with a callback. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available.</remarks> /// <param name="callback">The callback with a status code of the request, /// and string which is the email. It can be null.</param> public void GetUserEmail(Action<CommonStatusCodes, string> callback) { mClient.GetUserEmail(callback); } /// <summary> /// Gets the player stats. /// </summary> /// <param name="callback">Callback invoked when completed.</param> public void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback) { if (mClient != null && mClient.IsAuthenticated()) { mClient.GetPlayerStats(callback); } else { GooglePlayGames.OurUtils.Logger.e( "GetPlayerStats can only be called after authentication."); callback(CommonStatusCodes.SignInRequired, new PlayerStats()); } } /// <summary> /// Returns the achievement corresponding to the passed achievement identifier. /// </summary> /// <returns> /// The achievement corresponding to the identifer. <code>null</code> if no such /// achievement is found or if the user is not authenticated. /// </returns> /// <param name="achievementId"> /// The identifier of the achievement. /// </param> public Achievement GetAchievement(string achievementId) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetAchievement can only be called after authentication."); return null; } return mClient.GetAchievement(achievementId); } /// <summary> /// Returns the user's display name. /// </summary> /// <returns> /// The user display name (e.g. "Bruno Oliveira") /// </returns> public string GetUserDisplayName() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserDisplayName can only be called after authentication."); return string.Empty; } return mClient.GetUserDisplayName(); } /// <summary> /// Returns the user's avatar URL if they have one. /// </summary> /// <returns> /// The URL, or <code>null</code> if the user is not authenticated or does not have /// an avatar. /// </returns> public string GetUserImageUrl() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserImageUrl can only be called after authentication."); return null; } return mClient.GetUserImageUrl(); } /// <summary> /// Reports the progress of an achievement (reveal, unlock or increment). This method attempts /// to implement the expected behavior of ISocialPlatform.ReportProgress as closely as possible, /// as described below. Although this method works with incremental achievements for compatibility /// purposes, calling this method for incremental achievements is not recommended, /// since the Play Games API exposes incremental achievements in a very different way /// than the interface presented by ISocialPlatform.ReportProgress. The implementation of this /// method for incremental achievements attempts to produce the correct result, but may be /// imprecise. If possible, call <see cref="IncrementAchievement" /> instead. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to unlock, reveal or increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='progress'> /// Progress of the achievement. If the achievement is standard (not incremental), then /// a progress of 0.0 will reveal the achievement and 100.0 will unlock it. Behavior of other /// values is undefined. If the achievement is incremental, then this value is interpreted /// as the total percentage of the achievement's progress that the player should have /// as a result of this call (regardless of the progress they had before). So if the /// player's previous progress was 30% and this call specifies 50.0, the new progress will /// be 50% (not 80%). /// </param> /// <param name='callback'> /// Callback that will be called to report the result of the operation: <c>true</c> on /// success, <c>false</c> otherwise. /// </param> public void ReportProgress(string achievementID, double progress, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "ReportProgress can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary GooglePlayGames.OurUtils.Logger.d( "ReportProgress, " + achievementID + ", " + progress); achievementID = MapId(achievementID); // if progress is 0.0, we just want to reveal it if (progress < 0.000001) { GooglePlayGames.OurUtils.Logger.d( "Progress 0.00 interpreted as request to reveal."); mClient.RevealAchievement(achievementID, callback); return; } // figure out if it's a standard or incremental achievement bool isIncremental = false; int curSteps = 0, totalSteps = 0; Achievement ach = mClient.GetAchievement(achievementID); if (ach == null) { GooglePlayGames.OurUtils.Logger.w( "Unable to locate achievement " + achievementID); GooglePlayGames.OurUtils.Logger.w( "As a quick fix, assuming it's standard."); isIncremental = false; } else { isIncremental = ach.IsIncremental; curSteps = ach.CurrentSteps; totalSteps = ach.TotalSteps; GooglePlayGames.OurUtils.Logger.d( "Achievement is " + (isIncremental ? "INCREMENTAL" : "STANDARD")); if (isIncremental) { GooglePlayGames.OurUtils.Logger.d( "Current steps: " + curSteps + "/" + totalSteps); } } // do the right thing depending on the achievement type if (isIncremental) { // increment it to the target percentage (approximate) GooglePlayGames.OurUtils.Logger.d("Progress " + progress + " interpreted as incremental target (approximate)."); if (progress >= 0.0 && progress <= 1.0) { // in a previous version, incremental progress was reported by using the range [0-1] GooglePlayGames.OurUtils.Logger.w( "Progress " + progress + " is less than or equal to 1. You might be trying to use values in the range of [0,1], while values are expected to be within the range [0,100]. If you are using the latter, you can safely ignore this message."); } int targetSteps = (int)((progress / 100) * totalSteps); int numSteps = targetSteps - curSteps; GooglePlayGames.OurUtils.Logger.d("Target steps: " + targetSteps + ", cur steps:" + curSteps); GooglePlayGames.OurUtils.Logger.d("Steps to increment: " + numSteps); // handle incremental achievements with 0 steps if (numSteps >= 0) { mClient.IncrementAchievement(achievementID, numSteps, callback); } } else if (progress >= 100) { // unlock it! GooglePlayGames.OurUtils.Logger.d( "Progress " + progress + " interpreted as UNLOCK."); mClient.UnlockAchievement(achievementID, callback); } else { // not enough to unlock GooglePlayGames.OurUtils.Logger.d("Progress " + progress + " not enough to unlock non-incremental achievement."); } } /// <summary> /// Increments an achievement. This is a Play Games extension of the ISocialPlatform API. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='steps'> /// The number of steps to increment the achievement by. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void IncrementAchievement(string achievementID, int steps, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "IncrementAchievement can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary GooglePlayGames.OurUtils.Logger.d( "IncrementAchievement: " + achievementID + ", steps " + steps); achievementID = MapId(achievementID); mClient.IncrementAchievement(achievementID, steps, callback); } /// <summary> /// Set an achievement to have at least the given number of steps completed. /// Calling this method while the achievement already has more steps than /// the provided value is a no-op. Once the achievement reaches the /// maximum number of steps, the achievement is automatically unlocked, /// and any further mutation operations are ignored. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='steps'> /// The number of steps to increment the achievement by. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void SetStepsAtLeast(string achievementID, int steps, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "SetStepsAtLeast can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary GooglePlayGames.OurUtils.Logger.d( "SetStepsAtLeast: " + achievementID + ", steps " + steps); achievementID = MapId(achievementID); mClient.SetStepsAtLeast(achievementID, steps, callback); } /// <summary> /// Loads the Achievement descriptions. /// </summary> /// <param name="callback">The callback to receive the descriptions</param> public void LoadAchievementDescriptions(Action<IAchievementDescription[]> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "LoadAchievementDescriptions can only be called after authentication."); if (callback != null) { callback.Invoke(null); } return; } mClient.LoadAchievements(ach => { IAchievementDescription[] data = new IAchievementDescription[ach.Length]; for (int i = 0; i < data.Length; i++) { data[i] = new PlayGamesAchievement(ach[i]); } callback.Invoke(data); }); } /// <summary> /// Loads the achievement state for the current user. /// </summary> /// <param name="callback">The callback to receive the achievements</param> public void LoadAchievements(Action<IAchievement[]> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadAchievements can only be called after authentication."); callback.Invoke(null); } mClient.LoadAchievements(ach => { IAchievement[] data = new IAchievement[ach.Length]; for (int i = 0; i < data.Length; i++) { data[i] = new PlayGamesAchievement(ach[i]); } callback.Invoke(data); }); } /// <summary> /// Creates an achievement object which may be subsequently used to report an /// achievement. /// </summary> /// <returns> /// The achievement object. /// </returns> public IAchievement CreateAchievement() { return new PlayGamesAchievement(); } /// <summary> /// Reports a score to a leaderboard. /// </summary> /// <param name='score'> /// The score to report. /// </param> /// <param name='board'> /// The ID of the leaderboard on which the score is to be posted. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void ReportScore(long score, string board, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ReportScore can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } GooglePlayGames.OurUtils.Logger.d("ReportScore: score=" + score + ", board=" + board); string leaderboardId = MapId(board); mClient.SubmitScore(leaderboardId, score, callback); } /// <summary> /// Submits the score for the currently signed-in player /// to the leaderboard associated with a specific id /// and metadata (such as something the player did to earn the score). /// </summary> /// <param name="score">Score to report.</param> /// <param name="board">leaderboard id.</param> /// <param name="metadata">metadata about the score.</param> /// <param name="callback">Callback invoked upon completion.</param> public void ReportScore(long score, string board, string metadata, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ReportScore can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } GooglePlayGames.OurUtils.Logger.d("ReportScore: score=" + score + ", board=" + board + " metadata=" + metadata); string leaderboardId = MapId(board); mClient.SubmitScore(leaderboardId, score, metadata, callback); } /// <summary> /// Loads the scores relative the player. /// </summary> /// <remarks>This returns the 25 /// (which is the max results returned by the SDK per call) scores /// that are around the player's score on the Public, all time leaderboard. /// Use the overloaded methods which are specific to GPGS to modify these /// parameters. /// </remarks> /// <param name="leaderboardId">Leaderboard Id</param> /// <param name="callback">Callback to invoke when completed.</param> public void LoadScores(string leaderboardId, Action<IScore[]> callback) { LoadScores( leaderboardId, LeaderboardStart.PlayerCentered, mClient.LeaderboardMaxResults(), LeaderboardCollection.Public, LeaderboardTimeSpan.AllTime, (scoreData) => callback(scoreData.Scores)); } /// <summary> /// Loads the scores using the provided parameters. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="start">Start either top scores, or player centered.</param> /// <param name="rowCount">Row count. the number of rows to return.</param> /// <param name="collection">Collection. social or public</param> /// <param name="timeSpan">Time span. daily, weekly, all-time</param> /// <param name="callback">Callback to invoke when completed.</param> public void LoadScores( string leaderboardId, LeaderboardStart start, int rowCount, LeaderboardCollection collection, LeaderboardTimeSpan timeSpan, Action<LeaderboardScoreData> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadScores can only be called after authentication."); callback(new LeaderboardScoreData( leaderboardId, ResponseStatus.NotAuthorized)); return; } mClient.LoadScores( leaderboardId, start, rowCount, collection, timeSpan, callback); } /// <summary> /// Loads more scores. /// </summary> /// <remarks>This is used to load the next "page" of scores. </remarks> /// <param name="token">Token used to recording the loading.</param> /// <param name="rowCount">Row count.</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadMoreScores( ScorePageToken token, int rowCount, Action<LeaderboardScoreData> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadMoreScores can only be called after authentication."); callback( new LeaderboardScoreData( token.LeaderboardId, ResponseStatus.NotAuthorized)); return; } mClient.LoadMoreScores(token, rowCount, callback); } /// <summary> /// Returns a leaderboard object that can be configured to /// load scores. /// </summary> /// <returns>The leaderboard object.</returns> public ILeaderboard CreateLeaderboard() { return new PlayGamesLeaderboard(mDefaultLbUi); } /// <summary> /// Shows the standard Google Play Games achievements user interface, /// which allows the player to browse their achievements. /// </summary> public void ShowAchievementsUI() { ShowAchievementsUI(null); } /// <summary> /// Shows the standard Google Play Games achievements user interface, /// which allows the player to browse their achievements. /// </summary> /// <param name="callback">If non-null, the callback is invoked when /// the achievement UI is dismissed</param> public void ShowAchievementsUI(Action<UIStatus> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ShowAchievementsUI can only be called after authentication."); return; } GooglePlayGames.OurUtils.Logger.d("ShowAchievementsUI callback is " + callback); mClient.ShowAchievementsUI(callback); } /// <summary> /// Shows the standard Google Play Games leaderboards user interface, /// which allows the player to browse their leaderboards. If you have /// configured a specific leaderboard as the default through a call to /// <see cref="SetDefaultLeaderboardForUi" />, the UI will show that /// specific leaderboard only. Otherwise, a list of all the leaderboards /// will be shown. /// </summary> public void ShowLeaderboardUI() { GooglePlayGames.OurUtils.Logger.d("ShowLeaderboardUI with default ID"); ShowLeaderboardUI(MapId(mDefaultLbUi), null); } /// <summary> /// Shows the standard Google Play Games leaderboard UI for the given /// leaderboard. /// </summary> /// <param name='leaderboardId'> /// The ID of the leaderboard to display. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> public void ShowLeaderboardUI(string leaderboardId) { if (leaderboardId != null) { leaderboardId = MapId(leaderboardId); } mClient.ShowLeaderboardUI(leaderboardId, LeaderboardTimeSpan.AllTime, null); } /// <summary> /// Shows the leaderboard UI and calls the specified callback upon /// completion. /// </summary> /// <param name="leaderboardId">leaderboard ID, can be null meaning all leaderboards.</param> /// <param name="callback">Callback to call. If null, nothing is called.</param> public void ShowLeaderboardUI(string leaderboardId, Action<UIStatus> callback) { ShowLeaderboardUI(leaderboardId, LeaderboardTimeSpan.AllTime, callback); } /// <summary> /// Shows the leaderboard UI and calls the specified callback upon /// completion. /// </summary> /// <param name="leaderboardId">leaderboard ID, can be null meaning all leaderboards.</param> /// <param name="span">Timespan to display scores in the leaderboard.</param> /// <param name="callback">Callback to call. If null, nothing is called.</param> public void ShowLeaderboardUI( string leaderboardId, LeaderboardTimeSpan span, Action<UIStatus> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ShowLeaderboardUI can only be called after authentication."); if (callback != null) { callback(UIStatus.NotAuthorized); } return; } GooglePlayGames.OurUtils.Logger.d("ShowLeaderboardUI, lbId=" + leaderboardId + " callback is " + callback); mClient.ShowLeaderboardUI(leaderboardId, span, callback); } /// <summary> /// Sets the default leaderboard for the leaderboard UI. After calling this /// method, a call to <see cref="ShowLeaderboardUI" /> will show only the specified /// leaderboard instead of showing the list of all leaderboards. /// </summary> /// <param name='lbid'> /// The ID of the leaderboard to display on the default UI. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> public void SetDefaultLeaderboardForUI(string lbid) { GooglePlayGames.OurUtils.Logger.d("SetDefaultLeaderboardForUI: " + lbid); if (lbid != null) { lbid = MapId(lbid); } mDefaultLbUi = lbid; } /// <summary> /// Loads the friends that also play this game. See loadConnectedPlayers. /// </summary> /// <remarks>This is a callback variant of LoadFriends. When completed, /// the friends list set in the user object, so they can accessed via the /// friends property as needed. /// </remarks> /// <param name="user">The current local user</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadFriends(ILocalUser user, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "LoadScores can only be called after authentication."); if (callback != null) { callback(false); } } mClient.LoadFriends(callback); } /// <summary> /// Loads the leaderboard based on the constraints in the leaderboard /// object. /// </summary> /// <param name="board">The leaderboard object. This is created by /// calling CreateLeaderboard(), and then initialized appropriately.</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadScores(ILeaderboard board, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadScores can only be called after authentication."); if (callback != null) { callback(false); } } LeaderboardTimeSpan timeSpan; switch (board.timeScope) { case TimeScope.AllTime: timeSpan = LeaderboardTimeSpan.AllTime; break; case TimeScope.Week: timeSpan = LeaderboardTimeSpan.Weekly; break; case TimeScope.Today: timeSpan = LeaderboardTimeSpan.Daily; break; default: timeSpan = LeaderboardTimeSpan.AllTime; break; } ((PlayGamesLeaderboard)board).loading = true; GooglePlayGames.OurUtils.Logger.d("LoadScores, board=" + board + " callback is " + callback); mClient.LoadScores( board.id, LeaderboardStart.PlayerCentered, board.range.count > 0 ? board.range.count : mClient.LeaderboardMaxResults(), board.userScope == UserScope.FriendsOnly ? LeaderboardCollection.Social : LeaderboardCollection.Public, timeSpan, (scoreData) => HandleLoadingScores( (PlayGamesLeaderboard)board, scoreData, callback)); } /// <summary> /// Check if the leaderboard is currently loading. /// </summary> /// <returns><c>true</c>, if loading was gotten, <c>false</c> otherwise.</returns> /// <param name="board">The leaderboard to check for loading in progress</param> public bool GetLoading(ILeaderboard board) { return board != null && board.loading; } /// <summary> /// Register an invitation delegate to be /// notified when a multiplayer invitation arrives /// </summary> /// <param name="deleg">The delegate to register</param> public void RegisterInvitationDelegate(InvitationReceivedDelegate deleg) { mClient.RegisterInvitationDelegate(deleg); } /// <summary> /// Retrieves a bearer token associated with the current account. /// </summary> /// <returns>A bearer token for authorized requests.</returns> public string GetToken() { return mClient.GetToken(); } /// <summary> /// Handles the processing of scores during loading. /// </summary> /// <param name="board">leaderboard being loaded</param> /// <param name="scoreData">Score data.</param> /// <param name="callback">Callback invoked when complete.</param> internal void HandleLoadingScores( PlayGamesLeaderboard board, LeaderboardScoreData scoreData, Action<bool> callback) { bool ok = board.SetFromData(scoreData); if (ok && !board.HasAllScores() && scoreData.NextPageToken != null) { int rowCount = board.range.count - board.ScoreCount; // need to load more scores mClient.LoadMoreScores( scoreData.NextPageToken, rowCount, (nextScoreData) => HandleLoadingScores(board, nextScoreData, callback)); } else { callback(ok); } } /// <summary> /// Internal implmentation of getFriends.Gets the friends. /// </summary> /// <returns>The friends.</returns> internal IUserProfile[] GetFriends() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.d("Cannot get friends when not authenticated!"); return new IUserProfile[0]; } return mClient.GetFriends(); } /// <summary> /// Maps the alias to the identifier. /// </summary> /// <remarks>This maps an aliased ID to the actual id. The intent of /// this method is to allow easy to read constants to be used instead of /// the generated ids. /// </remarks> /// <returns>The identifier, or null if not found.</returns> /// <param name="id">Alias to map</param> private string MapId(string id) { if (id == null) { return null; } if (mIdMap.ContainsKey(id)) { string result = mIdMap[id]; GooglePlayGames.OurUtils.Logger.d("Mapping alias " + id + " to ID " + result); return result; } return id; } public void Authenticate(ILocalUser user, Action<bool, string> callback) { throw new NotImplementedException(); } } } #endif
// AssemblyListControl.cs // // 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.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.IO; using System.Reflection; using System.Diagnostics; using System.Runtime.InteropServices; using NDoc.Core; namespace NDoc.Gui { /// <summary> /// Control that displays the Assemblies in a project /// </summary> public class AssemblyListControl : UserControl { private System.Windows.Forms.ListView assembliesListView; private System.Windows.Forms.Button editButton; private System.Windows.Forms.Button namespaceSummariesButton; private System.Windows.Forms.Button deleteButton; private System.Windows.Forms.ColumnHeader nameColumnHeader; private System.Windows.Forms.ColumnHeader pathColumnHeader; private System.Windows.Forms.Button addButton; private System.Windows.Forms.ContextMenu itemContextMenu1; private System.Windows.Forms.MenuItem editMenuItem1; private System.Windows.Forms.MenuItem removeMenuItem2; private System.Windows.Forms.ContextMenu blankSpaceContextMenu; private System.Windows.Forms.MenuItem detailsMenuItem1; private System.Windows.Forms.MenuItem listMenuItem2; private System.Windows.Forms.MenuItem exploreMenuItem1; private System.Windows.Forms.ColumnHeader fixedColumnHeader1; private System.Windows.Forms.MenuItem propertiesMenuItem1; private System.Windows.Forms.MenuItem menuItem1; private AssemblySlashDocCollection _AssemblySlashDocs; /// <summary> /// Creates an isntance of the class /// </summary> public AssemblyListControl() { InitializeComponent(); } /// <summary> /// Gets the collection of assemblies and documentation comment XML files in the project. /// </summary> /// <value>An <see cref="AssemblySlashDocCollection"/>.</value> public AssemblySlashDocCollection AssemblySlashDocs { get { return _AssemblySlashDocs; } set { this.assembliesListView.Items.Clear(); if ( _AssemblySlashDocs != null ) { _AssemblySlashDocs.ItemAdded -= new AssemblySlashDocEventHandler(_AssemblySlashDocs_ItemAdded); _AssemblySlashDocs.ItemRemoved -= new AssemblySlashDocEventHandler(_AssemblySlashDocs_ItemRemoved); _AssemblySlashDocs.Cleared -= new EventHandler(_AssemblySlashDocs_Cleared); } _AssemblySlashDocs = value; if ( _AssemblySlashDocs != null ) { _AssemblySlashDocs.ItemAdded += new AssemblySlashDocEventHandler(_AssemblySlashDocs_ItemAdded); _AssemblySlashDocs.ItemRemoved += new AssemblySlashDocEventHandler(_AssemblySlashDocs_ItemRemoved); _AssemblySlashDocs.Cleared += new EventHandler(_AssemblySlashDocs_Cleared); this.assembliesListView.BeginUpdate(); foreach ( AssemblySlashDoc assemblySlashDoc in _AssemblySlashDocs ) AddListViewItem( assemblySlashDoc ); this.assembliesListView.EndUpdate(); } } } /// <summary> /// See <see cref="Control.Refresh"/> /// </summary> public override void Refresh() { foreach ( ListViewItem item in this.assembliesListView.Items ) { AssemblySlashDoc assemblySlashDoc = item.Tag as AssemblySlashDoc; Debug.Assert( assemblySlashDoc != null ); if ( File.Exists( assemblySlashDoc.Assembly.Path ) ) item.ForeColor = Color.Black; else item.ForeColor = Color.Red; } base.Refresh (); } private void AddListViewItem( AssemblySlashDoc assemblySlashDoc ) { Debug.Assert( assemblySlashDoc != null ); ListViewItem item = new ListViewItem( Path.GetFileName( assemblySlashDoc.Assembly.Path ) ); item.SubItems.Add( Path.GetDirectoryName( assemblySlashDoc.Assembly.Path ) ); item.SubItems.Add( GetFixedPathType( assemblySlashDoc ) ); item.Tag = assemblySlashDoc; if ( File.Exists( assemblySlashDoc.Assembly.Path ) == false ) item.ForeColor = Color.Red; assembliesListView.Items.Add( item ); item.EnsureVisible(); } #region InitializComponent private void InitializeComponent() { this.assembliesListView = new System.Windows.Forms.ListView(); this.nameColumnHeader = new System.Windows.Forms.ColumnHeader(); this.pathColumnHeader = new System.Windows.Forms.ColumnHeader(); this.fixedColumnHeader1 = new System.Windows.Forms.ColumnHeader(); this.itemContextMenu1 = new System.Windows.Forms.ContextMenu(); this.editMenuItem1 = new System.Windows.Forms.MenuItem(); this.removeMenuItem2 = new System.Windows.Forms.MenuItem(); this.exploreMenuItem1 = new System.Windows.Forms.MenuItem(); this.propertiesMenuItem1 = new System.Windows.Forms.MenuItem(); this.editButton = new System.Windows.Forms.Button(); this.namespaceSummariesButton = new System.Windows.Forms.Button(); this.deleteButton = new System.Windows.Forms.Button(); this.addButton = new System.Windows.Forms.Button(); this.blankSpaceContextMenu = new System.Windows.Forms.ContextMenu(); this.detailsMenuItem1 = new System.Windows.Forms.MenuItem(); this.listMenuItem2 = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // assembliesListView // this.assembliesListView.AllowDrop = true; this.assembliesListView.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.assembliesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.nameColumnHeader, this.pathColumnHeader, this.fixedColumnHeader1}); this.assembliesListView.ContextMenu = this.itemContextMenu1; this.assembliesListView.ForeColor = System.Drawing.SystemColors.WindowText; this.assembliesListView.FullRowSelect = true; this.assembliesListView.GridLines = true; this.assembliesListView.HideSelection = false; this.assembliesListView.Location = new System.Drawing.Point(0, 0); this.assembliesListView.Name = "assembliesListView"; this.assembliesListView.Size = new System.Drawing.Size(368, 136); this.assembliesListView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.assembliesListView.TabIndex = 18; this.assembliesListView.View = System.Windows.Forms.View.Details; this.assembliesListView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.assembliesListView_MouseDown); this.assembliesListView.ItemActivate += new System.EventHandler(this.assembliesListView_ItemActivate); this.assembliesListView.DragDrop += new System.Windows.Forms.DragEventHandler(this.assembliesListView_DragDrop); this.assembliesListView.DragEnter += new System.Windows.Forms.DragEventHandler(this.assembliesListView_DragEnter); this.assembliesListView.SelectedIndexChanged += new System.EventHandler(this.assembliesListView_SelectedIndexChanged); // // nameColumnHeader // this.nameColumnHeader.Text = "Assembly"; this.nameColumnHeader.Width = 96; // // pathColumnHeader // this.pathColumnHeader.Text = "Path"; this.pathColumnHeader.Width = 236; // // fixedColumnHeader1 // this.fixedColumnHeader1.Text = "Fixed"; this.fixedColumnHeader1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // itemContextMenu1 // this.itemContextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.editMenuItem1, this.removeMenuItem2, this.menuItem1, this.exploreMenuItem1, this.propertiesMenuItem1}); // // editMenuItem1 // this.editMenuItem1.DefaultItem = true; this.editMenuItem1.Index = 0; this.editMenuItem1.Text = "Edit..."; this.editMenuItem1.Click += new System.EventHandler(this.editMenuItem1_Click); // // removeMenuItem2 // this.removeMenuItem2.Index = 1; this.removeMenuItem2.Text = "Remove"; this.removeMenuItem2.Click += new System.EventHandler(this.removeMenuItem2_Click); // // exploreMenuItem1 // this.exploreMenuItem1.Index = 3; this.exploreMenuItem1.Text = "Find..."; this.exploreMenuItem1.Click += new System.EventHandler(this.exploreMenuItem1_Click); // // propertiesMenuItem1 // this.propertiesMenuItem1.Index = 4; this.propertiesMenuItem1.Text = "Properties..."; this.propertiesMenuItem1.Click += new System.EventHandler(this.propertiesMenuItem1_Click); // // editButton // this.editButton.Anchor = System.Windows.Forms.AnchorStyles.Right; this.editButton.Enabled = false; this.editButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.editButton.Location = new System.Drawing.Point(376, 36); this.editButton.Name = "editButton"; this.editButton.Size = new System.Drawing.Size(88, 24); this.editButton.TabIndex = 20; this.editButton.Text = "Edit"; this.editButton.Click += new System.EventHandler(this.editButton_Click); // // namespaceSummariesButton // this.namespaceSummariesButton.Anchor = System.Windows.Forms.AnchorStyles.Right; this.namespaceSummariesButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.namespaceSummariesButton.Location = new System.Drawing.Point(376, 100); this.namespaceSummariesButton.Name = "namespaceSummariesButton"; this.namespaceSummariesButton.Size = new System.Drawing.Size(88, 32); this.namespaceSummariesButton.TabIndex = 22; this.namespaceSummariesButton.Text = "Namespace\nSummaries"; this.namespaceSummariesButton.Click += new System.EventHandler(this.namespaceSummariesButton_Click); // // deleteButton // this.deleteButton.Anchor = System.Windows.Forms.AnchorStyles.Right; this.deleteButton.Enabled = false; this.deleteButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.deleteButton.Location = new System.Drawing.Point(376, 68); this.deleteButton.Name = "deleteButton"; this.deleteButton.Size = new System.Drawing.Size(88, 24); this.deleteButton.TabIndex = 21; this.deleteButton.Text = "Remove"; this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click); // // addButton // this.addButton.Anchor = System.Windows.Forms.AnchorStyles.Right; this.addButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.addButton.Location = new System.Drawing.Point(376, 4); this.addButton.Name = "addButton"; this.addButton.Size = new System.Drawing.Size(88, 24); this.addButton.TabIndex = 19; this.addButton.Text = "Add"; this.addButton.Click += new System.EventHandler(this.addButton_Click); // // blankSpaceContextMenu // this.blankSpaceContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.detailsMenuItem1, this.listMenuItem2}); // // detailsMenuItem1 // this.detailsMenuItem1.Index = 0; this.detailsMenuItem1.Text = "Details"; this.detailsMenuItem1.Click += new System.EventHandler(this.detailsMenuItem1_Click); // // listMenuItem2 // this.listMenuItem2.Index = 1; this.listMenuItem2.Text = "List"; this.listMenuItem2.Click += new System.EventHandler(this.listMenuItem2_Click); // // menuItem1 // this.menuItem1.Index = 2; this.menuItem1.Text = "-"; // // AssemblyListControl // this.Controls.Add(this.assembliesListView); this.Controls.Add(this.editButton); this.Controls.Add(this.namespaceSummariesButton); this.Controls.Add(this.deleteButton); this.Controls.Add(this.addButton); this.Name = "AssemblyListControl"; this.Size = new System.Drawing.Size(464, 136); this.ResumeLayout(false); } #endregion private void assembliesListView_SelectedIndexChanged(object sender, System.EventArgs e) { editButton.Enabled = assembliesListView.SelectedIndices.Count > 0; deleteButton.Enabled = assembliesListView.SelectedIndices.Count > 0; } private void addButton_Click (object sender, System.EventArgs e) { using ( AssemblySlashDocForm form = new AssemblySlashDocForm() ) { form.Text = "Add Assembly Filename and XML Documentation Filename"; form.StartPosition = FormStartPosition.CenterParent; if ( form.ShowDialog( this ) == System.Windows.Forms.DialogResult.OK ) { if ( this._AssemblySlashDocs.Contains( form.AssySlashDoc ) ) MessageBox.Show( this, "The selected assembly already exists in this project", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Asterisk ); else _AssemblySlashDocs.Add( form.AssySlashDoc ); } } } private void editButton_Click (object sender, System.EventArgs e) { if ( assembliesListView.SelectedItems.Count > 0 ) { using ( AssemblySlashDocForm form = new AssemblySlashDocForm() ) { form.Text = "Edit Assembly Filename and XML Documentation Filename"; form.StartPosition = FormStartPosition.CenterParent; ListViewItem item = assembliesListView.SelectedItems[0]; form.AssySlashDoc = ((AssemblySlashDoc)item.Tag).Clone() as AssemblySlashDoc; if ( form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK ) { this.assembliesListView.BeginUpdate(); this._AssemblySlashDocs.Remove( (AssemblySlashDoc)item.Tag ); this._AssemblySlashDocs.Add( form.AssySlashDoc ); this.assembliesListView.EndUpdate(); } } this.Refresh(); } } private static string GetFixedPathType( AssemblySlashDoc assemblySlashDoc ) { if ( assemblySlashDoc.Assembly.FixedPath == assemblySlashDoc.SlashDoc.FixedPath ) return assemblySlashDoc.Assembly.FixedPath.ToString(); else return string.Format( "{0}/{1}", assemblySlashDoc.Assembly.FixedPath, assemblySlashDoc.SlashDoc.FixedPath ); } /// <summary> /// Removes the selected assembly and /doc file pair from the listview. /// </summary> /// <remarks> /// If the row being deleted was the only one left in the listview then /// the documentation buttons are disabled. /// </remarks> /// <param name="sender">The sender (not used).</param> /// <param name="e">The event arguments (not used).</param> private void deleteButton_Click (object sender, System.EventArgs e) { this.assembliesListView.BeginUpdate(); foreach(ListViewItem listViewItem in assembliesListView.SelectedItems) _AssemblySlashDocs.Remove( listViewItem.Tag as AssemblySlashDoc ); if ( this.assembliesListView.Items.Count > 0 ) { this.assembliesListView.Items[0].Selected = true; this.assembliesListView.Items[0].EnsureVisible(); } this.assembliesListView.EndUpdate(); } /// <summary> /// Event raised when the "Edit Namespace" button is clicked /// </summary> public event EventHandler EditNamespaces; /// <summary> /// Raises the <see cref="EditNamespaces"/> event /// </summary> protected virtual void OnEditNamespaces() { if ( EditNamespaces != null ) EditNamespaces( this, EventArgs.Empty ); } /// <summary> /// Brings up the form for entering namespace summaries. /// </summary> /// <remarks> /// Calls XmlDocumenter to build an XML file documenting the assemblies /// currently in the project. This file is used to discover all of the /// namespaces currently being documented in case any new ones have been /// added. A <see cref="System.Collections.Hashtable"/> with the namespace /// names as keys and any existing summaries as values is passed in to /// a form which allows editing of the namespace summaries. If the ok button /// is selected in the form then the Hashtable becomes the main one used by /// NDoc and passed into documenters for building documentation. /// </remarks> /// <param name="sender">The sender (not used).</param> /// <param name="e">The event arguments (not used).</param> private void namespaceSummariesButton_Click (object sender, System.EventArgs e) { OnEditNamespaces(); } private void assembliesListView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { this.assembliesListView.BeginUpdate(); string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach ( AssemblySlashDoc assemblySlashDoc in DragDropHandler.GetAssemblySlashDocs( files ) ) { if ( _AssemblySlashDocs.Contains( assemblySlashDoc ) == false ) _AssemblySlashDocs.Add( assemblySlashDoc ); } this.assembliesListView.EndUpdate(); } private void assembliesListView_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { if( e.Data.GetDataPresent(DataFormats.FileDrop) && DragDropHandler.CanDrop( (string[])e.Data.GetData( DataFormats.FileDrop ) ) == DropFileType.Assembly ) e.Effect = DragDropEffects.Link; else e.Effect = DragDropEffects.None; } private void assembliesListView_ItemActivate(object sender, System.EventArgs e) { editButton_Click(sender, e); } private void _AssemblySlashDocs_ItemAdded(object sender, AssemblySlashDocEventArgs args) { AddListViewItem( args.AssemblySlashDoc ); } private void _AssemblySlashDocs_ItemRemoved(object sender, AssemblySlashDocEventArgs args) { foreach ( ListViewItem item in this.assembliesListView.Items ) { if ( item.Tag == args.AssemblySlashDoc ) { item.Remove(); break; } } } private void _AssemblySlashDocs_Cleared(object sender, EventArgs e) { this.assembliesListView.Items.Clear(); } private void assembliesListView_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if ( e.Button == MouseButtons.Right ) { ListViewItem item = assembliesListView.GetItemAt( e.X, e.Y ); if ( item != null ) assembliesListView.ContextMenu = this.itemContextMenu1; else assembliesListView.ContextMenu = this.blankSpaceContextMenu; } } private void editMenuItem1_Click(object sender, System.EventArgs e) { editButton_Click( sender, e ); } private void removeMenuItem2_Click(object sender, System.EventArgs e) { deleteButton_Click( sender, e ); } /// <summary> /// Event raised when the <see cref="DetailsView"/> property changes /// </summary> public event EventHandler DetailsViewChanged; /// <summary> /// Raises the <see cref="DetailsViewChanged"/> event /// </summary> protected virtual void OnDetailsViewChanged() { if ( DetailsViewChanged != null ) DetailsViewChanged( this, EventArgs.Empty ); } /// <summary> /// Determines if the ListView is in report or list mode /// </summary> public bool DetailsView { get { return this.assembliesListView.View == View.Details; } set { if ( value ) this.assembliesListView.View = View.Details; else this.assembliesListView.View = View.List; this.detailsMenuItem1.Enabled = !value; this.listMenuItem2.Enabled = value; OnDetailsViewChanged(); } } private void detailsMenuItem1_Click(object sender, System.EventArgs e) { DetailsView = true; } private void listMenuItem2_Click(object sender, System.EventArgs e) { DetailsView = false; } private void exploreMenuItem1_Click(object sender, System.EventArgs e) { if ( this.assembliesListView.SelectedIndices.Count > 0 ) { string path = ((AssemblySlashDoc)this.assembliesListView.SelectedItems[0].Tag).Assembly.Path; if ( File.Exists( path ) ) Process.Start( Path.GetDirectoryName( Path.GetFullPath( path ) ) ); else MessageBox.Show( this, string.Format( "Could not find the file:\n{0}", path ), "File not found", MessageBoxButtons.OK, MessageBoxIcon.Information ); } } [DllImport("shell32.dll")] private static extern bool SHObjectProperties( IntPtr hwnd, int dwType, IntPtr szObject, IntPtr szPage ); private const int SHOP_FILEPATH = 2; private void propertiesMenuItem1_Click(object sender, System.EventArgs e) { if ( this.assembliesListView.SelectedIndices.Count > 0 ) { string path = ((AssemblySlashDoc)this.assembliesListView.SelectedItems[0].Tag).Assembly.Path; if ( File.Exists( path ) ) { IntPtr szObject = Marshal.StringToHGlobalUni( path ); if ( szObject != IntPtr.Zero ) { SHObjectProperties( this.Handle, SHOP_FILEPATH, szObject, IntPtr.Zero ); Marshal.FreeHGlobal( szObject ); } else { string msg = string.Format( "Could not find the file:\n{0}", path ); MessageBox.Show( this, msg, "File not found", MessageBoxButtons.OK, MessageBoxIcon.Information ); } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; public static class YamlViewModelExtensions { public static bool IsPageLevel(this MemberType type) { return type == MemberType.Namespace || type == MemberType.Class || type == MemberType.Enum || type == MemberType.Delegate || type == MemberType.Interface || type == MemberType.Struct; } /// <summary> /// Allow multiple items in one yml file /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool AllowMultipleItems(this MemberType type) { return type == MemberType.Class || type == MemberType.Enum || type == MemberType.Delegate || type == MemberType.Interface || type == MemberType.Struct; } public static MetadataItem ShrinkToSimpleToc(this MetadataItem item) { MetadataItem shrinkedItem = new MetadataItem(); shrinkedItem.Name = item.Name; shrinkedItem.DisplayNames = item.DisplayNames; shrinkedItem.Items = null; if (item.Items == null) { return shrinkedItem; } if (item.Type == MemberType.Toc || item.Type == MemberType.Namespace) { foreach (var i in item.Items) { if (shrinkedItem.Items == null) { shrinkedItem.Items = new List<MetadataItem>(); } if (i.IsInvalid) continue; var shrinkedI = i.ShrinkToSimpleToc(); shrinkedItem.Items.Add(shrinkedI); } } return shrinkedItem; } /// <summary> /// Only when Namespace is not empty, return it /// </summary> /// <param name="item"></param> /// <returns></returns> public static MetadataItem ShrinkToSimpleTocWithNamespaceNotEmpty(this MetadataItem item) { MetadataItem shrinkedItem = new MetadataItem(); shrinkedItem.Name = item.Name; shrinkedItem.DisplayNames = item.DisplayNames; shrinkedItem.Type = item.Type; shrinkedItem.Items = null; if (item.Type == MemberType.Toc || item.Type == MemberType.Namespace) { if (item.Items != null) { foreach (var i in item.Items) { if (shrinkedItem.Items == null) { shrinkedItem.Items = new List<MetadataItem>(); } if (i.IsInvalid) continue; var shrinkedI = i.ShrinkToSimpleTocWithNamespaceNotEmpty(); if (shrinkedI != null) shrinkedItem.Items.Add(shrinkedI); } } } if (item.Type == MemberType.Namespace) { if (shrinkedItem.Items == null || shrinkedItem.Items.Count == 0) return null; } return shrinkedItem; } public static TocViewModel ToTocViewModel(this MetadataItem item) { if (item == null) { Debug.Fail("item is null."); return null; } switch (item.Type) { case MemberType.Toc: case MemberType.Namespace: var result = new List<TocItemViewModel>(); foreach (var child in item.Items) { result.Add(child.ToTocItemViewModel()); } return new TocViewModel(result.OrderBy(s => s.Name)); default: return null; } } public static TocItemViewModel ToTocItemViewModel(this MetadataItem item) { var result = new TocItemViewModel { Uid = item.Name, Name = item.DisplayNames.GetLanguageProperty(SyntaxLanguage.Default), }; var nameForCSharp = item.DisplayNames.GetLanguageProperty(SyntaxLanguage.CSharp); if (nameForCSharp != result.Name) { result.NameForCSharp = nameForCSharp; } var nameForVB = item.DisplayNames.GetLanguageProperty(SyntaxLanguage.VB); if (nameForVB != result.Name) { result.NameForVB = nameForVB; } if (item.Items != null) { result.Items = item.ToTocViewModel(); } return result; } public static PageViewModel ToPageViewModel(this MetadataItem model) { if (model == null) { return null; } var result = new PageViewModel(); result.Items.Add(model.ToItemViewModel()); if (model.Type.AllowMultipleItems()) { AddChildren(model, result); } foreach (var item in model.References) { result.References.Add(item.ToReferenceViewModel()); } return result; } public static ReferenceViewModel ToReferenceViewModel(this KeyValuePair<string, ReferenceItem> model) { Debug.Assert(model.Value != null, "Unexpected reference."); var result = new ReferenceViewModel { Uid = model.Key, CommentId = model.Value.CommentId, Parent = model.Value.Parent, Definition = model.Value.Definition, }; if (model.Value.Parts != null && model.Value.Parts.Count > 0) { result.Name = GetName(model.Value, SyntaxLanguage.Default, l => l.DisplayName); var nameForCSharp = GetName(model.Value, SyntaxLanguage.CSharp, l => l.DisplayName); if (result.Name != nameForCSharp) { result.NameInDevLangs[Constants.DevLang.CSharp] = nameForCSharp; } var nameForVB = GetName(model.Value, SyntaxLanguage.VB, l => l.DisplayName); if (result.Name != nameForVB) { result.NameInDevLangs[Constants.DevLang.VB] = nameForVB; } result.NameWithType = GetName(model.Value, SyntaxLanguage.Default, l => l.DisplayNamesWithType); var nameWithTypeForCSharp = GetName(model.Value, SyntaxLanguage.CSharp, l => l.DisplayNamesWithType); if (result.NameWithType != nameWithTypeForCSharp) { result.NameWithTypeInDevLangs[Constants.DevLang.CSharp] = nameWithTypeForCSharp; } var nameWithTypeForVB = GetName(model.Value, SyntaxLanguage.VB, l => l.DisplayNamesWithType); if (result.NameWithType != nameWithTypeForVB) { result.NameWithTypeInDevLangs[Constants.DevLang.VB] = nameWithTypeForVB; } result.FullName = GetName(model.Value, SyntaxLanguage.Default, l => l.DisplayQualifiedNames); var fullnameForCSharp = GetName(model.Value, SyntaxLanguage.CSharp, l => l.DisplayQualifiedNames); if (result.FullName != fullnameForCSharp) { result.FullNameInDevLangs[Constants.DevLang.CSharp] = fullnameForCSharp; } var fullnameForVB = GetName(model.Value, SyntaxLanguage.VB, l => l.DisplayQualifiedNames); if (result.FullName != fullnameForVB) { result.FullNameInDevLangs[Constants.DevLang.VB] = fullnameForVB; } result.Specs[Constants.DevLang.CSharp] = GetSpec(model.Value, SyntaxLanguage.CSharp); result.Specs[Constants.DevLang.VB] = GetSpec(model.Value, SyntaxLanguage.VB); result.IsExternal = GetIsExternal(model.Value); result.Href = GetHref(model.Value); } return result; } public static ItemViewModel ToItemViewModel(this MetadataItem model) { if (model == null) { return null; } var result = new ItemViewModel { Uid = model.Name, CommentId = model.CommentId, IsExplicitInterfaceImplementation = model.IsExplicitInterfaceImplementation, IsExtensionMethod = model.IsExtensionMethod, Parent = model.Parent?.Name, Children = model.Items?.Select(x => x.Name).OrderBy(s => s).ToList(), Type = model.Type, Source = model.Source, Documentation = model.Documentation, AssemblyNameList = model.AssemblyNameList, NamespaceName = model.NamespaceName, Summary = model.Summary, Remarks = model.Remarks, Examples = model.Examples, Syntax = model.Syntax.ToSyntaxDetailViewModel(), Overridden = model.Overridden, Overload = model.Overload, Exceptions = model.Exceptions, Sees = model.Sees, SeeAlsos = model.SeeAlsos, DerivedClasses = model.DerivedClasses, Inheritance = model.Inheritance, Implements = model.Implements, InheritedMembers = model.InheritedMembers, ExtensionMethods = model.ExtensionMethods, Attributes = model.Attributes, }; result.Id = model.Name.Substring((model.Parent?.Name?.Length ?? -1) + 1); result.Name = model.DisplayNames.GetLanguageProperty(SyntaxLanguage.Default); var nameForCSharp = model.DisplayNames.GetLanguageProperty(SyntaxLanguage.CSharp); if (result.Name != nameForCSharp) { result.NameForCSharp = nameForCSharp; } var nameForVB = model.DisplayNames.GetLanguageProperty(SyntaxLanguage.VB); if (result.Name != nameForVB) { result.NameForVB = nameForVB; } result.NameWithType = model.DisplayNamesWithType.GetLanguageProperty(SyntaxLanguage.Default); var nameWithTypeForCSharp = model.DisplayNamesWithType.GetLanguageProperty(SyntaxLanguage.CSharp); if (result.NameWithType != nameWithTypeForCSharp) { result.NameWithTypeForCSharp = nameWithTypeForCSharp; } var nameWithTypeForVB = model.DisplayNamesWithType.GetLanguageProperty(SyntaxLanguage.VB); if (result.NameWithType != nameWithTypeForVB) { result.NameWithTypeForVB = nameWithTypeForVB; } result.FullName = model.DisplayQualifiedNames.GetLanguageProperty(SyntaxLanguage.Default); var fullnameForCSharp = model.DisplayQualifiedNames.GetLanguageProperty(SyntaxLanguage.CSharp); if (result.FullName != fullnameForCSharp) { result.FullNameForCSharp = fullnameForCSharp; } var fullnameForVB = model.DisplayQualifiedNames.GetLanguageProperty(SyntaxLanguage.VB); if (result.FullName != fullnameForVB) { result.FullNameForVB = fullnameForVB; } var modifierCSharp = model.Modifiers.GetLanguageProperty(SyntaxLanguage.CSharp); if (modifierCSharp?.Count > 0) { result.Modifiers["csharp"] = modifierCSharp; } var modifierForVB = model.Modifiers.GetLanguageProperty(SyntaxLanguage.VB); if (modifierForVB?.Count > 0) { result.Modifiers["vb"] = modifierForVB; } return result; } public static SyntaxDetailViewModel ToSyntaxDetailViewModel(this SyntaxDetail model) { if (model == null) { return null; } var result = new SyntaxDetailViewModel { Parameters = model.Parameters, TypeParameters = model.TypeParameters, Return = model.Return, }; if (model.Content != null && model.Content.Count > 0) { result.Content = model.Content.GetLanguageProperty(SyntaxLanguage.Default); var contentForCSharp = model.Content.GetLanguageProperty(SyntaxLanguage.CSharp); if (result.Content != contentForCSharp) { result.ContentForCSharp = contentForCSharp; } var contentForVB = model.Content.GetLanguageProperty(SyntaxLanguage.VB); if (result.Content != contentForVB) { result.ContentForVB = contentForVB; } } return result; } public static SpecViewModel ToSpecViewModel(this LinkItem model) { if (model == null) { return null; } var result = new SpecViewModel { Uid = model.Name, Name = model.DisplayName, NameWithType = model.DisplayNamesWithType, FullName = model.DisplayQualifiedNames, IsExternal = model.IsExternalPath, Href = model.Href, }; return result; } public static TValue GetLanguageProperty<TValue>(this SortedList<SyntaxLanguage, TValue> dict, SyntaxLanguage language, TValue defaultValue = null) where TValue : class { TValue result; if (dict.TryGetValue(language, out result)) { return result; } if (language == SyntaxLanguage.Default && dict.Count > 0) { return dict.Values[0]; } return defaultValue; } private static void AddChildren(MetadataItem model, PageViewModel result) { if (model.Items != null && model.Items.Count > 0) { foreach (var item in model.Items) { result.Items.Add(item.ToItemViewModel()); AddChildren(item, result); } } } private static string GetName(ReferenceItem reference, SyntaxLanguage language, Converter<LinkItem, string> getName) { var list = reference.Parts.GetLanguageProperty(language); if (list == null) { return null; } if (list.Count == 0) { Debug.Fail("Unexpected reference."); return null; } if (list.Count == 1) { return getName(list[0]); } return string.Concat(list.ConvertAll(item => getName(item)).ToArray()); } private static List<SpecViewModel> GetSpec(ReferenceItem reference, SyntaxLanguage language) { var list = reference.Parts.GetLanguageProperty(language); if (list == null || list.Count <= 1) { return null; } return list.ConvertAll(s => s.ToSpecViewModel()); } private static bool? GetIsExternal(ReferenceItem reference) { if (reference.IsDefinition != true) { return null; } foreach (var list in reference.Parts.Values) { foreach (var item in list) { if (item.IsExternalPath) { return true; } } } return false; } private static string GetHref(ReferenceItem reference) { foreach (var list in reference.Parts.Values) { foreach (var item in list) { if (item.Href != null) { return item.Href; } } } return null; } } }
#pragma warning disable 109, 114, 219, 429, 168, 162 public sealed class Array<T> : global::haxe.lang.HxObject, global::Array { public Array(T[] native) { this.__a = native; this.length = native.Length; } public Array(global::haxe.lang.EmptyObject empty) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" { } } #line default } public Array() { unchecked { #line 53 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<object>.__hx_ctor__Array<T>(this); } #line default } public static void __hx_ctor__Array<T_c>(global::Array<T_c> __temp_me4) { unchecked { #line 55 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" __temp_me4.length = 0; __temp_me4.__a = new T_c[((int) (0) )]; } #line default } public static object __hx_cast<T_c_c>(global::Array me) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ( (( me != default(global::Array) )) ? (me.Array_cast<T_c_c>()) : (default(global::Array)) ); } #line default } public static global::Array<X> ofNative<X>(X[] native) { return new Array<X>(native); } public static global::Array<Y> alloc<Y>(int size) { return new Array<Y>(new Y[size]); } public static new object __hx_createEmpty() { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::Array<object>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::Array<object>(); } #line default } public object Array_cast<T_c>() { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (global::haxe.lang.Runtime.eq(typeof(T), typeof(T_c))) { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this; } #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<T_c> new_me = new global::Array<T_c>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" object __temp_iterator137 = global::Reflect.fields(this).iterator(); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator137, "hasNext", 407283053, default(global::Array))) )) { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" string field = global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.callField(__temp_iterator137, "next", 1224901875, default(global::Array))); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" switch (field) { case "__a": { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T_c[] __temp_new_arr1 = new T_c[((int) (this.__a.Length) )]; #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int __temp_i2 = -1; #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" while (( ++ __temp_i2 < this.__a.Length )) { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" object __temp_obj3 = ((object) (this.__a[__temp_i2]) ); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if ( ! (global::haxe.lang.Runtime.eq(__temp_obj3, default(T[]))) ) { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" __temp_new_arr1[__temp_i2] = global::haxe.lang.Runtime.genericCast<T_c>(__temp_obj3); } } #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" new_me.__a = __temp_new_arr1; } #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } default: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Reflect.setField(new_me, field, ((object) (global::Reflect.field(this, field)) )); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } } } } #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new_me; } #line default } public int length; public T[] __a; public global::Array<T> concat(global::Array<T> a) { unchecked { #line 61 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int len = ( this.length + a.length ); T[] retarr = new T[((int) (len) )]; global::System.Array.Copy(((global::System.Array) (this.__a) ), ((int) (0) ), ((global::System.Array) (retarr) ), ((int) (0) ), ((int) (this.length) )); global::System.Array.Copy(((global::System.Array) (a.__a) ), ((int) (0) ), ((global::System.Array) (retarr) ), ((int) (this.length) ), ((int) (a.length) )); #line 66 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return global::Array<object>.ofNative<T>(retarr); } #line default } public void concatNative(T[] a) { unchecked { #line 71 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] __a = this.__a; int len = ( this.length + ( a as global::System.Array ).Length ); if (( ( __a as global::System.Array ).Length >= len )) { #line 75 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::System.Array.Copy(((global::System.Array) (a) ), ((int) (0) ), ((global::System.Array) (__a) ), ((int) (this.length) ), ((int) (this.length) )); } else { #line 77 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] newarr = new T[((int) (len) )]; global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (0) ), ((global::System.Array) (newarr) ), ((int) (0) ), ((int) (this.length) )); global::System.Array.Copy(((global::System.Array) (a) ), ((int) (0) ), ((global::System.Array) (newarr) ), ((int) (this.length) ), ((int) (( a as global::System.Array ).Length) )); #line 81 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a = newarr; } #line 84 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.length = len; } #line default } public string @join(string sep) { unchecked { #line 89 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::StringBuf buf = new global::StringBuf(); int i = -1; #line 92 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" bool first = true; int length = this.length; while (( ++ i < length )) { #line 96 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (first) { first = false; } else { #line 99 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" buf.b.Append(((object) (global::Std.@string(sep)) )); } buf.b.Append(((object) (global::Std.@string(this.__a[i])) )); } #line 103 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return buf.toString(); } #line default } public global::haxe.lang.Null<T> pop() { unchecked { #line 108 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] __a = this.__a; int length = this.length; if (( length > 0 )) { #line 112 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T val = __a[ -- length]; __a[length] = default(T); this.length = length; #line 116 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::haxe.lang.Null<T>(val, true); } else { #line 118 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return default(global::haxe.lang.Null<T>); } } #line default } public int push(T x) { unchecked { #line 124 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( this.length >= ( this.__a as global::System.Array ).Length )) { #line 126 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int newLen = ( (( this.length << 1 )) + 1 ); T[] newarr = new T[((int) (newLen) )]; ( this.__a as global::System.Array ).CopyTo(((global::System.Array) (newarr) ), ((int) (0) )); #line 130 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a = newarr; } #line 133 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a[this.length] = x; return ++ this.length; } #line default } public void reverse() { unchecked { #line 139 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int i = 0; int l = this.length; T[] a = this.__a; int half = ( l >> 1 ); l -= 1; while (( i < half )) { #line 146 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T tmp = a[i]; a[i] = a[( l - i )]; a[( l - i )] = tmp; i += 1; } } #line default } public global::haxe.lang.Null<T> shift() { unchecked { #line 155 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int l = this.length; if (( l == 0 )) { return default(global::haxe.lang.Null<T>); } #line 159 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] a = this.__a; T x = a[0]; l -= 1; global::System.Array.Copy(((global::System.Array) (a) ), ((int) (1) ), ((global::System.Array) (a) ), ((int) (0) ), ((int) (( this.length - 1 )) )); a[l] = default(T); this.length = l; #line 166 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::haxe.lang.Null<T>(x, true); } #line default } public global::Array<T> slice(int pos, global::haxe.lang.Null<int> end) { unchecked { #line 171 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( pos < 0 )) { pos = ( this.length + pos ); if (( pos < 0 )) { pos = 0; } } #line 176 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (global::haxe.lang.Runtime.eq((end).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) { end = new global::haxe.lang.Null<int>(new global::haxe.lang.Null<int>(this.length, true).@value, true); } else { if (( end.@value < 0 )) { end = new global::haxe.lang.Null<int>(new global::haxe.lang.Null<int>(( this.length + end.@value ), true).@value, true); } } if (( end.@value > this.length )) { end = new global::haxe.lang.Null<int>(new global::haxe.lang.Null<int>(this.length, true).@value, true); } int len = ( end.@value - pos ); if (( len < 0 )) { #line 183 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::Array<T>(); } #line 185 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] newarr = new T[((int) (len) )]; global::System.Array.Copy(((global::System.Array) (this.__a) ), ((int) (pos) ), ((global::System.Array) (newarr) ), ((int) (0) ), ((int) (len) )); #line 188 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return global::Array<object>.ofNative<T>(newarr); } #line default } public void sort(global::haxe.lang.Function f) { unchecked { #line 193 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( this.length == 0 )) { return ; } this.quicksort(0, ( this.length - 1 ), f); } #line default } public void quicksort(int lo, int hi, global::haxe.lang.Function f) { unchecked { #line 200 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] buf = this.__a; int i = lo; #line 201 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int j = hi; T p = buf[( ( i + j ) >> 1 )]; while (( i <= j )) { #line 205 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" while (( ((int) (f.__hx_invoke2_f(default(double), default(double), buf[i], p)) ) < 0 )) { #line 205 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" i++; } while (( ((int) (f.__hx_invoke2_f(default(double), default(double), buf[j], p)) ) > 0 )) { #line 206 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" j--; } if (( i <= j )) { #line 209 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T t = buf[i]; buf[i++] = buf[j]; buf[j--] = t; } } #line 215 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( lo < j )) { #line 215 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.quicksort(lo, j, f); } if (( i < hi )) { #line 216 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.quicksort(i, hi, f); } } #line default } public global::Array<T> splice(int pos, int len) { unchecked { #line 221 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( len < 0 )) { #line 221 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::Array<T>(); } if (( pos < 0 )) { pos = ( this.length + pos ); if (( pos < 0 )) { #line 224 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" pos = 0; } } #line 226 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( pos > this.length )) { pos = 0; len = 0; } else { if (( ( pos + len ) > this.length )) { len = ( this.length - pos ); if (( len < 0 )) { #line 231 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" len = 0; } } } #line 233 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] a = this.__a; #line 235 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] ret = new T[((int) (len) )]; global::System.Array.Copy(((global::System.Array) (a) ), ((int) (pos) ), ((global::System.Array) (ret) ), ((int) (0) ), ((int) (len) )); global::Array<T> ret1 = global::Array<object>.ofNative<T>(ret); #line 239 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int end = ( pos + len ); global::System.Array.Copy(((global::System.Array) (a) ), ((int) (end) ), ((global::System.Array) (a) ), ((int) (pos) ), ((int) (( this.length - end )) )); this.length -= len; while (( -- len >= 0 )) { a[( this.length + len )] = default(T); } return ret1; } #line default } public void spliceVoid(int pos, int len) { unchecked { #line 249 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( len < 0 )) { #line 249 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ; } if (( pos < 0 )) { pos = ( this.length + pos ); if (( pos < 0 )) { #line 252 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" pos = 0; } } #line 254 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( pos > this.length )) { pos = 0; len = 0; } else { if (( ( pos + len ) > this.length )) { len = ( this.length - pos ); if (( len < 0 )) { #line 259 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" len = 0; } } } #line 261 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] a = this.__a; #line 263 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int end = ( pos + len ); global::System.Array.Copy(((global::System.Array) (a) ), ((int) (end) ), ((global::System.Array) (a) ), ((int) (pos) ), ((int) (( this.length - end )) )); this.length -= len; while (( -- len >= 0 )) { a[( this.length + len )] = default(T); } } #line default } public string toString() { unchecked { #line 272 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::StringBuf ret = new global::StringBuf(); T[] a = this.__a; ret.b.Append(((object) ("[") )); bool first = true; { #line 276 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int _g1 = 0; #line 276 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int _g = this.length; #line 276 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" while (( _g1 < _g )) { #line 276 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int i = _g1++; #line 278 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (first) { first = false; } else { #line 281 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" ret.b.Append(((object) (",") )); } ret.b.Append(((object) (global::Std.@string(a[i])) )); } } #line 285 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" ret.b.Append(((object) ("]") )); return ret.toString(); } #line default } public void unshift(T x) { unchecked { #line 291 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] __a = this.__a; int length = this.length; if (( length >= ( __a as global::System.Array ).Length )) { #line 295 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int newLen = ( (( length << 1 )) + 1 ); T[] newarr = new T[((int) (newLen) )]; global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (0) ), ((global::System.Array) (newarr) ), ((int) (1) ), ((int) (length) )); #line 299 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a = newarr; } else { #line 301 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (0) ), ((global::System.Array) (__a) ), ((int) (1) ), ((int) (length) )); } #line 304 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a[0] = x; ++ this.length; } #line default } public void insert(int pos, T x) { unchecked { #line 310 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int l = this.length; if (( pos < 0 )) { pos = ( l + pos ); if (( pos < 0 )) { #line 313 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" pos = 0; } } #line 315 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( pos >= l )) { this.push(x); return ; } else { if (( pos == 0 )) { this.unshift(x); return ; } } #line 323 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( l >= ( this.__a as global::System.Array ).Length )) { #line 325 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int newLen = ( (( this.length << 1 )) + 1 ); T[] newarr = new T[((int) (newLen) )]; global::System.Array.Copy(((global::System.Array) (this.__a) ), ((int) (0) ), ((global::System.Array) (newarr) ), ((int) (0) ), ((int) (pos) )); newarr[pos] = x; global::System.Array.Copy(((global::System.Array) (this.__a) ), ((int) (pos) ), ((global::System.Array) (newarr) ), ((int) (( pos + 1 )) ), ((int) (( l - pos )) )); #line 331 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a = newarr; ++ this.length; } else { #line 334 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] __a = this.__a; global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (pos) ), ((global::System.Array) (__a) ), ((int) (( pos + 1 )) ), ((int) (( l - pos )) )); global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (0) ), ((global::System.Array) (__a) ), ((int) (0) ), ((int) (pos) )); __a[pos] = x; ++ this.length; } } #line default } public bool @remove(T x) { unchecked { #line 344 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] __a = this.__a; int i = -1; int length = this.length; while (( ++ i < length )) { #line 349 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (global::haxe.lang.Runtime.eq(__a[i], x)) { #line 351 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (( i + 1 )) ), ((global::System.Array) (__a) ), ((int) (i) ), ((int) (( ( length - i ) - 1 )) )); __a[ -- this.length] = default(T); #line 354 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return true; } } #line 358 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return false; } #line default } public global::Array<S> map<S>(global::haxe.lang.Function f) { unchecked { #line 362 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<S> ret = new global::Array<S>(new S[]{}); { #line 363 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int _g = 0; #line 363 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<T> _g1 = this; #line 363 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" while (( _g < _g1.length )) { #line 363 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T elt = _g1[_g]; #line 363 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" ++ _g; ret.push(global::haxe.lang.Runtime.genericCast<S>(f.__hx_invoke1_o(default(double), elt))); } } return ret; } #line default } public global::Array<T> filter(global::haxe.lang.Function f) { unchecked { #line 369 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<T> ret = new global::Array<T>(new T[]{}); { #line 370 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int _g = 0; #line 370 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<T> _g1 = this; #line 370 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" while (( _g < _g1.length )) { #line 370 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T elt = _g1[_g]; #line 370 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" ++ _g; if (((bool) (f.__hx_invoke1_o(default(double), elt)) )) { ret.push(elt); } } } return ret; } #line default } public global::Array<T> copy() { unchecked { #line 378 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" int len = this.length; T[] __a = this.__a; T[] newarr = new T[((int) (len) )]; global::System.Array.Copy(((global::System.Array) (__a) ), ((int) (0) ), ((global::System.Array) (newarr) ), ((int) (0) ), ((int) (len) )); return global::Array<object>.ofNative<T>(newarr); } #line default } public object iterator() { unchecked { #line 385 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<object> _g = new global::Array<object>(new object[]{this}); #line 387 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" global::Array<int> i = new global::Array<int>(new int[]{0}); global::Array<int> len = new global::Array<int>(new int[]{this.length}); #line 390 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" { global::haxe.lang.Function __temp_odecl257 = new global::Array_iterator_391__Fun(((global::Array<int>) (global::Array<object>.__hx_cast<int>(((global::Array) (len) ))) ), ((global::Array<int>) (global::Array<object>.__hx_cast<int>(((global::Array) (i) ))) )); global::haxe.lang.Function __temp_odecl258 = new global::Array_iterator_392__Fun<T>(((global::Array<int>) (global::Array<object>.__hx_cast<int>(((global::Array) (i) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (_g) ))) )); #line 390 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{407283053, 1224901875}), new global::Array<object>(new object[]{__temp_odecl257, __temp_odecl258}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{})); } } #line default } public T __get(int idx) { unchecked { #line 398 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" T[] __a = this.__a; uint idx1 = ((uint) (idx) ); if (( idx1 >= this.length )) { return default(T); } #line 403 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return __a[((int) (idx1) )]; } #line default } public T __set(int idx, T v) { unchecked { #line 408 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" uint idx1 = ((uint) (idx) ); T[] __a = this.__a; if (( idx1 >= ( __a as global::System.Array ).Length )) { #line 412 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" uint len = ( idx1 + 1 ); if (( idx1 == ( __a as global::System.Array ).Length )) { len = ((uint) (( (( idx1 << 1 )) + 1 )) ); } T[] newArr = new T[((int) (len) )]; ( __a as global::System.Array ).CopyTo(((global::System.Array) (newArr) ), ((int) (0) )); this.__a = __a = newArr; } #line 420 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" if (( idx1 >= this.length )) { this.length = ((int) (( idx1 + 1 )) ); } #line 423 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return __a[((int) (idx1) )] = v; } #line default } public T __unsafe_get(int idx) { unchecked { #line 428 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__a[idx]; } #line default } public T __unsafe_set(int idx, T val) { unchecked { #line 433 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__a[idx] = val; } #line default } public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" switch (hash) { case 520590566: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.length = ((int) (@value) ); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return @value; } default: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return base.__hx_setField_f(field, hash, @value, handleProperties); } } } #line default } public override object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" switch (hash) { case 4745537: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.__a = ((T[]) (@value) ); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return @value; } case 520590566: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.length = ((int) (global::haxe.lang.Runtime.toInt(@value)) ); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return @value; } default: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return base.__hx_setField(field, hash, @value, handleProperties); } } } #line default } public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" switch (hash) { case 1621420777: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("__unsafe_set"), ((int) (1621420777) ))) ); } case 1620824029: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("__unsafe_get"), ((int) (1620824029) ))) ); } case 1916009602: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("__set"), ((int) (1916009602) ))) ); } case 1915412854: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("__get"), ((int) (1915412854) ))) ); } case 328878574: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("iterator"), ((int) (328878574) ))) ); } case 1103412149: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("copy"), ((int) (1103412149) ))) ); } case 87367608: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("filter"), ((int) (87367608) ))) ); } case 5442204: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("map"), ((int) (5442204) ))) ); } case 76061764: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("remove"), ((int) (76061764) ))) ); } case 501039929: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("insert"), ((int) (501039929) ))) ); } case 2025055113: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("unshift"), ((int) (2025055113) ))) ); } case 946786476: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("toString"), ((int) (946786476) ))) ); } case 1352786672: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("spliceVoid"), ((int) (1352786672) ))) ); } case 1067353468: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("splice"), ((int) (1067353468) ))) ); } case 1282943179: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("quicksort"), ((int) (1282943179) ))) ); } case 1280845662: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("sort"), ((int) (1280845662) ))) ); } case 2127021138: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("slice"), ((int) (2127021138) ))) ); } case 2082663554: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("shift"), ((int) (2082663554) ))) ); } case 452737314: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("reverse"), ((int) (452737314) ))) ); } case 1247875546: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("push"), ((int) (1247875546) ))) ); } case 5594513: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("pop"), ((int) (5594513) ))) ); } case 1181037546: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("join"), ((int) (1181037546) ))) ); } case 1532710347: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("concatNative"), ((int) (1532710347) ))) ); } case 1204816148: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("concat"), ((int) (1204816148) ))) ); } case 4745537: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__a; } case 520590566: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.length; } default: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties); } } } #line default } public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" switch (hash) { case 520590566: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((double) (this.length) ); } default: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return base.__hx_getField_f(field, hash, throwErrors, handleProperties); } } } #line default } public override object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" switch (hash) { case 1621420777: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__unsafe_set(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), global::haxe.lang.Runtime.genericCast<T>(dynargs[1])); } case 1620824029: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__unsafe_get(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) )); } case 1916009602: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__set(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), global::haxe.lang.Runtime.genericCast<T>(dynargs[1])); } case 1915412854: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.__get(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) )); } case 328878574: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.iterator(); } case 1103412149: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.copy(); } case 87367608: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.filter(((global::haxe.lang.Function) (dynargs[0]) )); } case 5442204: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.map<object>(((global::haxe.lang.Function) (dynargs[0]) )); } case 76061764: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.@remove(global::haxe.lang.Runtime.genericCast<T>(dynargs[0])); } case 501039929: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.insert(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), global::haxe.lang.Runtime.genericCast<T>(dynargs[1])); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 2025055113: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.unshift(global::haxe.lang.Runtime.genericCast<T>(dynargs[0])); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 946786476: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.toString(); } case 1352786672: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.spliceVoid(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), ((int) (global::haxe.lang.Runtime.toInt(dynargs[1])) )); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 1067353468: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.splice(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), ((int) (global::haxe.lang.Runtime.toInt(dynargs[1])) )); } case 1282943179: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.quicksort(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), ((int) (global::haxe.lang.Runtime.toInt(dynargs[1])) ), ((global::haxe.lang.Function) (dynargs[2]) )); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 1280845662: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.sort(((global::haxe.lang.Function) (dynargs[0]) )); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 2127021138: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.slice(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ), global::haxe.lang.Null<object>.ofDynamic<int>(dynargs[1])); } case 2082663554: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return (this.shift()).toDynamic(); } case 452737314: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.reverse(); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 1247875546: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.push(global::haxe.lang.Runtime.genericCast<T>(dynargs[0])); } case 5594513: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return (this.pop()).toDynamic(); } case 1181037546: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.@join(global::haxe.lang.Runtime.toString(dynargs[0])); } case 1532710347: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.concatNative(((T[]) (dynargs[0]) )); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" break; } case 1204816148: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return this.concat(((global::Array<T>) (global::Array<object>.__hx_cast<T>(((global::Array) (dynargs[0]) ))) )); } default: { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return base.__hx_invokeField(field, hash, dynargs); } } #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return default(object); } #line default } public override void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" baseArr.push("__a"); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" baseArr.push("length"); #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" { #line 31 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" base.__hx_getFields(baseArr); } } #line default } public T this[int index] { get { return this.__get(index); } set { this.__set(index,value); } } object global::Array.this[int key] { get { return ((object) this.__get(key)); } set { this.__set(key, (T) value); } } public override string ToString() { return this.toString(); } } #pragma warning disable 109, 114, 219, 429, 168, 162 public class Array_iterator_391__Fun : global::haxe.lang.Function { public Array_iterator_391__Fun(global::Array<int> len, global::Array<int> i) : base(0, 0) { unchecked { #line 391 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.len = len; #line 391 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.i = i; } #line default } public override object __hx_invoke0_o() { unchecked { #line 391 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ( this.i[0] < this.len[0] ); } #line default } public global::Array<int> len; public global::Array<int> i; } #pragma warning disable 109, 114, 219, 429, 168, 162 public class Array_iterator_392__Fun<T> : global::haxe.lang.Function { public Array_iterator_392__Fun(global::Array<int> i, global::Array<object> _g) : base(0, 0) { unchecked { #line 392 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this.i = i; #line 392 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" this._g = _g; } #line default } public override object __hx_invoke0_o() { unchecked { #line 392 "C:\\HaxeToolkit\\haxe\\std/cs/_std/Array.hx" return ((global::Array<T>) (global::Array<object>.__hx_cast<T>(((global::Array) (this._g[0]) ))) ).__a[this.i[0]++]; } #line default } public global::Array<int> i; public global::Array<object> _g; } #pragma warning disable 109, 114, 219, 429, 168, 162 public interface Array : global::haxe.lang.IHxObject, global::haxe.lang.IGenericObject { object Array_cast<T_c>(); object this[int key] { get; set; } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="LocationViewServiceClient"/> instances.</summary> public sealed partial class LocationViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="LocationViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="LocationViewServiceSettings"/>.</returns> public static LocationViewServiceSettings GetDefault() => new LocationViewServiceSettings(); /// <summary>Constructs a new <see cref="LocationViewServiceSettings"/> object with default settings.</summary> public LocationViewServiceSettings() { } private LocationViewServiceSettings(LocationViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetLocationViewSettings = existing.GetLocationViewSettings; OnCopy(existing); } partial void OnCopy(LocationViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>LocationViewServiceClient.GetLocationView</c> and <c>LocationViewServiceClient.GetLocationViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetLocationViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="LocationViewServiceSettings"/> object.</returns> public LocationViewServiceSettings Clone() => new LocationViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="LocationViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class LocationViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<LocationViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public LocationViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public LocationViewServiceClientBuilder() { UseJwtAccessWithScopes = LocationViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref LocationViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<LocationViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override LocationViewServiceClient Build() { LocationViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<LocationViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<LocationViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private LocationViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return LocationViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<LocationViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return LocationViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => LocationViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => LocationViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => LocationViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>LocationViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch location views. /// </remarks> public abstract partial class LocationViewServiceClient { /// <summary> /// The default endpoint for the LocationViewService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default LocationViewService scopes.</summary> /// <remarks> /// The default LocationViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="LocationViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="LocationViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="LocationViewServiceClient"/>.</returns> public static stt::Task<LocationViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new LocationViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="LocationViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="LocationViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="LocationViewServiceClient"/>.</returns> public static LocationViewServiceClient Create() => new LocationViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="LocationViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="LocationViewServiceSettings"/>.</param> /// <returns>The created <see cref="LocationViewServiceClient"/>.</returns> internal static LocationViewServiceClient Create(grpccore::CallInvoker callInvoker, LocationViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } LocationViewService.LocationViewServiceClient grpcClient = new LocationViewService.LocationViewServiceClient(callInvoker); return new LocationViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC LocationViewService client</summary> public virtual LocationViewService.LocationViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::LocationView GetLocationView(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::LocationView> GetLocationViewAsync(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::LocationView> GetLocationViewAsync(GetLocationViewRequest request, st::CancellationToken cancellationToken) => GetLocationViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::LocationView GetLocationView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationView(new GetLocationViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::LocationView> GetLocationViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationViewAsync(new GetLocationViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::LocationView> GetLocationViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetLocationViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::LocationView GetLocationView(gagvr::LocationViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationView(new GetLocationViewRequest { ResourceNameAsLocationViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::LocationView> GetLocationViewAsync(gagvr::LocationViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetLocationViewAsync(new GetLocationViewRequest { ResourceNameAsLocationViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the location view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::LocationView> GetLocationViewAsync(gagvr::LocationViewName resourceName, st::CancellationToken cancellationToken) => GetLocationViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>LocationViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch location views. /// </remarks> public sealed partial class LocationViewServiceClientImpl : LocationViewServiceClient { private readonly gaxgrpc::ApiCall<GetLocationViewRequest, gagvr::LocationView> _callGetLocationView; /// <summary> /// Constructs a client wrapper for the LocationViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="LocationViewServiceSettings"/> used within this client.</param> public LocationViewServiceClientImpl(LocationViewService.LocationViewServiceClient grpcClient, LocationViewServiceSettings settings) { GrpcClient = grpcClient; LocationViewServiceSettings effectiveSettings = settings ?? LocationViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetLocationView = clientHelper.BuildApiCall<GetLocationViewRequest, gagvr::LocationView>(grpcClient.GetLocationViewAsync, grpcClient.GetLocationView, effectiveSettings.GetLocationViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetLocationView); Modify_GetLocationViewApiCall(ref _callGetLocationView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetLocationViewApiCall(ref gaxgrpc::ApiCall<GetLocationViewRequest, gagvr::LocationView> call); partial void OnConstruction(LocationViewService.LocationViewServiceClient grpcClient, LocationViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC LocationViewService client</summary> public override LocationViewService.LocationViewServiceClient GrpcClient { get; } partial void Modify_GetLocationViewRequest(ref GetLocationViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::LocationView GetLocationView(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetLocationViewRequest(ref request, ref callSettings); return _callGetLocationView.Sync(request, callSettings); } /// <summary> /// Returns the requested location view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::LocationView> GetLocationViewAsync(GetLocationViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetLocationViewRequest(ref request, ref callSettings); return _callGetLocationView.Async(request, callSettings); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ExecutionStepResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Studio.V2.Flow.Execution { public class ExecutionStepResource : Resource { private static Request BuildReadRequest(ReadExecutionStepOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Studio, "/v2/Flows/" + options.PathFlowSid + "/Executions/" + options.PathExecutionSid + "/Steps", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="options"> Read ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ResourceSet<ExecutionStepResource> Read(ReadExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ExecutionStepResource>.FromJson("steps", response.Content); return new ResourceSet<ExecutionStepResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="options"> Read ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ResourceSet<ExecutionStepResource>> ReadAsync(ReadExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ExecutionStepResource>.FromJson("steps", response.Content); return new ResourceSet<ExecutionStepResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ResourceSet<ExecutionStepResource> Read(string pathFlowSid, string pathExecutionSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadExecutionStepOptions(pathFlowSid, pathExecutionSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Steps for an Execution. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ResourceSet<ExecutionStepResource>> ReadAsync(string pathFlowSid, string pathExecutionSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadExecutionStepOptions(pathFlowSid, pathExecutionSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ExecutionStepResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ExecutionStepResource>.FromJson("steps", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ExecutionStepResource> NextPage(Page<ExecutionStepResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Studio) ); var response = client.Request(request); return Page<ExecutionStepResource>.FromJson("steps", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ExecutionStepResource> PreviousPage(Page<ExecutionStepResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Studio) ); var response = client.Request(request); return Page<ExecutionStepResource>.FromJson("steps", response.Content); } private static Request BuildFetchRequest(FetchExecutionStepOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Studio, "/v2/Flows/" + options.PathFlowSid + "/Executions/" + options.PathExecutionSid + "/Steps/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a Step. /// </summary> /// <param name="options"> Fetch ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ExecutionStepResource Fetch(FetchExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Retrieve a Step. /// </summary> /// <param name="options"> Fetch ExecutionStep parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ExecutionStepResource> FetchAsync(FetchExecutionStepOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Retrieve a Step. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ExecutionStep </returns> public static ExecutionStepResource Fetch(string pathFlowSid, string pathExecutionSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchExecutionStepOptions(pathFlowSid, pathExecutionSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Retrieve a Step. /// </summary> /// <param name="pathFlowSid"> The SID of the Flow </param> /// <param name="pathExecutionSid"> The SID of the Execution </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ExecutionStep </returns> public static async System.Threading.Tasks.Task<ExecutionStepResource> FetchAsync(string pathFlowSid, string pathExecutionSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchExecutionStepOptions(pathFlowSid, pathExecutionSid, pathSid); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ExecutionStepResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ExecutionStepResource object represented by the provided JSON </returns> public static ExecutionStepResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ExecutionStepResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Flow /// </summary> [JsonProperty("flow_sid")] public string FlowSid { get; private set; } /// <summary> /// The SID of the Execution /// </summary> [JsonProperty("execution_sid")] public string ExecutionSid { get; private set; } /// <summary> /// The event that caused the Flow to transition to the Step /// </summary> [JsonProperty("name")] public string Name { get; private set; } /// <summary> /// The current state of the flow /// </summary> [JsonProperty("context")] public object Context { get; private set; } /// <summary> /// The Widget that preceded the Widget for the Step /// </summary> [JsonProperty("transitioned_from")] public string TransitionedFrom { get; private set; } /// <summary> /// The Widget that will follow the Widget for the Step /// </summary> [JsonProperty("transitioned_to")] public string TransitionedTo { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private ExecutionStepResource() { } } }
using Signum.Utilities.Reflection; using Signum.Engine.Maps; using Signum.Entities.Basics; using Signum.Entities.Internal; using Signum.Utilities.DataStructures; namespace Signum.Engine.Linq; internal static class TranslatorBuilder { internal static ITranslateResult Build(ProjectionExpression proj) { Type type = proj.UniqueFunction == null ? proj.Type.ElementType()! : proj.Type; return miBuildPrivate.GetInvoker(type)(proj); } static GenericInvoker<Func<ProjectionExpression, ITranslateResult>> miBuildPrivate = new(pe => BuildPrivate<int>(pe)); static TranslateResult<T> BuildPrivate<T>(ProjectionExpression proj) { var eagerChildProjections = EagerChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList(); var lazyChildProjections = LazyChildProjectionGatherer.Gatherer(proj).Select(cp => BuildChild(cp)).ToList(); Scope scope = new Scope( alias :proj.Select.Alias, positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name!, p => p.i) /*CSBUG*/ ); Expression<Func<IProjectionRow, T>> lambda = ProjectionBuilder.Build<T>(proj.Projector, scope); var command = QueryFormatter.Format(proj.Select); var result = new TranslateResult<T>( eagerProjections: eagerChildProjections, lazyChildProjections: lazyChildProjections, mainCommand: command, projectorExpression: lambda, unique: proj.UniqueFunction ); return result; } static IChildProjection BuildChild(ChildProjectionExpression childProj) { var proj = childProj.Projection; Type type = proj.UniqueFunction == null ? proj.Type.ElementType()! : proj.Type; if(!type.IsInstantiationOf(typeof(KeyValuePair<,>))) throw new InvalidOperationException("All child projections should create KeyValuePairs"); Scope scope = new Scope( alias: proj.Select.Alias, positions: proj.Select.Columns.Select((c, i) => new { c.Name, i }).ToDictionary(p => p.Name!, p => p.i) /*CSBUG*/ ); var types = type.GetGenericArguments(); var command = QueryFormatter.Format(proj.Select); if (childProj.IsLazyMList) { types[1] = types[1].GetGenericArguments()[0]; return giLazyChild.GetInvoker(types)(proj.Projector, scope, childProj.Token, command); } else { return giEagerChild.GetInvoker(types)(proj.Projector, scope, childProj.Token, command); } } static readonly GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>> giLazyChild = new((proj, scope, token, sql) => LazyChild<int, bool>(proj, scope, token, sql)); static IChildProjection LazyChild<K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command) where K : notnull { var proj = ProjectionBuilder.Build<KeyValuePair<K, MList<V>.RowIdElement>>(projector, scope); return new LazyChildProjection<K, V>(token, command, proj); } static readonly GenericInvoker<Func<Expression, Scope, LookupToken, SqlPreCommandSimple, IChildProjection>> giEagerChild = new((proj, scope, token, sql) => EagerChild<int, bool>(proj, scope, token, sql)); static IChildProjection EagerChild<K, V>(Expression projector, Scope scope, LookupToken token, SqlPreCommandSimple command) { var proj = ProjectionBuilder.Build<KeyValuePair<K, V>>(projector, scope); return new EagerChildProjection<K, V>(token, command, proj); } public static SqlPreCommandSimple BuildCommandResult(CommandExpression command) { return QueryFormatter.Format(command); } public class LazyChildProjectionGatherer : DbExpressionVisitor { List<ChildProjectionExpression> list = new List<ChildProjectionExpression>(); public static List<ChildProjectionExpression> Gatherer(ProjectionExpression proj) { LazyChildProjectionGatherer pg = new LazyChildProjectionGatherer(); pg.Visit(proj); return pg.list; } protected internal override Expression VisitChildProjection(ChildProjectionExpression child) { if (child.IsLazyMList) list.Add(child); var result = base.VisitChildProjection(child); return result; } } public class EagerChildProjectionGatherer : DbExpressionVisitor { List<ChildProjectionExpression> list = new List<ChildProjectionExpression>(); public static List<ChildProjectionExpression> Gatherer(ProjectionExpression proj) { EagerChildProjectionGatherer pg = new EagerChildProjectionGatherer(); pg.Visit(proj); return pg.list; } protected internal override Expression VisitChildProjection(ChildProjectionExpression child) { var result = base.VisitChildProjection(child); if (!child.IsLazyMList) list.Add(child); return result; } } /// <summary> /// ProjectionBuilder is a visitor that converts an projector expression /// that constructs result objects out of ColumnExpressions into an actual /// LambdaExpression that constructs result objects out of accessing fields /// of a ProjectionRow /// </summary> public class ProjectionBuilder : DbExpressionVisitor { static readonly ParameterExpression row = Expression.Parameter(typeof(IProjectionRow), "row"); static readonly PropertyInfo piRetriever = ReflectionTools.GetPropertyInfo((IProjectionRow r) => r.Retriever); static readonly MemberExpression retriever = Expression.Property(row, piRetriever); static readonly MethodInfo miCached = ReflectionTools.GetMethodInfo((IRetriever r) => r.Complete<TypeEntity>(null, null!)).GetGenericMethodDefinition(); static readonly MethodInfo miRequest = ReflectionTools.GetMethodInfo((IRetriever r) => r.Request<TypeEntity>(null)).GetGenericMethodDefinition(); static readonly MethodInfo miRequestIBA = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestIBA<TypeEntity>(null, null)).GetGenericMethodDefinition(); static readonly MethodInfo miRequestLite = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestLite<TypeEntity>(null)).GetGenericMethodDefinition(); static readonly MethodInfo miModifiablePostRetrieving = ReflectionTools.GetMethodInfo((IRetriever r) => r.ModifiablePostRetrieving<EmbeddedEntity>(null)).GetGenericMethodDefinition(); Scope scope; public ProjectionBuilder(Scope scope) { this.scope = scope; } static internal Expression<Func<IProjectionRow, T>> Build<T>(Expression expression, Scope scope) { ProjectionBuilder pb = new ProjectionBuilder(scope); Expression body = pb.Visit(expression); return Expression.Lambda<Func<IProjectionRow, T>>(body, row); } static Expression NullifyColumn(Expression exp) { if (exp is not ColumnExpression ce) return exp; if (ce.Type.IsNullable() || ce.Type.IsClass) return ce; return new ColumnExpression(ce.Type.Nullify(), ce.Alias, ce.Name); } protected override Expression VisitUnary(UnaryExpression u) { var col = GetInnerColumn(u); if(col != null) return scope.GetColumnExpression(row, col.Alias, col.Name!, u.Type); return base.VisitUnary(u); } public ColumnExpression? GetInnerColumn(UnaryExpression u) { if(u.NodeType == ExpressionType.Convert && DiffersInNullability(u.Type, u.Operand.Type)) { if (u.Operand is ColumnExpression c) return c; if (u.Operand is UnaryExpression u2) return GetInnerColumn(u2); } return null; } static bool DiffersInNullability(Type a, Type b) { if (a.IsValueType && a.Nullify() == b || b.IsValueType && b.Nullify() == a) return true; if (a == typeof(DateOnly) && b == typeof(DateTime) || a == typeof(DateTime) && b == typeof(DateOnly)) return true; return false; } protected internal override Expression VisitColumn(ColumnExpression column) { return scope.GetColumnExpression(row, column.Alias, column.Name!, column.Type); } protected internal override Expression VisitChildProjection(ChildProjectionExpression child) { Expression outer = Visit(child.OuterKey); if (outer != child.OuterKey) child = new ChildProjectionExpression(child.Projection, outer, child.IsLazyMList, child.Type, child.Token); return Scope.LookupEager(row, child); } protected Expression VisitMListChildProjection(ChildProjectionExpression child, MemberExpression field) { Expression outer = Visit(child.OuterKey); if (outer != child.OuterKey) child = new ChildProjectionExpression(child.Projection, outer, child.IsLazyMList, child.Type, child.Token); return Scope.LookupMList(row, child, field); } protected internal override Expression VisitProjection(ProjectionExpression proj) { throw new InvalidOperationException("No ProjectionExpressions expected at this stage"); } protected internal override MixinEntityExpression VisitMixinEntity(MixinEntityExpression me) { throw new InvalidOperationException("Impossible to retrieve MixinEntity {0} without their main entity".FormatWith(me.Type.Name)); } protected internal override Expression VisitEntity(EntityExpression entityExpr) { Expression id = Visit(NullifyColumn(entityExpr.ExternalId)); if (entityExpr.TableAlias == null) return Expression.Call(retriever, miRequest.MakeGenericMethod(entityExpr.Type), id); ParameterExpression e = Expression.Parameter(entityExpr.Type, entityExpr.Type.Name.ToLower().Substring(0, 1)); var bindings = entityExpr.Bindings! .Where(a => !ReflectionTools.FieldEquals(EntityExpression.IdField, a.FieldInfo)) .Select(b => { var field = Expression.Field(e, b.FieldInfo); var value = b.Binding is ChildProjectionExpression cpe ? VisitMListChildProjection(cpe, field) : Convert(Visit(b.Binding), b.FieldInfo.FieldType); return (Expression)Expression.Assign(field, value); }).ToList(); if (entityExpr.Mixins != null) { var blocks = entityExpr.Mixins.Select(m => AssignMixin(e, m)).ToList(); bindings.AddRange(blocks); } LambdaExpression lambda = Expression.Lambda(typeof(Action<>).MakeGenericType(entityExpr.Type), Expression.Block(bindings), e); return Expression.Call(retriever, miCached.MakeGenericMethod(entityExpr.Type), id.Nullify(), lambda); } BlockExpression AssignMixin(ParameterExpression e, MixinEntityExpression m) { var mixParam = Expression.Parameter(m.Type); var mixBindings = new List<Expression> { Expression.Assign(mixParam, Expression.Call(e, MixinDeclarations.miMixin.MakeGenericMethod(m.Type))), Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(m.Type), mixParam) }; mixBindings.AddRange(m.Bindings.Select(b => { var field = Expression.Field(mixParam, b.FieldInfo); var value = b.Binding is ChildProjectionExpression cpe ? VisitMListChildProjection(cpe, field) : Convert(Visit(b.Binding), b.FieldInfo.FieldType); return (Expression)Expression.Assign(field, value); })); return Expression.Block(new[] { mixParam }, mixBindings); } private static Expression Convert(Expression expression, Type type) { if (expression.Type == type) return expression; return Expression.Convert(expression, type); } protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee) { var embeddedParam = Expression.Parameter(eee.Type); var embeddedBindings = new List<Expression> { Expression.Assign(embeddedParam, Expression.New(eee.Type)) }; if (typeof(EmbeddedEntity).IsAssignableFrom(eee.Type)) embeddedBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(eee.Type), embeddedParam)); embeddedBindings.AddRange(eee.Bindings.Select(b => { var field = Expression.Field(embeddedParam, b.FieldInfo); var value = b.Binding is ChildProjectionExpression cpe ? VisitMListChildProjection(cpe, field) : Convert(Visit(b.Binding), b.FieldInfo.FieldType); return Expression.Assign(field, value); })); if (eee.Mixins != null) { var blocks = eee.Mixins.Select(m => AssignMixin(embeddedParam, m)).ToList(); embeddedBindings.AddRange(blocks); } embeddedBindings.Add(embeddedParam); var block = Expression.Block(eee.Type, new[] { embeddedParam }, embeddedBindings); return Expression.Condition(Expression.Equal(Visit(eee.HasValue.Nullify()), Expression.Constant(true, typeof(bool?))), block, Expression.Constant(null, block.Type)); } protected internal override Expression VisitImplementedBy(ImplementedByExpression rb) { return rb.Implementations.Select(ee => new When(Visit(ee.Value.ExternalId).NotEqualsNulll(), Visit(ee.Value))).ToCondition(rb.Type); } protected internal override Expression VisitImplementedByAll(ImplementedByAllExpression rba) { return Expression.Call(retriever, miRequestIBA.MakeGenericMethod(rba.Type), Visit(NullifyColumn(rba.TypeId.TypeColumn)), Visit(NullifyColumn(rba.Id))); } static readonly ConstantExpression NullType = Expression.Constant(null, typeof(Type)); static readonly ConstantExpression NullId = Expression.Constant(null, typeof(int?)); protected internal override Expression VisitTypeEntity(TypeEntityExpression typeFie) { return Expression.Condition( Expression.NotEqual(Visit(NullifyColumn(typeFie.ExternalId)), NullId), Expression.Constant(typeFie.TypeValue, typeof(Type)), NullType); } protected internal override Expression VisitTypeImplementedBy(TypeImplementedByExpression typeIb) { return typeIb.TypeImplementations.Reverse().Aggregate((Expression)NullType, (acum, imp) => Expression.Condition( Expression.NotEqual(Visit(NullifyColumn(imp.Value)), NullId), Expression.Constant(imp.Key, typeof(Type)), acum)); } static MethodInfo miGetType = ReflectionTools.GetMethodInfo((Schema s) => s.GetType(1)); protected internal override Expression VisitTypeImplementedByAll(TypeImplementedByAllExpression typeIba) { return Expression.Condition( Expression.NotEqual(Visit(NullifyColumn(typeIba.TypeColumn)), NullId), SchemaGetType(typeIba), NullType); } private MethodCallExpression SchemaGetType(TypeImplementedByAllExpression typeIba) { return Expression.Call(Expression.Constant(Schema.Current), miGetType, Visit(typeIba.TypeColumn).UnNullify()); } protected internal override Expression VisitLiteReference(LiteReferenceExpression lite) { var reference = Visit(lite.Reference); var toStr = Visit(lite.CustomToStr); return Lite.ToLiteFatInternalExpression(reference, toStr ?? Expression.Constant(null, typeof(string))); } protected internal override Expression VisitLiteValue(LiteValueExpression lite) { var id = Visit(NullifyColumn(lite.Id)); if (id == null) return Expression.Constant(null, lite.Type); var toStr = Visit(lite.ToStr); var typeId = lite.TypeId; var toStringOrNull = toStr ?? Expression.Constant(null, typeof(string)); Expression nothing = Expression.Constant(null, lite.Type); Expression liteConstructor; if (typeId is TypeEntityExpression tee) { Type type = tee.TypeValue; liteConstructor = Expression.Condition(Expression.NotEqual(id, NullId), Expression.Convert(Lite.NewExpression(type, id, toStringOrNull), lite.Type), nothing); } else if (typeId is TypeImplementedByExpression tib) { liteConstructor = tib.TypeImplementations.Aggregate(nothing, (acum, ti) => { var visitId = Visit(NullifyColumn(ti.Value)); return Expression.Condition(Expression.NotEqual(visitId, NullId), Expression.Convert(Lite.NewExpression(ti.Key, visitId, toStringOrNull), lite.Type), acum); }); } else if (typeId is TypeImplementedByAllExpression tiba) { var tid = Visit(NullifyColumn(tiba.TypeColumn)); liteConstructor = Expression.Convert(Expression.Call(miLiteCreateParse, Expression.Constant(Schema.Current), tid, id.UnNullify(), toStringOrNull), lite.Type); } else { liteConstructor = Expression.Condition(Expression.NotEqual(id.Nullify(), NullId), Expression.Convert(Expression.Call(miLiteCreate, Visit(typeId), id.UnNullify(), toStringOrNull), lite.Type), nothing); } if (toStr != null) return Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(typeof(LiteImp)), liteConstructor.TryConvert(typeof(LiteImp))).TryConvert(liteConstructor.Type); else return Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(lite.Type)!), liteConstructor); } static readonly MethodInfo miLiteCreateParse = ReflectionTools.GetMethodInfo(() => LiteCreateParse(null!, null, null!, null!)); static Lite<Entity>? LiteCreateParse(Schema schema, PrimaryKey? typeId, string id, string toString) { if (typeId == null) return null; Type type = schema.GetType(typeId.Value); return Lite.Create(type, PrimaryKey.Parse(id, type), toString); } static MethodInfo miLiteCreate = ReflectionTools.GetMethodInfo(() => Lite.Create(null!, 0, null)); protected internal override Expression VisitMListElement(MListElementExpression mle) { Type type = mle.Type; var bindings = new List<MemberAssignment> { Expression.Bind(type.GetProperty("RowId")!, Visit(mle.RowId.UnNullify())), Expression.Bind(type.GetProperty("Parent")!, Visit(mle.Parent)), }; if (mle.Order != null) bindings.Add(Expression.Bind(type.GetProperty("RowOrder")!, Visit(mle.Order))); bindings.Add(Expression.Bind(type.GetProperty("Element")!, Visit(mle.Element))); var init = Expression.MemberInit(Expression.New(type), bindings); return Expression.Condition(SmartEqualizer.NotEqualNullable(Visit(mle.RowId.Nullify()), NullId), init, Expression.Constant(null, init.Type)); } protected internal override Expression VisitSqlConstant(SqlConstantExpression sce) { return Expression.Constant(sce.Value, sce.Type); } protected internal override Expression VisitPrimaryKey(PrimaryKeyExpression pk) { var val = Visit(pk.Value); return Expression.Call(miWrap, Expression.Convert(val, typeof(IComparable))); } static readonly MethodInfo miWrap = ReflectionTools.GetMethodInfo(() => PrimaryKey.Wrap(1)); protected internal override Expression VisitPrimaryKeyString(PrimaryKeyStringExpression pk) { var id = this.Visit(pk.Id); var type = this.Visit(pk.TypeId); return Expression.Call(miTryParse, type, id); } static readonly MethodInfo miTryParse = ReflectionTools.GetMethodInfo(() => TryParse(null!, null!)); static PrimaryKey? TryParse(Type type, string id) { if (type == null) return null; return PrimaryKey.Parse(id, type); } protected internal override Expression VisitToDayOfWeek(ToDayOfWeekExpression toDayOfWeek) { var result = this.Visit(toDayOfWeek.Expression); if (Schema.Current.Settings.IsPostgres) { return Expression.Call(ToDayOfWeekExpression.miToDayOfWeekPostgres, result); } else { var dateFirst = ((SqlServerConnector)Connector.Current).DateFirst; return Expression.Call(ToDayOfWeekExpression.miToDayOfWeekSql, result, Expression.Constant(dateFirst, typeof(byte))); } } static MethodInfo miToInterval = ReflectionTools.GetMethodInfo(() => ToInterval<int>(new NpgsqlTypes.NpgsqlRange<int>())).GetGenericMethodDefinition(); static NullableInterval<T> ToInterval<T>(NpgsqlTypes.NpgsqlRange<T> range) where T : struct, IComparable<T>, IEquatable<T> => new NullableInterval<T>( range.LowerBoundInfinite ? null : range.LowerBound, range.UpperBoundInfinite ? null : range.UpperBound); protected internal override Expression VisitInterval(IntervalExpression interval) { var intervalType = interval.Type.GetGenericArguments()[0]; if (Schema.Current.Settings.IsPostgres) { return Expression.Call(miToInterval.MakeGenericMethod(intervalType), Visit(interval.PostgresRange!)); } else { return Expression.New(typeof(NullableInterval<>).MakeGenericType(intervalType).GetConstructor(new[] { intervalType, intervalType })!, Visit(interval.Min!), Visit(interval.Max!)); } } protected override Expression VisitNew(NewExpression node) { var expressions = this.Visit(node.Arguments); if (node.Members != null) { for (int i = 0; i < node.Members.Count; i++) { var m = node.Members[i]; var e = expressions[i]; if (m is PropertyInfo pi && !pi.PropertyType.IsAssignableFrom(e.Type)) { throw new InvalidOperationException( $"Impossible to assign a '{e.Type.TypeName()}' to the member '{m.Name}' of type '{pi.PropertyType.TypeName()}'." + (e.Type.IsInstantiationOf(typeof(IEnumerable<>)) ? "\nConsider adding '.ToList()' at the end of your sub-query" : null) ); } } } return (Expression)node.Update(expressions); } } } internal class Scope { public Alias Alias; public Dictionary<string, int> Positions; public Scope(Alias alias, Dictionary<string, int> positions) { Alias = alias; Positions = positions; } static readonly PropertyInfo miReader = ReflectionTools.GetPropertyInfo((IProjectionRow row) => row.Reader); public Expression GetColumnExpression(Expression row, Alias alias, string name, Type type) { if (alias != Alias) throw new InvalidOperationException("alias '{0}' not found".FormatWith(alias)); int position = Positions.GetOrThrow(name, "column name '{0}' not found in alias '" + alias + "'"); return FieldReader.GetExpression(Expression.Property(row, miReader), position, type); } static readonly MethodInfo miLookupRequest = ReflectionTools.GetMethodInfo((IProjectionRow row) => row.LookupRequest<int, double>(null!, 0, null!)).GetGenericMethodDefinition(); static readonly MethodInfo miLookup = ReflectionTools.GetMethodInfo((IProjectionRow row) => row.Lookup<int, double>(null!, 0)).GetGenericMethodDefinition(); public static Expression LookupEager(Expression row, ChildProjectionExpression cProj) { if (cProj.IsLazyMList) throw new InvalidOperationException("IsLazyMList not expected at this stage"); Type type = cProj.Projection.UniqueFunction == null ? cProj.Type.ElementType()! : cProj.Type; MethodInfo mi = miLookup.MakeGenericMethod(cProj.OuterKey.Type, type); Expression call = Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey); if (cProj.Projection.UniqueFunction != null) throw new InvalidOperationException("Eager ChildProyection with UniqueFunction '{0}' not expected at this stage".FormatWith(cProj.Projection.UniqueFunction)); return call; } public static Expression LookupMList(Expression row, ChildProjectionExpression cProj, MemberExpression field) { if (!cProj.IsLazyMList) throw new InvalidOperationException("Not IsLazyMList not expected at this stage"); if (!cProj.Type.IsMList()) throw new InvalidOperationException("Lazy ChildProyection of type '{0}' instead of MList".FormatWith(cProj.Type.TypeName())); if (cProj.Projection.UniqueFunction != null) throw new InvalidOperationException("Lazy ChildProyection with UniqueFunction '{0}'".FormatWith(cProj.Projection.UniqueFunction)); MethodInfo mi = miLookupRequest.MakeGenericMethod(cProj.OuterKey.Type, cProj.Type.ElementType()!); return Expression.Call(row, mi, Expression.Constant(cProj.Token), cProj.OuterKey, field); } }
// 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.ComponentModel; using System.Data; using System.Data.Common; using System.Threading; namespace System.Data.Odbc { [ DefaultEvent("RowUpdated"), ToolboxItem("Microsoft.VSDesigner.Data.VS.OdbcDataAdapterToolboxItem, " + AssemblyRef.MicrosoftVSDesigner), // WebData 97832 Designer("Microsoft.VSDesigner.Data.VS.OdbcDataAdapterDesigner, " + AssemblyRef.MicrosoftVSDesigner) ] public sealed class OdbcDataAdapter : DbDataAdapter, IDbDataAdapter, ICloneable { static private readonly object s_eventRowUpdated = new object(); static private readonly object s_eventRowUpdating = new object(); private OdbcCommand _deleteCommand, _insertCommand, _selectCommand, _updateCommand; public OdbcDataAdapter() : base() { GC.SuppressFinalize(this); } public OdbcDataAdapter(OdbcCommand selectCommand) : this() { SelectCommand = selectCommand; } public OdbcDataAdapter(string selectCommandText, OdbcConnection selectConnection) : this() { SelectCommand = new OdbcCommand(selectCommandText, selectConnection); } public OdbcDataAdapter(string selectCommandText, string selectConnectionString) : this() { OdbcConnection connection = new OdbcConnection(selectConnectionString); SelectCommand = new OdbcCommand(selectCommandText, connection); } private OdbcDataAdapter(OdbcDataAdapter from) : base(from) { GC.SuppressFinalize(this); } [ DefaultValue(null), ResCategoryAttribute(Res.DataCategory_Update), ResDescriptionAttribute(Res.DbDataAdapter_DeleteCommand), Editor("Microsoft.VSDesigner.Data.Design.DBCommandEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ] new public OdbcCommand DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = value; } } IDbCommand IDbDataAdapter.DeleteCommand { get { return _deleteCommand; } set { _deleteCommand = (OdbcCommand)value; } } [ DefaultValue(null), ResCategoryAttribute(Res.DataCategory_Update), ResDescriptionAttribute(Res.DbDataAdapter_InsertCommand), Editor("Microsoft.VSDesigner.Data.Design.DBCommandEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ] new public OdbcCommand InsertCommand { get { return _insertCommand; } set { _insertCommand = value; } } IDbCommand IDbDataAdapter.InsertCommand { get { return _insertCommand; } set { _insertCommand = (OdbcCommand)value; } } [ DefaultValue(null), ResCategoryAttribute(Res.DataCategory_Fill), ResDescriptionAttribute(Res.DbDataAdapter_SelectCommand), Editor("Microsoft.VSDesigner.Data.Design.DBCommandEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ] new public OdbcCommand SelectCommand { get { return _selectCommand; } set { _selectCommand = value; } } IDbCommand IDbDataAdapter.SelectCommand { get { return _selectCommand; } set { _selectCommand = (OdbcCommand)value; } } [ DefaultValue(null), ResCategoryAttribute(Res.DataCategory_Update), ResDescriptionAttribute(Res.DbDataAdapter_UpdateCommand), Editor("Microsoft.VSDesigner.Data.Design.DBCommandEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ] new public OdbcCommand UpdateCommand { get { return _updateCommand; } set { _updateCommand = value; } } IDbCommand IDbDataAdapter.UpdateCommand { get { return _updateCommand; } set { _updateCommand = (OdbcCommand)value; } } [ ResCategoryAttribute(Res.DataCategory_Update), ResDescriptionAttribute(Res.DbDataAdapter_RowUpdated), ] public event OdbcRowUpdatedEventHandler RowUpdated { add { Events.AddHandler(s_eventRowUpdated, value); } remove { Events.RemoveHandler(s_eventRowUpdated, value); } } [ ResCategoryAttribute(Res.DataCategory_Update), ResDescriptionAttribute(Res.DbDataAdapter_RowUpdating), ] public event OdbcRowUpdatingEventHandler RowUpdating { add { OdbcRowUpdatingEventHandler handler = (OdbcRowUpdatingEventHandler)Events[s_eventRowUpdating]; // MDAC 58177, 64513 // prevent someone from registering two different command builders on the adapter by // silently removing the old one if ((null != handler) && (value.Target is OdbcCommandBuilder)) { OdbcRowUpdatingEventHandler d = (OdbcRowUpdatingEventHandler)ADP.FindBuilder(handler); if (null != d) { Events.RemoveHandler(s_eventRowUpdating, d); } } Events.AddHandler(s_eventRowUpdating, value); } remove { Events.RemoveHandler(s_eventRowUpdating, value); } } object ICloneable.Clone() { return new OdbcDataAdapter(this); } override protected RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new OdbcRowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new OdbcRowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } override protected void OnRowUpdated(RowUpdatedEventArgs value) { OdbcRowUpdatedEventHandler handler = (OdbcRowUpdatedEventHandler)Events[s_eventRowUpdated]; if ((null != handler) && (value is OdbcRowUpdatedEventArgs)) { handler(this, (OdbcRowUpdatedEventArgs)value); } base.OnRowUpdated(value); } override protected void OnRowUpdating(RowUpdatingEventArgs value) { OdbcRowUpdatingEventHandler handler = (OdbcRowUpdatingEventHandler)Events[s_eventRowUpdating]; if ((null != handler) && (value is OdbcRowUpdatingEventArgs)) { handler(this, (OdbcRowUpdatingEventArgs)value); } base.OnRowUpdating(value); } } }
/* * 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; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { public struct QueueItem { public int id; public OSDMap body; } [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EventQueueGetModule")] public class EventQueueGetModule : IEventQueue, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[EVENT QUEUE GET MODULE]"; /// <value> /// Debug level. /// </value> public int DebugLevel { get; set; } // Viewer post requests timeout in 60 secs // https://bitbucket.org/lindenlab/viewer-release/src/421c20423df93d650cc305dc115922bb30040999/indra/llmessage/llhttpclient.cpp?at=default#cl-44 // private const int VIEWER_TIMEOUT = 60 * 1000; // Just to be safe, we work on a 10 sec shorter cycle private const int SERVER_EQ_TIME_NO_EVENTS = VIEWER_TIMEOUT - (10 * 1000); protected Scene m_scene; private Dictionary<UUID, int> m_ids = new Dictionary<UUID, int>(); private Dictionary<UUID, Queue<OSD>> queues = new Dictionary<UUID, Queue<OSD>>(); private Dictionary<UUID, UUID> m_AvatarQueueUUIDMapping = new Dictionary<UUID, UUID>(); #region INonSharedRegionModule methods public virtual void Initialise(IConfigSource config) { } public void AddRegion(Scene scene) { m_scene = scene; scene.RegisterModuleInterface<IEventQueue>(this); scene.EventManager.OnClientClosed += ClientClosed; scene.EventManager.OnRegisterCaps += OnRegisterCaps; MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug eq", "debug eq [0|1|2]", "Turn on event queue debugging\n" + " <= 0 - turns off all event queue logging\n" + " >= 1 - turns on event queue setup and outgoing event logging\n" + " >= 2 - turns on poll notification", HandleDebugEq); MainConsole.Instance.Commands.AddCommand( "Debug", false, "show eq", "show eq", "Show contents of event queues for logged in avatars. Used for debugging.", HandleShowEq); } public void RemoveRegion(Scene scene) { if (m_scene != scene) return; scene.EventManager.OnClientClosed -= ClientClosed; scene.EventManager.OnRegisterCaps -= OnRegisterCaps; scene.UnregisterModuleInterface<IEventQueue>(this); m_scene = null; } public void RegionLoaded(Scene scene) { } public virtual void Close() { } public virtual string Name { get { return "EventQueueGetModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion protected void HandleDebugEq(string module, string[] args) { int debugLevel; if (!(args.Length == 3 && int.TryParse(args[2], out debugLevel))) { MainConsole.Instance.OutputFormat("Usage: debug eq [0|1|2]"); } else { DebugLevel = debugLevel; MainConsole.Instance.OutputFormat( "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.RegionInfo.RegionName); } } protected void HandleShowEq(string module, string[] args) { MainConsole.Instance.OutputFormat("For scene {0}", m_scene.Name); lock (queues) { foreach (KeyValuePair<UUID, Queue<OSD>> kvp in queues) { MainConsole.Instance.OutputFormat( "For agent {0} there are {1} messages queued for send.", kvp.Key, kvp.Value.Count); } } } /// <summary> /// Always returns a valid queue /// </summary> /// <param name="agentId"></param> /// <returns></returns> private Queue<OSD> TryGetQueue(UUID agentId) { lock (queues) { if (!queues.ContainsKey(agentId)) { if (DebugLevel > 0) m_log.DebugFormat( "[EVENTQUEUE]: Adding new queue for agent {0} in region {1}", agentId, m_scene.RegionInfo.RegionName); queues[agentId] = new Queue<OSD>(); } return queues[agentId]; } } /// <summary> /// May return a null queue /// </summary> /// <param name="agentId"></param> /// <returns></returns> private Queue<OSD> GetQueue(UUID agentId) { lock (queues) { if (queues.ContainsKey(agentId)) { return queues[agentId]; } else return null; } } #region IEventQueue Members public bool Enqueue(OSD ev, UUID avatarID) { //m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName); try { Queue<OSD> queue = GetQueue(avatarID); if (queue != null) { lock (queue) queue.Enqueue(ev); } else { OSDMap evMap = (OSDMap)ev; m_log.WarnFormat( "[EVENTQUEUE]: (Enqueue) No queue found for agent {0} when placing message {1} in region {2}", avatarID, evMap["message"], m_scene.Name); } } catch (NullReferenceException e) { m_log.Error("[EVENTQUEUE] Caught exception: " + e); return false; } return true; } #endregion private void ClientClosed(UUID agentID, Scene scene) { //m_log.DebugFormat("[EVENTQUEUE]: Closed client {0} in region {1}", agentID, m_scene.RegionInfo.RegionName); lock (queues) queues.Remove(agentID); lock (m_AvatarQueueUUIDMapping) m_AvatarQueueUUIDMapping.Remove(agentID); lock (m_ids) { if (!m_ids.ContainsKey(agentID)) m_ids.Remove(agentID); } // m_log.DebugFormat("[EVENTQUEUE]: Deleted queues for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName); } /// <summary> /// Generate an Event Queue Get handler path for the given eqg uuid. /// </summary> /// <param name='eqgUuid'></param> private string GenerateEqgCapPath(UUID eqgUuid) { return string.Format("/CAPS/EQG/{0}/", eqgUuid); } public void OnRegisterCaps(UUID agentID, Caps caps) { // Register an event queue for the client if (DebugLevel > 0) m_log.DebugFormat( "[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}", agentID, caps, m_scene.RegionInfo.RegionName); UUID eventQueueGetUUID; Queue<OSD> queue; Random rnd = new Random(Environment.TickCount); int nrnd = rnd.Next(30000000); lock (queues) { if (queues.ContainsKey(agentID)) queue = queues[agentID]; else queue = null; if (queue == null) { queue = new Queue<OSD>(); queues[agentID] = queue; lock (m_AvatarQueueUUIDMapping) { eventQueueGetUUID = UUID.Random(); while(m_AvatarQueueUUIDMapping.ContainsKey(agentID)) eventQueueGetUUID = UUID.Random(); m_AvatarQueueUUIDMapping.Add(agentID, eventQueueGetUUID); } lock (m_ids) { if (!m_ids.ContainsKey(agentID)) m_ids.Add(agentID, nrnd); else m_ids[agentID]++; } } else { queue.Enqueue(null); queue.Enqueue(null); // one should be enough // reuse or not to reuse lock (m_AvatarQueueUUIDMapping) { // Reuse open queues. The client does! // Its reuse caps path not queues those are been reused already if (m_AvatarQueueUUIDMapping.ContainsKey(agentID)) { m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!"); eventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID]; lock (m_ids) { // change to negative numbers so they are changed at end of sending first marker // old data on a queue may be sent on a response for a new caps // but at least will be sent with coerent IDs if (!m_ids.ContainsKey(agentID)) m_ids.Add(agentID, -nrnd); // should not happen else m_ids[agentID] = -m_ids[agentID]; } } else { eventQueueGetUUID = UUID.Random(); while(m_AvatarQueueUUIDMapping.ContainsKey(agentID)) eventQueueGetUUID = UUID.Random(); m_AvatarQueueUUIDMapping.Add(agentID, eventQueueGetUUID); m_log.DebugFormat("[EVENTQUEUE]: Using random UUID!"); lock (m_ids) { if (!m_ids.ContainsKey(agentID)) m_ids.Add(agentID, nrnd); else m_ids[agentID]++; } } } } } caps.RegisterPollHandler( "EventQueueGet", new PollServiceEventArgs(null, GenerateEqgCapPath(eventQueueGetUUID), HasEvents, GetEvents, NoEvents, Drop, agentID, SERVER_EQ_TIME_NO_EVENTS)); } public bool HasEvents(UUID requestID, UUID agentID) { Queue<OSD> queue = GetQueue(agentID); if (queue != null) lock (queue) { //m_log.WarnFormat("POLLED FOR EVENTS BY {0} in {1} -- {2}", agentID, m_scene.RegionInfo.RegionName, queue.Count); return queue.Count > 0; } //m_log.WarnFormat("POLLED FOR EVENTS BY {0} unknown agent", agentID); return true; } /// <summary> /// Logs a debug line for an outbound event queue message if appropriate. /// </summary> /// <param name='element'>Element containing message</param> private void LogOutboundDebugMessage(OSD element, UUID agentId) { if (element is OSDMap) { OSDMap ev = (OSDMap)element; m_log.DebugFormat( "Eq OUT {0,-30} to {1,-20} {2,-20}", ev["message"], m_scene.GetScenePresence(agentId).Name, m_scene.Name); } } public void Drop(UUID requestID, UUID pAgentId) { // do nothing for now, hope client close will do it } public Hashtable GetEvents(UUID requestID, UUID pAgentId) { if (DebugLevel >= 2) m_log.WarnFormat("POLLED FOR EQ MESSAGES BY {0} in {1}", pAgentId, m_scene.Name); Queue<OSD> queue = GetQueue(pAgentId); if (queue == null) { return NoEvents(requestID, pAgentId); } OSD element = null;; OSDArray array = new OSDArray(); int thisID = 0; bool negativeID = false; lock (queue) { if (queue.Count == 0) return NoEvents(requestID, pAgentId); lock (m_ids) thisID = m_ids[pAgentId]; if (thisID < 0) { negativeID = true; thisID = -thisID; } while (queue.Count > 0) { element = queue.Dequeue(); // add elements until a marker is found // so they get into a response if (element == null) break; if (DebugLevel > 0) LogOutboundDebugMessage(element, pAgentId); array.Add(element); } } OSDMap events = null; if (array.Count > 0) { events = new OSDMap(); events.Add("events", array); events.Add("id", new OSDInteger(thisID)); } if (negativeID && element == null) { Random rnd = new Random(Environment.TickCount); thisID = rnd.Next(30000000); } lock (m_ids) { m_ids[pAgentId] = thisID + 1; } Hashtable responsedata; // if there where no elements before a marker send a NoEvents if (events == null) { return NoEvents(requestID, pAgentId); } else { responsedata = new Hashtable(); responsedata["int_response_code"] = 200; responsedata["content_type"] = "application/xml"; responsedata["bin_response_data"] = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(events)); } //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", pAgentId, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]); return responsedata; } public Hashtable NoEvents(UUID requestID, UUID agentID) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 502; responsedata["content_type"] = "text/plain"; responsedata["str_response_string"] = "<llsd></llsd>"; responsedata["error_status_text"] = "<llsd></llsd>"; responsedata["http_protocol_version"] = "HTTP/1.0"; responsedata["keepalive"] = false; return responsedata; } /* this is not a event message public void DisableSimulator(ulong handle, UUID avatarID) { OSD item = EventQueueHelper.DisableSimulator(handle); Enqueue(item, avatarID); } */ public virtual void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY) { if (DebugLevel > 0) m_log.DebugFormat("{0} EnableSimulator. handle={1}, endPoint={2}, avatarID={3}", LogHeader, handle, endPoint, avatarID, regionSizeX, regionSizeY); OSD item = EventQueueHelper.EnableSimulator(handle, endPoint, regionSizeX, regionSizeY); Enqueue(item, avatarID); } public virtual void EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoint, string capsPath, ulong regionHandle, int regionSizeX, int regionSizeY) { if (DebugLevel > 0) m_log.DebugFormat("{0} EstablishAgentCommunication. handle={1}, endPoint={2}, avatarID={3}", LogHeader, regionHandle, endPoint, avatarID, regionSizeX, regionSizeY); OSD item = EventQueueHelper.EstablishAgentCommunication(avatarID, endPoint.ToString(), capsPath, regionHandle, regionSizeX, regionSizeY); Enqueue(item, avatarID); } public virtual void TeleportFinishEvent(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL, UUID avatarID, int regionSizeX, int regionSizeY) { if (DebugLevel > 0) m_log.DebugFormat("{0} TeleportFinishEvent. handle={1}, endPoint={2}, avatarID={3}", LogHeader, regionHandle, regionExternalEndPoint, avatarID, regionSizeX, regionSizeY); OSD item = EventQueueHelper.TeleportFinishEvent(regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL, avatarID, regionSizeX, regionSizeY); Enqueue(item, avatarID); } public virtual void CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL, UUID avatarID, UUID sessionID, int regionSizeX, int regionSizeY) { if (DebugLevel > 0) m_log.DebugFormat("{0} CrossRegion. handle={1}, avatarID={2}, regionSize={3},{4}>", LogHeader, handle, avatarID, regionSizeX, regionSizeY); OSD item = EventQueueHelper.CrossRegion(handle, pos, lookAt, newRegionExternalEndPoint, capsURL, avatarID, sessionID, regionSizeX, regionSizeY); Enqueue(item, avatarID); } public void ChatterboxInvitation(UUID sessionID, string sessionName, UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket) { OSD item = EventQueueHelper.ChatterboxInvitation(sessionID, sessionName, fromAgent, message, toAgent, fromName, dialog, timeStamp, offline, parentEstateID, position, ttl, transactionID, fromGroup, binaryBucket); Enqueue(item, toAgent); //m_log.InfoFormat("########### eq ChatterboxInvitation #############\n{0}", item); } public void ChatterBoxSessionAgentListUpdates(UUID sessionID, UUID fromAgent, UUID toAgent, bool canVoiceChat, bool isModerator, bool textMute, bool isEnterorLeave) { OSD item = EventQueueHelper.ChatterBoxSessionAgentListUpdates(sessionID, fromAgent, canVoiceChat, isModerator, textMute, isEnterorLeave); Enqueue(item, toAgent); //m_log.InfoFormat("########### eq ChatterBoxSessionAgentListUpdates #############\n{0}", item); } public void ChatterBoxForceClose(UUID toAgent, UUID sessionID, string reason) { OSD item = EventQueueHelper.ChatterBoxForceClose(sessionID, reason); Enqueue(item, toAgent); } public void ParcelProperties(ParcelPropertiesMessage parcelPropertiesMessage, UUID avatarID) { OSD item = EventQueueHelper.ParcelProperties(parcelPropertiesMessage); Enqueue(item, avatarID); } public void GroupMembershipData(UUID receiverAgent, GroupMembershipData[] data) { OSD item = EventQueueHelper.GroupMembershipData(receiverAgent, data); Enqueue(item, receiverAgent); } public void QueryReply(PlacesReplyPacket groupUpdate, UUID avatarID) { OSD item = EventQueueHelper.PlacesQuery(groupUpdate); Enqueue(item, avatarID); } public OSD ScriptRunningEvent(UUID objectID, UUID itemID, bool running, bool mono) { return EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, running, mono); } public OSD BuildEvent(string eventName, OSD eventBody) { return EventQueueHelper.BuildEvent(eventName, eventBody); } public void partPhysicsProperties(uint localID, byte physhapetype, float density, float friction, float bounce, float gravmod,UUID avatarID) { OSD item = EventQueueHelper.partPhysicsProperties(localID, physhapetype, density, friction, bounce, gravmod); Enqueue(item, avatarID); } } }
/* * ****************************************************************************** * Copyright 2014-2016 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetTapeFailuresSpectraS3Request : Ds3Request { private string _errorMessage; public string ErrorMessage { get { return _errorMessage; } set { WithErrorMessage(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } private string _tapeDriveId; public string TapeDriveId { get { return _tapeDriveId; } set { WithTapeDriveId(value); } } private string _tapeId; public string TapeId { get { return _tapeId; } set { WithTapeId(value); } } private TapeFailureType? _type; public TapeFailureType? Type { get { return _type; } set { WithType(value); } } public GetTapeFailuresSpectraS3Request WithErrorMessage(string errorMessage) { this._errorMessage = errorMessage; if (errorMessage != null) { this.QueryParams.Add("error_message", errorMessage); } else { this.QueryParams.Remove("error_message"); } return this; } public GetTapeFailuresSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetTapeFailuresSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetTapeFailuresSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetTapeFailuresSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetTapeFailuresSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetTapeFailuresSpectraS3Request WithTapeDriveId(Guid? tapeDriveId) { this._tapeDriveId = tapeDriveId.ToString(); if (tapeDriveId != null) { this.QueryParams.Add("tape_drive_id", tapeDriveId.ToString()); } else { this.QueryParams.Remove("tape_drive_id"); } return this; } public GetTapeFailuresSpectraS3Request WithTapeDriveId(string tapeDriveId) { this._tapeDriveId = tapeDriveId; if (tapeDriveId != null) { this.QueryParams.Add("tape_drive_id", tapeDriveId); } else { this.QueryParams.Remove("tape_drive_id"); } return this; } public GetTapeFailuresSpectraS3Request WithTapeId(Guid? tapeId) { this._tapeId = tapeId.ToString(); if (tapeId != null) { this.QueryParams.Add("tape_id", tapeId.ToString()); } else { this.QueryParams.Remove("tape_id"); } return this; } public GetTapeFailuresSpectraS3Request WithTapeId(string tapeId) { this._tapeId = tapeId; if (tapeId != null) { this.QueryParams.Add("tape_id", tapeId); } else { this.QueryParams.Remove("tape_id"); } return this; } public GetTapeFailuresSpectraS3Request WithType(TapeFailureType? type) { this._type = type; if (type != null) { this.QueryParams.Add("type", type.ToString()); } else { this.QueryParams.Remove("type"); } return this; } public GetTapeFailuresSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/tape_failure"; } } } }
using GuiLabs.Canvas.Controls; namespace GuiLabs.Editor.CSharp { partial class OptionsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Tabs = new System.Windows.Forms.TabControl(); this.tabAppearance = new System.Windows.Forms.TabPage(); this.FontSizeBox = new System.Windows.Forms.NumericUpDown(); this.CurlyCombo = new GuiLabs.Editor.CSharp.CurlyTypeCombo(); this.DesignOfUniversalControlCombo = new GuiLabs.Editor.CSharp.UniversalControlDesignCombo(); this.lblFontSize = new System.Windows.Forms.Label(); this.lblCurlyType = new System.Windows.Forms.Label(); this.lblDesignOfUniversalControl = new System.Windows.Forms.Label(); this.TabStyles = new System.Windows.Forms.TabPage(); this.LoadFromFileButton = new System.Windows.Forms.Button(); this.WriteToFileButton = new System.Windows.Forms.Button(); this.StylesProperties = new GuiLabs.Canvas.DrawStyle.StyleListEditor(); this.CloseButton = new System.Windows.Forms.Button(); this.Tabs.SuspendLayout(); this.tabAppearance.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.FontSizeBox)).BeginInit(); this.TabStyles.SuspendLayout(); this.SuspendLayout(); // // Tabs // this.Tabs.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.Tabs.Controls.Add(this.tabAppearance); this.Tabs.Controls.Add(this.TabStyles); this.Tabs.Location = new System.Drawing.Point(13, 13); this.Tabs.Name = "Tabs"; this.Tabs.SelectedIndex = 0; this.Tabs.Size = new System.Drawing.Size(667, 571); this.Tabs.TabIndex = 0; // // tabAppearance // this.tabAppearance.Controls.Add(this.FontSizeBox); this.tabAppearance.Controls.Add(this.CurlyCombo); this.tabAppearance.Controls.Add(this.DesignOfUniversalControlCombo); this.tabAppearance.Controls.Add(this.lblFontSize); this.tabAppearance.Controls.Add(this.lblCurlyType); this.tabAppearance.Controls.Add(this.lblDesignOfUniversalControl); this.tabAppearance.Location = new System.Drawing.Point(4, 25); this.tabAppearance.Name = "tabAppearance"; this.tabAppearance.Padding = new System.Windows.Forms.Padding(3); this.tabAppearance.Size = new System.Drawing.Size(659, 542); this.tabAppearance.TabIndex = 1; this.tabAppearance.Text = "Appearance"; this.tabAppearance.UseVisualStyleBackColor = true; // // FontSizeBox // this.FontSizeBox.Location = new System.Drawing.Point(192, 88); this.FontSizeBox.Minimum = new decimal(new int[] { 4, 0, 0, 0}); this.FontSizeBox.Name = "FontSizeBox"; this.FontSizeBox.Size = new System.Drawing.Size(64, 22); this.FontSizeBox.TabIndex = 4; this.FontSizeBox.Value = new decimal(new int[] { 10, 0, 0, 0}); this.FontSizeBox.ValueChanged += new System.EventHandler(this.FontSizeBox_ValueChanged); // // CurlyCombo // this.CurlyCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CurlyCombo.FormattingEnabled = true; this.CurlyCombo.Location = new System.Drawing.Point(192, 48); this.CurlyCombo.Name = "CurlyCombo"; this.CurlyCombo.Size = new System.Drawing.Size(232, 24); this.CurlyCombo.TabIndex = 3; // // DesignOfUniversalControlCombo // this.DesignOfUniversalControlCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.DesignOfUniversalControlCombo.FormattingEnabled = true; this.DesignOfUniversalControlCombo.Location = new System.Drawing.Point(192, 8); this.DesignOfUniversalControlCombo.Name = "DesignOfUniversalControlCombo"; this.DesignOfUniversalControlCombo.Size = new System.Drawing.Size(232, 24); this.DesignOfUniversalControlCombo.TabIndex = 2; // // lblFontSize // this.lblFontSize.AutoSize = true; this.lblFontSize.Location = new System.Drawing.Point(8, 88); this.lblFontSize.Name = "lblFontSize"; this.lblFontSize.Size = new System.Drawing.Size(65, 17); this.lblFontSize.TabIndex = 1; this.lblFontSize.Text = "Font size"; // // lblCurlyType // this.lblCurlyType.AutoSize = true; this.lblCurlyType.Location = new System.Drawing.Point(8, 48); this.lblCurlyType.Name = "lblCurlyType"; this.lblCurlyType.Size = new System.Drawing.Size(87, 17); this.lblCurlyType.TabIndex = 1; this.lblCurlyType.Text = "Curly braces"; // // lblDesignOfUniversalControl // this.lblDesignOfUniversalControl.AutoSize = true; this.lblDesignOfUniversalControl.Location = new System.Drawing.Point(8, 8); this.lblDesignOfUniversalControl.Name = "lblDesignOfUniversalControl"; this.lblDesignOfUniversalControl.Size = new System.Drawing.Size(176, 17); this.lblDesignOfUniversalControl.TabIndex = 1; this.lblDesignOfUniversalControl.Text = "Design of universal control"; // // TabStyles // this.TabStyles.Controls.Add(this.LoadFromFileButton); this.TabStyles.Controls.Add(this.WriteToFileButton); this.TabStyles.Controls.Add(this.StylesProperties); this.TabStyles.Location = new System.Drawing.Point(4, 25); this.TabStyles.Name = "TabStyles"; this.TabStyles.Padding = new System.Windows.Forms.Padding(3); this.TabStyles.Size = new System.Drawing.Size(659, 542); this.TabStyles.TabIndex = 2; this.TabStyles.Text = "Styles"; this.TabStyles.UseVisualStyleBackColor = true; // // LoadFromFileButton // this.LoadFromFileButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.LoadFromFileButton.Location = new System.Drawing.Point(168, 496); this.LoadFromFileButton.Name = "LoadFromFileButton"; this.LoadFromFileButton.Size = new System.Drawing.Size(144, 32); this.LoadFromFileButton.TabIndex = 1; this.LoadFromFileButton.Text = "Read from file..."; this.LoadFromFileButton.UseVisualStyleBackColor = true; this.LoadFromFileButton.Click += new System.EventHandler(this.LoadFromFileButton_Click); // // WriteToFileButton // this.WriteToFileButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.WriteToFileButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.WriteToFileButton.Location = new System.Drawing.Point(8, 496); this.WriteToFileButton.Name = "WriteToFileButton"; this.WriteToFileButton.Size = new System.Drawing.Size(144, 32); this.WriteToFileButton.TabIndex = 1; this.WriteToFileButton.Text = "Write to file..."; this.WriteToFileButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.WriteToFileButton.UseVisualStyleBackColor = true; this.WriteToFileButton.Click += new System.EventHandler(this.WriteToFileButton_Click); // // StylesProperties // this.StylesProperties.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.StylesProperties.Location = new System.Drawing.Point(3, 3); this.StylesProperties.Name = "StylesProperties"; this.StylesProperties.Size = new System.Drawing.Size(643, 485); this.StylesProperties.TabIndex = 0; // // CloseButton // this.CloseButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.CloseButton.Location = new System.Drawing.Point(586, 598); this.CloseButton.Name = "CloseButton"; this.CloseButton.Size = new System.Drawing.Size(94, 28); this.CloseButton.TabIndex = 1; this.CloseButton.Text = "Close"; this.CloseButton.UseVisualStyleBackColor = true; this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click); // // OptionsForm // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.CancelButton = this.CloseButton; this.ClientSize = new System.Drawing.Size(692, 638); this.Controls.Add(this.CloseButton); this.Controls.Add(this.Tabs); this.KeyPreview = true; this.Name = "OptionsForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "OptionsForm"; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OptionsForm_KeyDown); this.Tabs.ResumeLayout(false); this.tabAppearance.ResumeLayout(false); this.tabAppearance.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.FontSizeBox)).EndInit(); this.TabStyles.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl Tabs; private System.Windows.Forms.Button CloseButton; private System.Windows.Forms.TabPage tabAppearance; private System.Windows.Forms.Label lblDesignOfUniversalControl; private UniversalControlDesignCombo DesignOfUniversalControlCombo; private CurlyTypeCombo CurlyCombo; private System.Windows.Forms.Label lblCurlyType; private System.Windows.Forms.NumericUpDown FontSizeBox; private System.Windows.Forms.Label lblFontSize; private System.Windows.Forms.TabPage TabStyles; private GuiLabs.Canvas.DrawStyle.StyleListEditor StylesProperties; private System.Windows.Forms.Button LoadFromFileButton; private System.Windows.Forms.Button WriteToFileButton; } }
// Copyright (c) morrisjdev. All rights reserved. // Original copyright (c) .NET Foundation. All rights reserved. // Modified version by morrisjdev // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using FileContextCore.Diagnostics; using FileContextCore.FileManager; using FileContextCore.Infrastructure; using FileContextCore.Infrastructure.Internal; using FileContextCore.Serializer; using FileContextCore.Storage; using FileContextCore.StoreManager; using FileContextCore.Utilities; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; // ReSharper disable once CheckNamespace namespace FileContextCore { /// <summary> /// FileContextCore specific extension methods for <see cref="DbContextOptionsBuilder" />. /// </summary> public static class FileContextDbContextOptionsExtensions { #region NothingConfiguredUseJsonAndDefaultFileManager /// <summary> /// Configures the context to connect to an in-memory database. /// The in-memory database is shared anywhere the same name is used, but only for a given /// service provider. /// </summary> /// <typeparam name="TContext"> The type of context being configured. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="databaseName"> /// The name of the in-memory database. This allows the scope of the in-memory database to be controlled /// independently of the context. The in-memory database is shared anywhere the same name is used. /// </param> /// <param name="location">An optional parameter to define the location where the files are stored</param> /// <param name="password">An optional parameter to define a password if needed by store manager, serializer or file manager</param> /// <param name="databaseRoot"> /// All in-memory databases will be rooted in this object, allowing the application /// to control their lifetime. This is useful when sometimes the context instance /// is created explicitly with <c>new</c> while at other times it is resolved using dependency injection. /// </param> /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder<TContext> UseFileContextDatabase<TContext>( [NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder, string databaseName = "", string location = null, string password = null, [CanBeNull] FileContextDatabaseRoot databaseRoot = null, [CanBeNull] Action<FileContextDbContextOptionsBuilder> inMemoryOptionsAction = null) where TContext : DbContext => (DbContextOptionsBuilder<TContext>) UseFileContextDatabase( (DbContextOptionsBuilder) optionsBuilder, databaseName, location, password, databaseRoot, inMemoryOptionsAction); /// <summary> /// Configures the context to connect to a named in-memory database. /// The in-memory database is shared anywhere the same name is used, but only for a given /// service provider. /// </summary> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="databaseName"> /// The name of the in-memory database. This allows the scope of the in-memory database to be controlled /// independently of the context. The in-memory database is shared anywhere the same name is used. /// </param> /// <param name="location">An optional parameter to define the location where the files are stored</param> /// <param name="password">An optional parameter to define a password if needed by store manager, serializer or file manager</param> /// <param name="databaseRoot"> /// All in-memory databases will be rooted in this object, allowing the application /// to control their lifetime. This is useful when sometimes the context instance /// is created explicitly with <c>new</c> while at other times it is resolved using dependency injection. /// </param> /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder UseFileContextDatabase( [NotNull] this DbContextOptionsBuilder optionsBuilder, string databaseName = "", string location = null, string password = null, [CanBeNull] FileContextDatabaseRoot databaseRoot = null, [CanBeNull] Action<FileContextDbContextOptionsBuilder> inMemoryOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); var extension = optionsBuilder.Options.FindExtension<FileContextOptionsExtension>() ?? new FileContextOptionsExtension(); extension = extension.WithCustomOptions(databaseName, location, password, typeof(DefaultStoreManager), typeof(JSONSerializer), typeof(DefaultFileManager)); if (databaseRoot != null) { extension = extension.WithDatabaseRoot(databaseRoot); } ConfigureWarnings(optionsBuilder); ((IDbContextOptionsBuilderInfrastructure) optionsBuilder).AddOrUpdateExtension(extension); inMemoryOptionsAction?.Invoke(new FileContextDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } #endregion #region UseDefaultStoreManagerWithSerializerAndFileManager /// <summary> /// Configures the context to connect to an in-memory database. /// The in-memory database is shared anywhere the same name is used, but only for a given /// service provider. /// </summary> /// <typeparam name="TContext"> The type of context being configured. </typeparam> /// <typeparam name="TSerializer"> The type of the serializer to be used. </typeparam> /// <typeparam name="TFileManager"> The type of the file manager to be used. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="databaseName"> /// The name of the in-memory database. This allows the scope of the in-memory database to be controlled /// independently of the context. The in-memory database is shared anywhere the same name is used. /// </param> /// <param name="location">An optional parameter to define the location where the files are stored</param> /// <param name="password">An optional parameter to define a password if needed by store manager, serializer or file manager</param> /// <param name="databaseRoot"> /// All in-memory databases will be rooted in this object, allowing the application /// to control their lifetime. This is useful when sometimes the context instance /// is created explicitly with <c>new</c> while at other times it is resolved using dependency injection. /// </param> /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder<TContext> UseFileContextDatabase<TContext, TSerializer, TFileManager>( [NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder, string databaseName = "", string location = null, string password = null, [CanBeNull] FileContextDatabaseRoot databaseRoot = null, [CanBeNull] Action<FileContextDbContextOptionsBuilder> inMemoryOptionsAction = null) where TContext : DbContext where TSerializer : ISerializer where TFileManager : IFileManager => (DbContextOptionsBuilder<TContext>) UseFileContextDatabase<TSerializer, TFileManager>( optionsBuilder, databaseName, location, password, databaseRoot, inMemoryOptionsAction); /// <summary> /// Configures the context to connect to a named in-memory database. /// The in-memory database is shared anywhere the same name is used, but only for a given /// service provider. /// </summary> /// <typeparam name="TSerializer"> The type of the serializer to be used. </typeparam> /// <typeparam name="TFileManager"> The type of the file manager to be used. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="databaseName"> /// The name of the in-memory database. This allows the scope of the in-memory database to be controlled /// independently of the context. The in-memory database is shared anywhere the same name is used. /// </param> /// <param name="location">An optional parameter to define the location where the files are stored</param> /// <param name="password">An optional parameter to define a password if needed by store manager, serializer or file manager</param> /// <param name="databaseRoot"> /// All in-memory databases will be rooted in this object, allowing the application /// to control their lifetime. This is useful when sometimes the context instance /// is created explicitly with <c>new</c> while at other times it is resolved using dependency injection. /// </param> /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder UseFileContextDatabase<TSerializer, TFileManager>( [NotNull] this DbContextOptionsBuilder optionsBuilder, string databaseName = "", string location = null, string password = null, [CanBeNull] FileContextDatabaseRoot databaseRoot = null, [CanBeNull] Action<FileContextDbContextOptionsBuilder> inMemoryOptionsAction = null) where TSerializer : ISerializer where TFileManager : IFileManager { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); var extension = optionsBuilder.Options.FindExtension<FileContextOptionsExtension>() ?? new FileContextOptionsExtension(); extension = extension.WithCustomOptions(databaseName, location, password, typeof(DefaultStoreManager), typeof(TSerializer), typeof(TFileManager)); if (databaseRoot != null) { extension = extension.WithDatabaseRoot(databaseRoot); } ConfigureWarnings(optionsBuilder); ((IDbContextOptionsBuilderInfrastructure) optionsBuilder).AddOrUpdateExtension(extension); inMemoryOptionsAction?.Invoke(new FileContextDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } #endregion #region UseCustomStoreManager /// <summary> /// Configures the context to connect to an in-memory database. /// The in-memory database is shared anywhere the same name is used, but only for a given /// service provider. /// </summary> /// <typeparam name="TContext"> The type of context being configured. </typeparam> /// <typeparam name="TStoreManager"> The type of the store manager to be used. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="databaseName"> /// The name of the in-memory database. This allows the scope of the in-memory database to be controlled /// independently of the context. The in-memory database is shared anywhere the same name is used. /// </param> /// <param name="location">An optional parameter to define the location where the files are stored</param> /// <param name="password">An optional parameter to define a password if needed by store manager, serializer or file manager</param> /// <param name="databaseRoot"> /// All in-memory databases will be rooted in this object, allowing the application /// to control their lifetime. This is useful when sometimes the context instance /// is created explicitly with <c>new</c> while at other times it is resolved using dependency injection. /// </param> /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder<TContext> UseFileContextDatabase<TContext, TStoreManager>( [NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder, string databaseName = "", string location = null, string password = null, [CanBeNull] FileContextDatabaseRoot databaseRoot = null, [CanBeNull] Action<FileContextDbContextOptionsBuilder> inMemoryOptionsAction = null) where TContext : DbContext where TStoreManager : IStoreManager => (DbContextOptionsBuilder<TContext>) UseFileContextDatabase<TStoreManager>( optionsBuilder, databaseName, location, password, databaseRoot, inMemoryOptionsAction); /// <summary> /// Configures the context to connect to a named in-memory database. /// The in-memory database is shared anywhere the same name is used, but only for a given /// service provider. /// </summary> /// <typeparam name="TStoreManager"> The type of the store manager to be used. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="databaseName"> /// The name of the in-memory database. This allows the scope of the in-memory database to be controlled /// independently of the context. The in-memory database is shared anywhere the same name is used. /// </param> /// <param name="location">An optional parameter to define the location where the files are stored</param> /// <param name="password">An optional parameter to define a password if needed by store manager, serializer or file manager</param> /// <param name="databaseRoot"> /// All in-memory databases will be rooted in this object, allowing the application /// to control their lifetime. This is useful when sometimes the context instance /// is created explicitly with <c>new</c> while at other times it is resolved using dependency injection. /// </param> /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder UseFileContextDatabase<TStoreManager>( [NotNull] this DbContextOptionsBuilder optionsBuilder, string databaseName = "", string location = null, string password = null, [CanBeNull] FileContextDatabaseRoot databaseRoot = null, [CanBeNull] Action<FileContextDbContextOptionsBuilder> inMemoryOptionsAction = null) where TStoreManager : IStoreManager { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); var extension = optionsBuilder.Options.FindExtension<FileContextOptionsExtension>() ?? new FileContextOptionsExtension(); extension = extension.WithCustomOptions(databaseName, location, password, typeof(TStoreManager), null, null); if (databaseRoot != null) { extension = extension.WithDatabaseRoot(databaseRoot); } ConfigureWarnings(optionsBuilder); ((IDbContextOptionsBuilderInfrastructure) optionsBuilder).AddOrUpdateExtension(extension); inMemoryOptionsAction?.Invoke(new FileContextDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } #endregion private static void ConfigureWarnings(DbContextOptionsBuilder optionsBuilder) { // Set warnings defaults var coreOptionsExtension = optionsBuilder.Options.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension(); coreOptionsExtension = coreOptionsExtension.WithWarningsConfiguration( coreOptionsExtension.WarningsConfiguration.TryWithExplicit( FileContextEventId.TransactionIgnoredWarning, WarningBehavior.Throw)); ((IDbContextOptionsBuilderInfrastructure) optionsBuilder).AddOrUpdateExtension(coreOptionsExtension); } } }
// 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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class HoistedStateMachineLocalTests : ExpressionCompilerTestBase { private const string asyncLambdaSourceTemplate = @" using System; using System.Threading.Tasks; public class D {{ private double t; public {0} void M(char u) {{ int x = 1; Func<char, Task<int>> f = async ch => {1}; }} }} "; private const string genericAsyncLambdaSourceTemplate = @" using System; using System.Threading.Tasks; public class D<T> {{ private T t; public {0} void M<U>(U u) {{ int x = 1; Func<char, Task<int>> f = async ch => {1}; }} }} "; [Fact] public void Iterator() { var source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { #line 500 DummySequencePoint(); { #line 550 int x = 0; yield return x; x++; #line 600 } #line 650 DummySequencePoint(); { #line 700 int x = 0; yield return x; x++; #line 750 } #line 800 DummySequencePoint(); } static void DummySequencePoint() { } } "; var expectedError = "error CS0103: The name 'x' does not exist in the current context"; var expectedIlTemplate = @" {{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, bool V_1, int V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.{0}"" IL_0006: ret }} "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); EvaluationContext context; CompilationTestData testData; string error; context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 500); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 550); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 600); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 650); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 700); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 750); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 800); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); } [Fact] public void Async() { var source = @" using System.Threading.Tasks; class C { static async Task M() { #line 500 DummySequencePoint(); { #line 550 int x = 0; await M(); x++; #line 600 } #line 650 DummySequencePoint(); { #line 700 int x = 0; await M(); x++; #line 750 } #line 800 DummySequencePoint(); } static void DummySequencePoint() { } } "; var expectedError = "error CS0103: The name 'x' does not exist in the current context"; var expectedIlTemplate = @" {{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<M>d__0 V_2, int V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.{0}"" IL_0006: ret }} "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); EvaluationContext context; CompilationTestData testData; string error; context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 500); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 550); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 600); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__1")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 650); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 700); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); testData = new CompilationTestData(); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 750); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(string.Format(expectedIlTemplate, "<x>5__2")); context = CreateMethodContext(runtime, "C.<M>d__0.MoveNext", atLineNumber: 800); context.CompileExpression("x", out error); Assert.Equal(expectedError, error); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Instance_CaptureNothing() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Instance_CaptureLocal() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D.<>c__DisplayClass1_0.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "x"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Instance_CaptureParameter() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""char D.<>c__DisplayClass1_0.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "u"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Instance_CaptureLambdaParameter() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Instance_CaptureThis() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D D.<<M>b__1_0>d.<>4__this"" IL_0006: ldfld ""double D.t"" IL_000b: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "this", "ch"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Instance_CaptureThisAndLocal() { var source = string.Format(asyncLambdaSourceTemplate, "/*instance*/", "x + t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""D D.<>c__DisplayClass1_0.<>4__this"" IL_000b: ldfld ""double D.t"" IL_0010: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D.<>c__DisplayClass1_0.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "this", "ch", "x"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Static_CaptureNothing() { var source = string.Format(asyncLambdaSourceTemplate, "static", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Static_CaptureLocal() { var source = string.Format(asyncLambdaSourceTemplate, "static", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D.<>c__DisplayClass1_0.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "x"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Static_CaptureParameter() { var source = string.Format(asyncLambdaSourceTemplate, "static", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D.<>c__DisplayClass1_0 D.<>c__DisplayClass1_0.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""char D.<>c__DisplayClass1_0.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c__DisplayClass1_0.<<M>b__0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch", "u"); } [WorkItem(1112496)] [Fact] public void AsyncLambda_Static_CaptureLambdaParameter() { var source = string.Format(asyncLambdaSourceTemplate, "static", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D.<>c.<<M>b__1_0>d.ch"" IL_0006: ret } "); AssertEx.SetEqual(GetLocalNames(context), "ch"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Instance_CaptureNothing() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Instance_CaptureLocal() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D<T>.<>c__DisplayClass1_0<U>.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "x", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Instance_CaptureParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""U D<T>.<>c__DisplayClass1_0<U>.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "u", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Instance_CaptureLambdaParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Instance_CaptureThis() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T> D<T>.<<M>b__1_0>d<U>.<>4__this"" IL_0006: ldfld ""T D<T>.t"" IL_000b: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<<M>b__1_0>d<U>.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "this", "ch", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Instance_CaptureThisAndLocal() { var source = string.Format(genericAsyncLambdaSourceTemplate, "/*instance*/", "x + t.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; testData = new CompilationTestData(); context.CompileExpression("t", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""D<T> D<T>.<>c__DisplayClass1_0<U>.<>4__this"" IL_000b: ldfld ""T D<T>.t"" IL_0010: ret } "); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D<T>.<>c__DisplayClass1_0<U>.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "this", "ch", "x", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Static_CaptureNothing() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "1"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Static_CaptureLocal() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "x"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("x", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""int D<T>.<>c__DisplayClass1_0<U>.x"" IL_000b: ret } "); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "x", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Static_CaptureParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "u.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__DisplayClass1_0.<<M>b__0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); testData = new CompilationTestData(); context.CompileExpression("u", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""D<T>.<>c__DisplayClass1_0<U> D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.<>4__this"" IL_0006: ldfld ""U D<T>.<>c__DisplayClass1_0<U>.u"" IL_000b: ret } "); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__DisplayClass1_0<U>.<<M>b__0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "u", "<>TypeVariables"); } [WorkItem(1112496)] [Fact] public void GenericAsyncLambda_Static_CaptureLambdaParameter() { var source = string.Format(genericAsyncLambdaSourceTemplate, "static", "ch.GetHashCode()"); var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, "D.<>c__1.<<M>b__1_0>d.MoveNext"); string error; CompilationTestData testData; context.CompileExpression("t", out error); Assert.Equal("error CS0120: An object reference is required for the non-static field, method, or property 'D<T>.t'", error); context.CompileExpression("u", out error); Assert.Equal("error CS0103: The name 'u' does not exist in the current context", error); context.CompileExpression("x", out error); Assert.Equal("error CS0103: The name 'x' does not exist in the current context", error); testData = new CompilationTestData(); context.CompileExpression("ch", out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T, U>.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, int V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""char D<T>.<>c__1<U>.<<M>b__1_0>d.ch"" IL_0006: ret } "); context.CompileExpression("typeof(T)", out error); Assert.Null(error); context.CompileExpression("typeof(U)", out error); Assert.Null(error); AssertEx.SetEqual(GetLocalNames(context), "ch", "<>TypeVariables"); } private static string[] GetLocalNames(EvaluationContext context) { string unused; var locals = new ArrayBuilder<LocalAndMethod>(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out unused); return locals.Select(l => l.LocalName).ToArray(); } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Drawing; using System.Windows.Forms; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.VisualStudio.Project.UnitTests { [TestClass] public class ImageHandlerTest { private static void VerifySameBitmap(Bitmap expected, Bitmap actual) { // The size should be the same. Assert.AreEqual<int>(expected.Height, actual.Height); Assert.AreEqual<int>(expected.Width, actual.Width); // every pixel should match. for(int x = 0; x < expected.Width; ++x) { for(int y = 0; y < expected.Height; ++y) { Assert.AreEqual<Color>(expected.GetPixel(x, y), actual.GetPixel(x, y), "Pixel ({0}, {1}) is different in the two bitmaps", x, y); } } } [TestMethod] public void ImageHandlerConstructors() { // Default constructor. ImageHandler handler = new ImageHandler(); Assert.IsNull(handler.ImageList); // Constructor from resource stream. System.IO.Stream nullStream = null; Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { new ImageHandler(nullStream); })); try { handler = new ImageHandler(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(handler.ImageList); Assert.AreEqual<int>(3, handler.ImageList.Images.Count); } finally { handler.Close(); handler = null; } ImageList imageList = null; Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { new ImageHandler(imageList); })); imageList = Microsoft.VisualStudio.Shell.PackageUtilities.GetImageList(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(imageList); try { handler = new ImageHandler(imageList); Assert.IsNotNull(handler.ImageList); Assert.AreEqual<ImageList>(imageList, handler.ImageList); } finally { handler.Close(); handler = null; } } [TestMethod] public void ImageHandlerClose() { // Verify that it is possible to close an empty object. ImageHandler handler = new ImageHandler(); handler.Close(); // We can not verify that if the image handler is not empty, then // the image list is disposed, but we can verify that at least it // is released. handler = new ImageHandler(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(handler.ImageList); handler.Close(); Assert.IsNull(handler.ImageList); } [TestMethod] public void GetIconHandleTest() { // Verify the kind of exception when the ImageList is empty. ImageHandler handler = new ImageHandler(); Assert.IsTrue(Utilities.HasFunctionThrown<InvalidOperationException>(delegate { handler.GetIconHandle(0); })); try { // Set the image list property so that the object is no more empty. handler.ImageList = Microsoft.VisualStudio.Shell.PackageUtilities.GetImageList(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(handler.ImageList); // Verify the kind of exception in case of a bad index. Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentOutOfRangeException>(delegate { handler.GetIconHandle(-1); })); Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentOutOfRangeException>(delegate { handler.GetIconHandle(handler.ImageList.Images.Count); })); // Get the handle for one of the images IntPtr iconHandle = handler.GetIconHandle(1); Assert.AreNotEqual<IntPtr>(IntPtr.Zero, iconHandle); // Verify the image. Icon icon = Icon.FromHandle(iconHandle); Bitmap resultBmp = icon.ToBitmap(); Bitmap expectedBmp = handler.ImageList.Images[1] as Bitmap; // The bitmaps should match. VerifySameBitmap(expectedBmp, resultBmp); } finally { handler.Close(); } } [TestMethod] public void AddImageTest() { Bitmap newBmp = new Bitmap(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.Image1.bmp")); // Case 1: Add an image to an empty ImageHandler. ImageHandler handler = new ImageHandler(); try { Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { handler.AddImage(null); })); handler.AddImage(newBmp); Assert.IsNotNull(handler.ImageList); Assert.AreEqual(1, handler.ImageList.Images.Count); } finally { handler.Close(); } // Case 2: Add a new image to a not empty image handler handler = new ImageHandler(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); try { Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { handler.AddImage(null); })); handler.AddImage(newBmp); Assert.IsNotNull(handler.ImageList); Assert.AreEqual(4, handler.ImageList.Images.Count); // Verify that it is possible to get the icon handle for the // last (new) element in the list. IntPtr iconHandle = handler.GetIconHandle(3); Assert.AreNotEqual<IntPtr>(IntPtr.Zero, iconHandle); // Verify the image. Icon icon = Icon.FromHandle(iconHandle); Bitmap resultBmp = icon.ToBitmap(); Bitmap expectedBmp = handler.ImageList.Images[3] as Bitmap; VerifySameBitmap(expectedBmp, resultBmp); } finally { handler.Close(); } } } }
// 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 Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public class DocCommentFormatterTests { private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string docCommentXmlFragment, string expected) { TestFormat(docCommentXmlFragment, expected, expected); } private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB) { var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment); var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment)); var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment)); Assert.Equal(expectedCSharp, csharpFormattedComment); Assert.Equal(expectedVB, vbFormattedComment); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Summary() { var comment = "<summary>This is a summary.</summary>"; var expected = $@"{FeaturesResources.Summary} This is a summary."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping1() { var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>"; var expected = $@"{FeaturesResources.Summary} I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping2() { var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>"; var expected = $@"{FeaturesResources.Summary} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Exception() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>"; var expected = $@"{FeaturesResources.Exceptions} T:System.NotImplementedException: throws NotImplementedException"; TestFormat(comment, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTags() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>"; var expected = $@"{FeaturesResources.Exceptions} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, WorkItem(530760)] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTagsWithSameType() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception> <exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>"; var expected = $@"{FeaturesResources.Exceptions} T:System.NotImplementedException: throws NotImplementedException for reason X T:System.NotImplementedException: also throws NotImplementedException for reason Y T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Returns() { var comment = @"<returns>A string is returned</returns>"; var expected = $@"{FeaturesResources.Returns} A string is returned"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void SummaryAndParams() { var comment = @"<summary>This is the summary.</summary> <param name=""a"">The param named 'a'</param> <param name=""b"">The param named 'b'</param>"; var expected = $@"{FeaturesResources.Summary} This is the summary. {FeaturesResources.Parameters} a: The param named 'a' b: The param named 'b'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TypeParameters() { var comment = @"<typeparam name=""T"">The type param named 'T'</typeparam> <typeparam name=""U"">The type param named 'U'</typeparam>"; var expected = $@"{FeaturesResources.TypeParameters} T: The type param named 'T' U: The type param named 'U'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatEverything() { var comment = @"<summary> This is a summary of something. </summary> <param name=""a"">The param named 'a'.</param> <param name=""b""></param> <param name=""c"">The param named 'c'.</param> <typeparam name=""T"">A type parameter.</typeparam> <typeparam name=""U""></typeparam> <typeparam name=""V"">Another type parameter.</typeparam> <returns>This returns nothing.</returns> <exception cref=""System.FooException"">Thrown for an unknown reason</exception> <exception cref=""System.BarException""></exception> <exception cref=""System.BlahException"">Thrown when blah blah blah</exception> <remarks>This doc comment is really not very remarkable.</remarks>"; var expected = $@"{FeaturesResources.Summary} This is a summary of something. {FeaturesResources.Parameters} a: The param named 'a'. b: c: The param named 'c'. {FeaturesResources.TypeParameters} T: A type parameter. U: V: Another type parameter. {FeaturesResources.Returns} This returns nothing. {FeaturesResources.Exceptions} System.FooException: Thrown for an unknown reason System.BarException: System.BlahException: Thrown when blah blah blah {FeaturesResources.Remarks} This doc comment is really not very remarkable."; TestFormat(comment, expected); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace ConvertVideos { public abstract class Ffmpeg { public const string FIELD_CODEC_TYPE = "codec_type"; public const string STREAM_START = "[STREAM]"; public const string STREAM_END = "[/STREAM]"; public const string CODEC_TYPE_AUDIO = "audio"; public const string CODEC_TYPE_VIDEO = "video"; public static string FfmpegPath { get; set; } public static string FfprobePath { get; set; } // abstract methods - to be implemented by specific codec writers public abstract string OutputFileExtension { get; } public abstract void Convert(string infile, string outfile); public abstract void Convert(string infile, string outfile, int newWidth, int newHeight); public void ExtractFrame(string moviePath, string imagePath, int seconds) { var args = $"-i \"{moviePath}\" -ss 00:00:{seconds:00} -vframes 1 \"{imagePath}\""; ExecuteFfmpeg(args); } public MovieMetadata GatherMetadata(string file) { string data = CollectMovieMetadataFromFile(file); string[] lines = data.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); bool inStreamSection = false; Dictionary<string, string> dict = new Dictionary<string, string>(); Dictionary<string, string> vDic = null; Dictionary<string, string> aDic = null; foreach (string line in lines) { if (!inStreamSection) { if (string.Equals(line, STREAM_START, StringComparison.OrdinalIgnoreCase)) { inStreamSection = true; dict = new Dictionary<string, string>(); continue; } else { continue; } } else { if (string.Equals(line, STREAM_END, StringComparison.OrdinalIgnoreCase)) { inStreamSection = false; if (!dict.ContainsKey(FIELD_CODEC_TYPE)) { throw new Exception("Expected to find codec_type!!!"); } if (string.Equals(dict[FIELD_CODEC_TYPE], CODEC_TYPE_AUDIO, StringComparison.OrdinalIgnoreCase)) { aDic = dict; } else if (string.Equals(dict[FIELD_CODEC_TYPE], CODEC_TYPE_VIDEO, StringComparison.OrdinalIgnoreCase)) { vDic = dict; } else { Console.WriteLine("Unknown codec type: " + dict[FIELD_CODEC_TYPE] + " ignoring this!"); } continue; } else { string[] vals = line.Split(new char[] { '=' }); if (vals.Length == 2) { dict.Add(vals[0].Trim(), vals[1].Trim()); } } } } if (vDic == null) { throw new Exception("Expecting to find a video stream!"); } return BuildMovieMetadata(vDic, aDic); } protected void ExecuteFfmpeg(string arguments) { Process ffmpeg = null; try { // capture the output, otherwise it won't make sense w/ many processes writing to stdout ffmpeg = new Process(); ffmpeg.StartInfo.FileName = FfmpegPath; ffmpeg.StartInfo.Arguments = arguments; ffmpeg.StartInfo.UseShellExecute = false; ffmpeg.StartInfo.RedirectStandardOutput = false; ffmpeg.StartInfo.RedirectStandardError = false; ffmpeg.Start(); //ffmpeg.StandardOutput.ReadToEnd(); ffmpeg.WaitForExit(); } finally { ffmpeg.Dispose(); } } static MovieMetadata BuildMovieMetadata(Dictionary<string, string> vDic, Dictionary<string, string> aDic) { var mm = new MovieMetadata(); foreach (string key in vDic.Keys) { switch (key) { case "codec_name": mm.VideoCodecName = vDic[key]; break; case "width": mm.RawWidth = int.Parse(vDic[key]); break; case "height": mm.RawHeight = int.Parse(vDic[key]); break; case "r_frame_rate": mm.VideoFrameRate = vDic[key]; break; case "duration": float f; if (float.TryParse(vDic[key], out f)) { mm.VideoDuration = f; } break; case "nb_frames": int i; if (int.TryParse(vDic[key], out i)) { mm.VideoNumberOfFrames = i; } break; case "TAG:creation_time": DateTime dt; if (DateTime.TryParse(vDic[key], out dt)) { mm.VideoCreationTime = dt; } break; case "TAG:rotate": int rotation; if (int.TryParse(vDic[key], out rotation)) { mm.Rotation = rotation; } break; } } // if rotation is reported, swap width/height to compensate if (mm.Rotation != 0) { if (Math.Abs(mm.Rotation) == 90 || Math.Abs(mm.Rotation) == 270) { var tmp = mm.RawWidth; mm.RawWidth = mm.RawHeight; mm.RawHeight = tmp; } } if(aDic != null) { foreach (string key in aDic.Keys) { switch (key) { case "codec_name": mm.AudioCodecName = aDic[key]; break; case "channels": mm.AudioChannelCount = int.Parse(aDic[key]); break; case "sample_rate": mm.AudioSampleRate = float.Parse(aDic[key]); break; } } } return mm; } static string CollectMovieMetadataFromFile(string imagePath) { Process ffprobe = null; try { ffprobe = new Process(); ffprobe.StartInfo.FileName = FfprobePath; ffprobe.StartInfo.Arguments = string.Concat("-show_streams \"", imagePath, "\""); ffprobe.StartInfo.UseShellExecute = false; ffprobe.StartInfo.RedirectStandardOutput = true; ffprobe.StartInfo.RedirectStandardError = true; ffprobe.Start(); string output = ffprobe.StandardOutput.ReadToEnd(); ffprobe.WaitForExit(); return output; } finally { ffprobe.Dispose(); } } } }
/* * Copyright (c) 2010, www.wojilu.com. All rights reserved. */ using System; using System.Collections; using System.Collections.Generic; using wojilu.SOA; using wojilu.Web.Mvc; using wojilu.Apps.Content.Domain; using wojilu.Apps.Content.Interface; using wojilu.Common.AppBase; using wojilu.Common.AppBase.Interface; using wojilu.Serialization; using wojilu.Web.Controller.Content.Utils; namespace wojilu.Web.Controller.Content.Admin { public partial class ContentController : ControllerBase { private void bindCmd() { ContentApp app = ctx.app.obj as ContentApp; ContentSkin s = ContentSkin.findById( app.SkinId ); set( "skinPath", strUtil.Join( sys.Path.Skin, s.StylePath ) ); set( "skinLink", to( new SkinController().Index ) ); set( "addRow1Url", to( new ContentController().ConfirmAddRow, 1 ) ); set( "addRow2Url", to( new ContentController().ConfirmAddRow, 2 ) ); set( "addRow3Url", to( new ContentController().ConfirmAddRow, 3 ) ); set( "addRow4Url", to( new ContentController().ConfirmAddRow, 4 ) ); set( "addRow5Url", to( new ContentController().ConfirmAddRow, 5 ) ); set( "addRow6Url", to( new ContentController().ConfirmAddRow, 6 ) ); set( "setStyleUrl", to( new ContentController().SetStyle ) ); set( "layoutSaveUrl", to( new ContentController().SaveLayout ) ); set( "resizeLink", to( new ContentController().SaveResize ) ); } private void bindRowList( ContentApp article, List<ContentSection> sections ) { IBlock block = getBlock( "rowList" ); string[] rowList = article.RowList; for (int i = 1; i < (rowList.Length + 1); i++) { int columnCount = cvt.ToInt( rowList[i - 1] ); if (columnCount <= 0) continue; block.Set( "row.No", string.Format( alang( "rowNo" ), i ) ); block.Set( "row.DeleteUrl", to( DeleteRow, i ) ); block.Set( "row.ColumnCount", columnCount ); block.Set( "row.Index", i ); block.Set( "row.EditUILink", to( new ContentSectionController().EditRowUI, i ) ); IBlock columnBlock = block.GetBlock( "columnList" ); bindColumnList( sections, i, columnCount, columnBlock ); block.Next(); } } private void bindColumnList( List<ContentSection> sectionList, int iRow, int columnCount, IBlock columnBlock ) { for (int i = 1; i < (columnCount + 1); i++) { columnBlock.Set( "App.ImgPath", sys.Path.Img ); columnBlock.Set( "column.Id", string.Concat( new object[] { "row", iRow, "_column", i } ) ); String ctitle = alang( "columnNo" ); columnBlock.Set( "column.Name", string.Format( ctitle, i ) ); columnBlock.Set( "column.Index", i ); int rowColumnId = cvt.ToInt( iRow + "" + i ); String addUrl = Link.To( new ContentSectionController().Add, rowColumnId ); String addAutoUrl = Link.To( new ContentSectionController().AddAuto, rowColumnId ); String addFeed = Link.To( new ContentSectionController().AddFeed, rowColumnId ); String editUILink = to( new ContentSectionController().EditUI, rowColumnId ); columnBlock.Set( "column.AddModuleUrl", addUrl ); columnBlock.Set( "column.AddAutoSection", addAutoUrl ); columnBlock.Set( "column.AddFeed", addFeed ); columnBlock.Set( "column.EditUILink", editUILink ); List<ContentSection> sections = sectionService.GetByRowColumn( sectionList, iRow, i ); IBlock sectionBlock = columnBlock.GetBlock( "sectionList" ); bindSectionList( sections, sectionBlock ); columnBlock.Next(); } } private void bindSectionList( IList sections, IBlock sectionBlock ) { foreach (ContentSection section in sections) { sectionBlock.Set( "section.Id", section.Id ); sectionBlock.Set( "section.Title", section.Title ); sectionBlock.Set( "section.CombineIds", section.CombineIds ); sectionBlock.Set( "section.DeleteUrl", Link.To( new ContentSectionController().Delete, section.Id ) ); sectionBlock.Set( "section.EditUILink", Link.To( new ContentSectionController().EditSectionUI, section.Id ) ); sectionBlock.Set( "section.EditTitleUILink", Link.To( new ContentSectionController().EditSectionTitleUI, section.Id ) ); sectionBlock.Set( "section.EditContentUILink", Link.To( new ContentSectionController().EditSectionContentUI, section.Id ) ); sectionBlock.Set( "section.EditEffectLink", Link.To( new ContentSectionController().EditEffect, section.Id ) ); // bindCombineLink( section, sectionBlock ); bindRemoveLinks( section, sectionBlock ); String sectionContent = getSectionContent( sectionBlock, section ); sectionBlock.Set( "section.Content", sectionContent ); sectionBlock.Next(); } } private void bindCombineLink( ContentSection section, IBlock sectionBlock ) { IBlock block = sectionBlock.GetBlock( "combineSection" ); if (cvt.ToIntArray( section.CombineIds ).Length == 0) { block.Set( "section.CombineUrl", Link.To( new ContentSectionController().Combine, section.Id ) ); block.Next(); } } private void bindRemoveLinks( ContentSection section, IBlock sectionBlock ) { IBlock block = sectionBlock.GetBlock( "removeSections" ); int[] arrIds = cvt.ToIntArray( section.CombineIds ); if (arrIds.Length <= 0) return; for (int i = 0; i < arrIds.Length; i++) { ContentSection target = sectionService.GetById( arrIds[i], ctx.app.Id ); if (target == null) continue; block.Set( "r.Name", target.Title ); block.Set( "r.RemoveLink", Link.To( new ContentSectionController().RemoveSection, section.Id ) + "?targetSection=" + target.Id ); block.Next(); } } private String getSectionContent( IBlock sectionBlock, ContentSection section ) { String sectionContent; if (section.ServiceId <= 0) sectionContent = bindData( sectionBlock, section ); else sectionContent = "<div class=\"binderSectionBody\">"+bindAutoData( sectionBlock, section )+"</div>"; return sectionContent; } private String bindAutoData( IBlock sectionBlock, ContentSection section ) { IList setttingLinks = getAutoBinderSettingLinks( section ); bindSettingLink( sectionBlock, setttingLinks ); Dictionary<string, string> presult = getDefaultValue( section ); IList data = ServiceContext.GetData( section.ServiceId, section.GetServiceParamValues(), presult ); if (section.TemplateId <= 0) return getJsonResult( section, data ); ContentSectionTemplate tpl = templatelService.GetById( section.TemplateId ); Template currentView = utils.getTemplateByFileName( BinderUtils.GetBinderTemplatePath( tpl ) ); ISectionBinder binder = BinderUtils.GetBinder( tpl, ctx, currentView ); binder.Bind( section, data ); ControllerBase cb2 = binder as ControllerBase; return cb2.utils.getActionResult(); } private String getJsonResult( ContentSection section, IList data ) { String jsonStr = JsonString.ConvertList( data ); String scriptData = string.Format( " <script>var sectionData{0} = {1};</script>", section.Id, jsonStr ); if (section.CustomTemplateId <= 0) return scriptData; ContentCustomTemplate ct = ctService.GetById( section.CustomTemplateId, ctx.owner.Id ); if (ct == null) return scriptData; return scriptData + ct.Content; } private IList getAutoBinderSettingLinks( ContentSection section ) { IList setttingLinks = new ArrayList(); PageSettingLink slink = new PageSettingLink(); slink.Name = lang( "editSetting" ); slink.Url = Link.To( new SectionSettingController().EditBinder, section.Id ); setttingLinks.Add( slink ); PageSettingLink lnktmp = new PageSettingLink(); lnktmp.Name = alang( "editTemplate" ); lnktmp.Url = to( new TemplateCustomController().EditBinder, section.Id ); setttingLinks.Add( lnktmp ); return setttingLinks; } private Dictionary<string, string> getDefaultValue( ContentSection section ) { Service service = ServiceContext.Get( section.ServiceId ); Dictionary<string, string> pd = service.GetParamDefault(); Dictionary<string, string> presult = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> pair in pd) { if (pair.Key.Equals( "ownerId" )) presult.Add( pair.Key, ctx.owner.obj.Id.ToString() ); else if (pair.Key.Equals( "viewerId" )) presult.Add( pair.Key, ctx.viewer.Id.ToString() ); else presult.Add( pair.Key, pair.Key ); } return presult; } private String bindData( IBlock sectionBlock, ContentSection articleSection ) { IPageSection section = BinderUtils.GetPageSectionAdmin( articleSection, ctx, "AdminSectionShow" ); ControllerBase controller = section as ControllerBase; bindSettingLink( sectionBlock, section.GetSettingLink( articleSection.Id ) ); section.AdminSectionShow( articleSection.Id ); return controller.utils.getActionResult(); } private static void bindSettingLink( IBlock sectionBlock, IList setttingLinks ) { IBlock block = sectionBlock.GetBlock( "links" ); foreach (IPageSettingLink link in setttingLinks) { block.Set( "settting.Name", link.Name ); block.Set( "setting.Url", link.Url ); block.Next(); } } } }
// // XmlConfigurationClient.cs // // Author: // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (C) 2007-2008 Scott Peterson // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Timers; using System.Xml; using System.Xml.Serialization; using Banshee.Base; namespace Banshee.Configuration { public class XmlConfigurationClient : IConfigurationClient { private const string null_namespace = "null"; private const string namespace_tag_name = "namespace"; private const string value_tag_name = "value"; private const string tag_identifier_attribute_name = "name"; private static string file_path { get { return Path.Combine(Paths.ApplicationData, "config.xml"); } } private static XmlDocument xml_document; private static System.Timers.Timer timer; private static object timer_mutex = new object(); private static volatile bool delay_write; public XmlConfigurationClient() { timer = new System.Timers.Timer(100); // a 10th of a second timer.Elapsed += new ElapsedEventHandler(OnTimerElapsedEvent); timer.AutoReset = true; xml_document = new XmlDocument(); bool make_new_xml = true; if(File.Exists(file_path)) { try { xml_document.Load(file_path); make_new_xml = false; } catch { // TODO try recovery? } } if(make_new_xml) { xml_document.LoadXml("<configuration />"); } } public T Get<T>(SchemaEntry<T> entry) { return Get<T>(entry.Namespace, entry.Key, entry.DefaultValue); } public T Get<T>(SchemaEntry<T> entry, T fallback) { return Get<T>(entry.Namespace, entry.Key, fallback); } public T Get<T>(string key, T fallback) { return Get<T>(null, key, fallback); } public T Get<T>(string namespce, string key, T fallback) { lock(xml_document) { XmlNode namespace_node = GetNamespaceNode(namespce == null ? new string [] {null_namespace} : namespce.Split('.'), false); if(namespace_node == null) { return fallback; } foreach(XmlNode node in namespace_node.ChildNodes) { if(node.Attributes[tag_identifier_attribute_name].Value == key && node.Name == value_tag_name) { XmlSerializer serializer = new XmlSerializer(typeof(T)); StringReader reader = new StringReader(node.InnerXml); return (T) serializer.Deserialize(reader); } } return fallback; } } public void Set<T>(SchemaEntry<T> entry, T value) { Set(entry.Namespace, entry.Key, value); } public void Set<T>(string key, T value) { Set(null, key, value); } public void Set<T>(string namespce, string key, T value) { lock(xml_document) { XmlSerializer serializer = new XmlSerializer(typeof(T)); StringWriter writer = new StringWriter(); serializer.Serialize(writer, value); XmlDocumentFragment fragment = xml_document.CreateDocumentFragment(); fragment.InnerXml = writer.ToString(); writer.Close(); if(fragment.FirstChild is XmlDeclaration) { fragment.RemoveChild(fragment.FirstChild); // This is only a problem with Microsoft's System.Xml } XmlNode namespace_node = GetNamespaceNode(namespce == null ? new string [] {null_namespace} : namespce.Split('.'), true); bool found = false; foreach(XmlNode node in namespace_node.ChildNodes) { if(node.Attributes[tag_identifier_attribute_name].Value == key && node.Name == value_tag_name) { node.InnerXml = fragment.InnerXml; found = true; break; } } if(!found) { XmlNode new_node = xml_document.CreateElement(value_tag_name); XmlAttribute attribute = xml_document.CreateAttribute(tag_identifier_attribute_name); attribute.Value = key; new_node.Attributes.Append(attribute); new_node.AppendChild(fragment); namespace_node.AppendChild(new_node); } QueueWrite(); } } private XmlNode GetNamespaceNode(string [] namespace_parts, bool create) { return GetNamespaceNode(xml_document.DocumentElement, namespace_parts, create); } private XmlNode GetNamespaceNode(XmlNode parent_node, string [] namespace_parts, bool create) { XmlNode node = parent_node.FirstChild ?? parent_node; do { if(node.Name == namespace_tag_name && node.Attributes[tag_identifier_attribute_name].Value == namespace_parts[0]) { if(namespace_parts.Length > 1) { string [] new_namespace_parts = new string[namespace_parts.Length - 1]; for(int i = 1; i < namespace_parts.Length; i++) { new_namespace_parts[i - 1] = namespace_parts[i]; } node = GetNamespaceNode(node, new_namespace_parts, create); } return node; } else { node = node.NextSibling; } } while(node != null); if(create) { XmlNode appending_node = parent_node; foreach(string s in namespace_parts) { XmlNode new_node = xml_document.CreateElement(namespace_tag_name); XmlAttribute attribute = xml_document.CreateAttribute(tag_identifier_attribute_name); attribute.Value = s; new_node.Attributes.Append(attribute); appending_node.AppendChild(new_node); appending_node = new_node; } node = appending_node; } return node; } // Queue XML file writes to minimize disk access private static void QueueWrite() { lock(timer_mutex) { if(!timer.Enabled) { timer.Start(); } else { delay_write = true; } } } private static void OnTimerElapsedEvent(object o, ElapsedEventArgs args) { lock(timer_mutex) { if(delay_write) { delay_write = false; } else { xml_document.Save(file_path); timer.Stop(); } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace RealMocking.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (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.Threading; using Alachisoft.NCache.Storage; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Caching.EvictionPolicies; using Alachisoft.NCache.Caching.Events; using Alachisoft.NCache.Caching.AutoExpiration; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Util; using System.Net; using Alachisoft.NCache.Common; using System.Collections.Generic; using Alachisoft.NCache.Caching.Messaging; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Common.DataStructures.Clustered; using Alachisoft.NCache.Common.Caching; using Alachisoft.NCache.Runtime.Caching; using System.Text.RegularExpressions; using Alachisoft.NCache.Common.Pooling; using Alachisoft.NCache.Common.ErrorHandling; using Alachisoft.NCache.Caching.Pooling; using Alachisoft.NCache.Caching.Enumeration; using Alachisoft.NCache.Common.DataStructures; using Alachisoft.NCache.Util; namespace Alachisoft.NCache.Caching.Topologies.Local { /// <summary> /// This class provides the local storage options i.e. the actual storage of objects. It is used /// by the Cache Manager, replicated cache and partitioned cache. /// </summary> internal class LocalCache : LocalCacheBase { /// <summary> The eviction policy for the cache. </summary> protected IEvictionPolicy _evictionPolicy; /// <summary> Thread which evicts item when cache is full.</summary> private Thread _evictionThread; private object _eviction_sync_mutex = new object(); /// <summary>Flag which indicates whether to explicitly call GC.Collect or not</summary> private bool _allowExplicitGCCollection = true; private bool _notifyCacheFull = false; private TopicManager _topicManager; private EnumerationIndex _enumerationIndex; /// <summary> /// Overloaded constructor. Takes the properties as a map. /// </summary> /// <param name="cacheSchemes">collection of cache schemes (config properties).</param> /// <param name="properties">properties collection for this cache.</param> /// <param name="listener">cache events listener</param> /// <param name="timeSched">scheduler to use for periodic tasks</param> public LocalCache(IDictionary cacheClasses, CacheBase parentCache, IDictionary properties, ICacheEventsListener listener, CacheRuntimeContext context) : base(properties, parentCache, listener, context) { _stats.ClassName = "local-cache"; _topicManager = new TopicManager(context); Initialize(cacheClasses, properties); CreateEventsTopics(); _cacheStore.ISizableEvictionIndexManager = _evictionPolicy; _cacheStore.ISizableExpirationIndexManager = _context.ExpiryMgr; } #region / --- IDisposable --- / /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> public override void Dispose() { if (_cacheStore != null) { _cacheStore.Dispose(); _cacheStore = null; } base.Dispose(); } #endregion /// <summary> /// returns the number of objects contained in the cache. /// </summary> public override long Count { get { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Count", ""); if (_cacheStore == null) throw new InvalidOperationException(); return _cacheStore.Count; } } public override long SessionCount { get { return _stats.SessionCount; } } public override IPAddress ServerJustLeft { get { return null; } set {; } } public override int ServersCount { get { return 1; } } public override bool IsServerNodeIp(Address clientAddress) { return false; } /// <summary> /// Get the size of data in store, in bytes. /// </summary> internal override long Size { get { if (_cacheStore != null) return _cacheStore.Size; return 0; } } internal override float EvictRatio { get { if (_evictionPolicy != null) return _evictionPolicy.EvictRatio; return 0; } set { if (_evictionPolicy != null) { _evictionPolicy.EvictRatio = value; } } } /// <summary> /// Returns true if cache is started as backup mirror cache, false otherwise. /// In Case of replica space will not be checked at storage level /// </summary> /// public override bool VirtualUnlimitedSpace { get { return _cacheStore.VirtualUnlimitedSpace; } set { _cacheStore.VirtualUnlimitedSpace = value; } } internal override long MaxSize { get { if (_cacheStore != null) return _cacheStore.MaxSize; return 0; } set { if (_cacheStore != null) { //muds: //if the cache has less data than the new maximum size. //we can not apply the new size to the cache if the cache has already more data. if (_cacheStore.Size <= value) { _cacheStore.MaxSize = value; _stats.MaxSize = value; } else { throw new Exception("You need to remove some data from cache before applying the new size"); } } } } internal override bool CanChangeCacheSize(long size) { return (_cacheStore.Size <= size); } /// <summary> /// Method that allows the object to initialize itself. Passes the property map down /// the object hierarchy so that other objects may configure themselves as well.. /// </summary> /// <param name="properties">configuration properties</param> protected override void Initialize(IDictionary cacheClasses, IDictionary properties) { if (properties == null) throw new ArgumentNullException("properties"); try { base.Initialize(cacheClasses, properties); _allowExplicitGCCollection = ServiceConfiguration.EnableGCCollection; if (!properties.Contains("storage")) throw new ConfigurationException("Missing configuration option 'storage'"); if (properties.Contains("scavenging-policy")) { IDictionary evictionProps = properties["scavenging-policy"] as IDictionary; if (Convert.ToDouble(evictionProps["evict-ratio"]) > 0) _evictionPolicy = EvictionPolicyFactory.CreateEvictionPolicy(evictionProps, _context.NCacheLog); } else { _evictionPolicy = EvictionPolicyFactory.CreateDefaultEvictionPolicy(); } IDictionary storageProps = properties["storage"] as IDictionary; _cacheStore = CacheStorageFactory.CreateStorageProvider(storageProps, this._context.SerializationContext, _evictionPolicy != null, _context.NCacheLog, null); _cacheStore.ISizableMessageStore = _topicManager; _stats.MaxCount = _cacheStore.MaxCount; _stats.MaxSize = _cacheStore.MaxSize; } catch (ConfigurationException e) { if (_context != null) { _context.NCacheLog.Error("LocalCache.Initialize()", e.ToString()); } Dispose(); throw; } catch (Exception e) { if (_context != null) { _context.NCacheLog.Error("LocalCache.Initialize()", e.ToString()); } Dispose(); throw new ConfigurationException("Configuration Error: " + e.ToString(), e); } } #region / --- LocalCacheBase --- / /// <summary> /// Removes all entries from the store. /// </summary> internal override void ClearInternal() { if (_cacheStore == null) throw new InvalidOperationException(); _cacheStore.Clear(); _topicManager.Clear(); _context.PerfStatsColl.SetCacheSize(0); // on clear cache cachesize set to zero if (_evictionThread != null) { NCacheLog.Flush(); #if !NETCORE _evictionThread.Abort(); #elif NETCORE _evictionThread.Interrupt(); #endif } if (_evictionPolicy != null) { _evictionPolicy.Clear(); if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetEvictionIndexSize(_evictionPolicy.IndexInMemorySize); } } } /// <summary> /// Determines whether the cache contains a specific key. /// </summary> /// <param name="key">The key to locate in the cache.</param> /// <returns>true if the cache contains an element /// with the specified key; otherwise, false.</returns> internal override bool ContainsInternal(object key) { if (_cacheStore == null) throw new InvalidOperationException(); return _cacheStore.Contains(key); } /// <summary> /// Retrieve the object from the cache. A string key is passed as parameter. /// </summary> /// <param name="key">key of the entry.</param> /// <returns>cache entry.</returns> internal override CacheEntry GetInternal(object key, bool isUserOperation, OperationContext operationContext, bool cloneEntry, bool needUserPayload) { if (_cacheStore == null) throw new InvalidOperationException(); CacheEntry e = (CacheEntry)_cacheStore.Get(key); if (e != null) { EvictionHint evh = e.EvictionHint; if (isUserOperation && _evictionPolicy != null && evh != null && evh.IsVariant) _evictionPolicy.Notify(key, evh, null); e.MarkInUse(NCModulesConstants.Global); if (cloneEntry) { e = e.DeepClone(operationContext.UseObjectPool? _context.TransactionalPoolManager: _context.FakeObjectPool,true); } } return e; } /// <summary> /// Special purpose internal method. Derived classes don't override this method. /// </summary> /// <param name="key"></param> /// <param name="isUserOperation"></param> /// <returns></returns> internal override CacheEntry GetEntryInternal(object key, bool isUserOperation,OperationContext operationContext, bool cloneCacheEntry, bool needUserPayload) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.GetInternal", ""); if (_cacheStore == null) throw new InvalidOperationException(); CacheEntry e = (CacheEntry)_cacheStore.Get(key); if (e == null) return e; EvictionHint evh = e.EvictionHint; if (isUserOperation && _evictionPolicy != null && evh != null && evh.IsVariant) _evictionPolicy.Notify(key, evh, null); e.MarkInUse(NCModulesConstants.Global); if (cloneCacheEntry) e = e.DeepClone(operationContext.UseObjectPool ? _context.TransactionalPoolManager : _context.FakeObjectPool); return e; } /// <summary> /// Get the item size stored in cache /// </summary> /// <param name="key">key</param> /// <returns>item size</returns> public override int GetItemSize(object key) { if (_cacheStore == null) return 0; return _cacheStore.GetItemSize(key); } /// <summary> /// Adds a pair of key and value to the cache. Throws an exception or reports error /// if the specified key already exists in the cache. /// </summary> /// <param name="key">key of the entry.</param> /// <param name="cacheEntry">the cache entry.</param> /// <returns>returns the result of operation.</returns> internal override CacheAddResult AddInternal(object key, CacheEntry cacheEntry, bool isUserOperation, OperationContext operationContext) { try { if (_cacheStore == null) throw new InvalidOperationException(); if (cacheEntry != null) cacheEntry.MarkInUse(NCModulesConstants.LocalCache); if (_evictionPolicy != null) { if (cacheEntry.EvictionHint is PriorityEvictionHint) cacheEntry.Priority = ((PriorityEvictionHint)cacheEntry.EvictionHint).Priority; EvictionHint oldEvictionHint = cacheEntry.EvictionHint; cacheEntry.EvictionHint = _evictionPolicy.CompatibleHint(cacheEntry.EvictionHint, _context.StorePoolManager); if (oldEvictionHint != null && !ReferenceEquals(oldEvictionHint, cacheEntry.EvictionHint)) MiscUtil.ReturnEvictionHintToPool(oldEvictionHint, _context.StorePoolManager); } // No Need to insert Eviction if Eviction is turned off it will reduce cache-entry overhead if (_evictionPolicy == null) cacheEntry.EvictionHint = null; StoreAddResult result = _cacheStore.Add(key, cacheEntry, !isUserOperation); if (result == StoreAddResult.Success || result == StoreAddResult.SuccessNearEviction) { cacheEntry.IsStored = true; if (_evictionPolicy != null) _evictionPolicy.Notify(key, null, cacheEntry.EvictionHint); } if (result == StoreAddResult.NotEnoughSpace && !_notifyCacheFull) { _notifyCacheFull = true; _context.NCacheLog.Error("LocalCache.AddInternal", "The cache is full and not enough items could be evicted."); } if (_context.PerfStatsColl != null) { if (_evictionPolicy != null) _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize); if (_context.ExpiryMgr != null) _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize); } switch (result) { case StoreAddResult.Success: return CacheAddResult.Success; case StoreAddResult.KeyExists: return CacheAddResult.KeyExists; case StoreAddResult.NotEnoughSpace: return CacheAddResult.NeedsEviction; case StoreAddResult.SuccessNearEviction: return CacheAddResult.SuccessNearEviction; } return CacheAddResult.Failure; } finally { if (cacheEntry != null) cacheEntry.MarkFree(NCModulesConstants.LocalCache); } } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="eh"></param> /// <returns></returns> internal override bool AddInternal(object key, ExpirationHint eh, OperationContext operationContext) { CacheEntry e = null; try { if (_cacheStore == null) throw new InvalidOperationException(); e = (CacheEntry)_cacheStore.Get(key); if (e == null) return false; //We only allow either idle expiration or Fixed expiration both cannot be set at the same time if ((e.ExpirationHint is IdleExpiration && eh is FixedExpiration) || (e.ExpirationHint is FixedExpiration && eh is IdleExpiration)) { return false; } if (e.ExpirationHint == null) { e.ExpirationHint = eh; } else { if (e.ExpirationHint is AggregateExpirationHint) { ((AggregateExpirationHint)e.ExpirationHint).Add(eh); } else { AggregateExpirationHint aeh = AggregateExpirationHint.Create(Context.StorePoolManager); aeh.Add(e.ExpirationHint); aeh.Add(eh); e.ExpirationHint = aeh; } } e.MarkFree(NCModulesConstants.Global); e.MarkInUse(NCModulesConstants.LocalCache); //Our store may not be an in memory store _cacheStore.Insert(key, e, true); e.LastModifiedTime = System.DateTime.Now; if (_context.PerfStatsColl != null) { if (_evictionPolicy != null) _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize); if (_context.ExpiryMgr != null) _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize); } return true; } finally { if (e!=null) e.MarkFree(NCModulesConstants.LocalCache); } } /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="eh"></param> /// <returns></returns> internal override bool RemoveInternal(object key, ExpirationHint eh) { CacheEntry e = null; try { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Remove", ""); if (_cacheStore == null) throw new InvalidOperationException(); e = (CacheEntry)_cacheStore.Get(key); if (e == null || e.ExpirationHint == null) { return false; } else { e.MarkInUse(NCModulesConstants.LocalCache); if (e.ExpirationHint is AggregateExpirationHint) { AggregateExpirationHint AggHint = AggregateExpirationHint.Create(Context.StorePoolManager); AggregateExpirationHint entryExpHint = (AggregateExpirationHint)e.ExpirationHint; foreach (ExpirationHint exp in entryExpHint) { if (!exp.Equals(eh)) { AggHint.Add(exp); } else { MiscUtil.ReturnExpirationHintToPool(exp, Context.StorePoolManager); } } e.ExpirationHint = AggHint; } else if (e.ExpirationHint.Equals(eh)) { MiscUtil.ReturnExpirationHintToPool(e.ExpirationHint, Context.StorePoolManager); e.ExpirationHint = null; } } // Our store may not be an in memory store if (_notifyCacheFull) { _notifyCacheFull = false; } _cacheStore.Insert(key, e, true); e.LastModifiedTime = System.DateTime.Now; if (_context.PerfStatsColl != null) { if (_evictionPolicy != null) _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize); if (_context.ExpiryMgr != null) _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize); } return true; } finally { if (e != null) e.MarkFree(NCModulesConstants.LocalCache); } } /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> internal override bool AddInternal(object key) { CacheEntry e = null; try { if (_cacheStore == null) throw new InvalidOperationException(); e = (CacheEntry)_cacheStore.Get(key); if (e == null) return false; e.MarkInUse(NCModulesConstants.LocalCache); //Our store may not be an in memory store _cacheStore.Insert(key, e, true); e.LastModifiedTime = System.DateTime.Now; return true; } finally { if (e != null) e.MarkFree(NCModulesConstants.LocalCache); } } /// <summary> /// Adds a pair of key and value to the cache. If the specified key already exists /// in the cache; it is updated, otherwise a new item is added to the cache. /// </summary> /// <param name="key">key of the entry.</param> /// <param name="cacheEntry">the cache entry.</param> /// <returns>returns the result of operation.</returns> internal override CacheInsResult InsertInternal(object key, CacheEntry cacheEntry, bool isUserOperation, CacheEntry oldEntry, OperationContext operationContext, bool updateIndex) { try { if (cacheEntry != null) cacheEntry.MarkInUse(NCModulesConstants.LocalCache); if (_cacheStore == null) throw new InvalidOperationException(); if (oldEntry != null && cacheEntry.Type != oldEntry.Type) throw new Exception(string.Format("Cannot update '{0}' type with '{1}' type.", oldEntry.Type, cacheEntry.Type)); if (cacheEntry.EvictionHint is PriorityEvictionHint) cacheEntry.Priority = ((PriorityEvictionHint)cacheEntry.EvictionHint).Priority; if (_evictionPolicy != null) { EvictionHint oldEvictionHint = cacheEntry.EvictionHint; cacheEntry.EvictionHint = _evictionPolicy.CompatibleHint(cacheEntry.EvictionHint, _context.StorePoolManager); if (oldEvictionHint != null && !ReferenceEquals(oldEvictionHint, cacheEntry.EvictionHint)) MiscUtil.ReturnEvictionHintToPool(oldEvictionHint, _context.StorePoolManager); } EvictionHint peEvh = oldEntry == null ? null : oldEntry.EvictionHint; // No Need to insert Eviction if Eviction is turned off it will reduce cache-entry overhead if (_evictionPolicy == null) cacheEntry.EvictionHint = null; CacheEntry storedEntry = _cacheStore.Get(key) as CacheEntry; StoreInsResult result = _cacheStore.Insert(key, cacheEntry, !isUserOperation); // Operation completed! if (result == StoreInsResult.Success || result == StoreInsResult.SuccessNearEviction) { //This means that entry has become part of the store cacheEntry.IsStored = true; if (_evictionPolicy != null) _evictionPolicy.Notify(key, null, cacheEntry.EvictionHint); if (!object.ReferenceEquals(storedEntry, cacheEntry)) MiscUtil.ReturnEntryToPool(storedEntry, _context.StorePoolManager); } else if (result == StoreInsResult.SuccessOverwrite || result == StoreInsResult.SuccessOverwriteNearEviction) { if(!object.ReferenceEquals(storedEntry,cacheEntry)) MiscUtil.ReturnEntryToPool(storedEntry, _context.StorePoolManager); //This means that entry has become part of the store cacheEntry.IsStored = true; if (oldEntry != null) { //update the cache item version... if (isUserOperation) { cacheEntry.UpdateVersion(oldEntry); } //update the cache item last modifeid time... cacheEntry.UpdateLastModifiedTime(oldEntry); } if (_evictionPolicy != null) _evictionPolicy.Notify(key, peEvh, cacheEntry.EvictionHint); } if (result == StoreInsResult.NotEnoughSpace && !_notifyCacheFull) { _notifyCacheFull = true; _context.NCacheLog.Error("LocalCache.InsertInternal", "The cache is full and not enough items could be evicted."); } if (_context.PerfStatsColl != null) { if (_evictionPolicy != null) _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize); if (_context.ExpiryMgr != null) _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize); } switch (result) { case StoreInsResult.Success: return CacheInsResult.Success; case StoreInsResult.SuccessOverwrite: return CacheInsResult.SuccessOverwrite; case StoreInsResult.NotEnoughSpace: return CacheInsResult.NeedsEviction; case StoreInsResult.SuccessNearEviction: return CacheInsResult.SuccessNearEvicition; case StoreInsResult.SuccessOverwriteNearEviction: return CacheInsResult.SuccessOverwriteNearEviction; } return CacheInsResult.Failure; } finally { if (cacheEntry != null) cacheEntry.MarkFree(NCModulesConstants.LocalCache); } } /// <summary> /// Removes the object and key pair from the cache. The key is specified as parameter. /// Moreover it take a removal reason and a boolean specifying if a notification should /// be raised. /// </summary> /// <param name="key">key of the entry.</param> /// <param name="removalReason">reason for the removal.</param> /// <param name="notify">boolean specifying to raise the event.</param> /// <returns>item value</returns> internal override CacheEntry RemoveInternal(object key, ItemRemoveReason removalReason, bool isUserOperation, OperationContext operationContext,bool cloneEntry, bool needUserPayload) { if (_cacheStore == null) throw new InvalidOperationException(); CacheEntry e = (CacheEntry)_cacheStore.Remove(key); if (e != null) { //Entry is no more part of store e.IsStored = false; if (_evictionPolicy != null && e.EvictionHint != null) _evictionPolicy.Remove(key, e.EvictionHint); if (_notifyCacheFull) { _notifyCacheFull = false; } if (cloneEntry) { var clone = e.DeepClone(operationContext.UseObjectPool ? _context.TransactionalPoolManager : _context.FakeObjectPool,true); //return entry to the store pool MiscUtil.ReturnEntryToPool(e, _context.StorePoolManager); e = clone; } } if (_context.PerfStatsColl != null) { if (_evictionPolicy != null) _context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize); if (_context.ExpiryMgr != null) _context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize); } return e; } public override EnumerationDataChunk GetNextChunk(EnumerationPointer pointer, OperationContext operationContext) { if (!IsCacheOperationAllowed(operationContext)) return null; if (_enumerationIndex == null) _enumerationIndex = new EnumerationIndex(this); EnumerationDataChunk nextChunk = _enumerationIndex.GetNextChunk(pointer); return nextChunk; } public override bool HasEnumerationPointer(EnumerationPointer pointer) { if (_enumerationIndex == null) return false; return _enumerationIndex.Contains(pointer); } #endregion #region / --- ICache --- / /// <summary> /// Returns a .NET IEnumerator interface so that a client should be able /// to iterate over the elements of the cache store. /// </summary> /// <returns>IDictionaryEnumerator enumerator.</returns> public override IDictionaryEnumerator GetEnumerator() { if (_cacheStore == null) throw new InvalidOperationException(); return _cacheStore.GetEnumerator(); } public override Array Keys { get { if (_cacheStore == null) throw new InvalidOperationException(); return _cacheStore.Keys; } } #endregion /// <summary> /// Evicts items from the store. /// </summary> /// <returns></returns> public override void Evict() { if (_evictionPolicy == null) { return; } lock (_eviction_sync_mutex) { if (_parentCache.IsEvictionAllowed) { if (_allowAsyncEviction) { if (_evictionThread == null) { _evictionThread = new Thread(new ThreadStart(EvictAysnc)); _evictionThread.IsBackground = true; _evictionThread.Start(); } } else { DoEvict(this); } } } } /// <summary> /// Evicts the items from the cache. /// </summary> private void DoEvict(CacheBase cache) { try { if (_evictionPolicy != null) { var sizeToEvict = (long)Math.Ceiling(Size * _evictionPolicy.EvictRatio); long evictedSize = _evictionPolicy.Execute(cache, _context, Size); if (sizeToEvict > evictedSize) { _context.MessageManager.Evict(sizeToEvict - evictedSize); } } } finally { } } /// <summary> /// Called by async thread to evict the item from the store. /// </summary> private void EvictAysnc() { try { if (!IsSelfInternal) DoEvict(_context.CacheImpl); else DoEvict(_context.CacheInternal); } catch (ThreadAbortException) { } catch (ThreadInterruptedException) { } catch (Exception e) { if (_context != null) { _context.NCacheLog.Error("LocalCache._evictionRun", e.ToString()); } } finally { lock (_eviction_sync_mutex) { _evictionThread = null; } } } internal override void TouchInternal(string key, OperationContext operationContext) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Touch", ""); if (_cacheStore == null) throw new InvalidOperationException(); CacheEntry e = (CacheEntry)_cacheStore.Get(key); if (e != null) { EvictionHint evh = e.EvictionHint; if (_evictionPolicy != null && evh != null && evh.IsVariant) _evictionPolicy.Notify(key, evh, null); ExpirationHint exh = e.ExpirationHint; if (exh != null && exh.IsVariant) { try { _context.ExpiryMgr.ResetVariant(exh); } catch (Exception ex) { throw ex; } } } } public override void ClientDisconnected(string client, bool isInproc, Runtime.Caching.ClientInfo clientInfo) { base.ClientDisconnected(client, isInproc, clientInfo); _topicManager.OnClientDisconnected(client); } public override void ClientConnected(string client, bool isInproc, Runtime.Caching.ClientInfo clientInfo) { base.ClientConnected(client, isInproc, clientInfo); } #region / --- IMessageStore implementation ---- / public override bool TopicOperation(TopicOperation operation, OperationContext operationContext) { bool result = false; if(!IsCacheOperationAllowed(operationContext)) return result; try { if (operation != null) { switch (operation.TopicOperationType) { case TopicOperationType.Create: result = CreateTopic(operation.Topic); break; case TopicOperationType.Get: result = GetTopic(operation.Topic); break; case TopicOperationType.Remove: result = DeleteTopic(operation.Topic); break; case TopicOperationType.Subscribe: result = _topicManager.CreateSubscription(operation.Topic, ((SubscriptionOperation)operation).SubscriptionInfo); break; case TopicOperationType.UnSubscribe: result = _topicManager.RemoveSubscription(operation.Topic, ((SubscriptionOperation)operation).SubscriptionInfo,((SubscriptionOperation)operation).IsDispose); break; case TopicOperationType.RefreshSubscription: result = RefreshSubscription(operation.Topic, ((SubscriptionOperation)operation).SubscriptionInfo); break; case TopicOperationType.RemoveInavtiveSubscripber: result = _topicManager.RemoveInactiveSubscriber(operation.Topic, ((SubscriptionOperation)operation).SubscriptionInfo); break; } } if (result && _context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return result; } catch (Exception ex) { throw; } result = false; } private bool CreateTopic(string topic) { _topicManager.CreateTopic(topic); return true; } private bool GetTopic(string topic) { return _topicManager.GetTopic(topic) != null; } private bool DeleteTopic(string topic) { return _topicManager.RemoveTopic(topic); } private bool RefreshSubscription(string topic, SubscriptionInfo subscriptionInfo) { Topic instance = _topicManager.GetTopic(topic); if (instance != null) { instance.RefreshSubscription(subscriptionInfo); } return true; } public override bool StoreMessage(string topic, Messaging.Message message, OperationContext context) { if (!IsCacheOperationAllowed(context)) return false; Topic topicInstance = _topicManager.GetTopic(topic); bool stored = false; if (topicInstance != null) { StoreStatus status = _cacheStore.HasSpace(message, 0, true); _cacheStore.CheckIfCacheNearEviction(); if (status == StoreStatus.HasSpace || status == StoreStatus.NearEviction) { stored = topicInstance.StoreMessage(message, context); } if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } if (status != StoreStatus.HasSpace) { Evict(); } if (status == StoreStatus.HasNotEnoughSpace) throw new OperationFailedException(ErrorCodes.Common.NOT_ENOUGH_ITEMS_EVICTED, ErrorMessages.GetErrorMessage(ErrorCodes.Common.NOT_ENOUGH_ITEMS_EVICTED)); } else { throw new OperationFailedException(ErrorCodes.PubSub.TOPIC_NOT_FOUND, ErrorMessages.GetErrorMessage(ErrorCodes.PubSub.TOPIC_NOT_FOUND, topic)); } return stored; } public override MessageInfo GetNextUnassignedMessage(TimeSpan timeout, OperationContext context) { return _topicManager.GetNextUnassignedMessage(timeout, context); } public override SubscriptionInfo GetSubscriber(string topic, Common.Enum.SubscriptionType type, OperationContext context) { Topic instance = _topicManager.GetTopic(topic); if (instance != null) return instance.GetSubscriberForAssignment(type, context); return null; } public override bool AssignmentOperation(MessageInfo messageInfo, SubscriptionInfo subscriptionInfo, TopicOperationType type, OperationContext context) { Topic instance = _topicManager.GetTopic(messageInfo.Topic); if (instance != null) { switch (type) { case TopicOperationType.AssignSubscription: return instance.AssignSubscription(messageInfo, subscriptionInfo); case TopicOperationType.RevokeAssignment: instance.RevokeAssignment(messageInfo, subscriptionInfo); return true; } } return false; } public override MessageResponse GetAssignedMessage(SubscriptionInfo subscriptionInfo, OperationContext operationContext) { if (!IsCacheOperationAllowed(operationContext)) return null; return _topicManager.GetAssignedMessages(subscriptionInfo); } public override void AcknowledgeMessageReceipt(string clientId, IDictionary<string, IList<string>> topicWiseMessageIds, OperationContext operationContext) { if (!IsCacheOperationAllowed(operationContext)) return; HashVector errors = new HashVector(); foreach (KeyValuePair<string, IList<string>> topicMessges in topicWiseMessageIds) { foreach (string messageId in topicMessges.Value) { try { AcknowledgeMessageReceiptInternal(clientId, topicMessges.Key, messageId, operationContext); } catch (Exception e) { errors.Add(new MessageInfo() { Topic = topicMessges.Key, MessageId = messageId }, e); } } } } protected virtual void AcknowledgeMessageReceiptInternal(string clientId, string topic, string messageId, OperationContext operationContext) { _topicManager.AcknowledgeMessageReceipt(clientId, topic, messageId, operationContext); } public override IList<MessageInfo> GetDeliveredMessages() { return _topicManager.GetDeliveredMessages(); } public override IList<MessageInfo> GetExpiredMessages() { return _topicManager.GetExpiredMessages(); } public override IList<MessageInfo> GetEvicatableMessages(long sizeToEvict) { return _topicManager.GetEvicatableMessages(sizeToEvict); } public override void RemoveMessages(IList<MessageInfo> messagesTobeRemoved, MessageRemovedReason reason, OperationContext context) { HashVector errors = new HashVector(); foreach (MessageInfo messageInfo in messagesTobeRemoved) { try { RemoveMessagesInternal(messageInfo, reason, context); } catch (Exception e) { errors.Add(messageInfo, e); } } if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } } protected virtual Messaging.Message RemoveMessagesInternal(MessageInfo messageTobeRemoved, MessageRemovedReason reason, OperationContext context) { return _topicManager.RemoveMessage(messageTobeRemoved, reason); } public override IList<MessageInfo> GetUnacknowledgeMessages(TimeSpan assginmentTimeout) { return _topicManager.GetUnAcknowledgedMessages(assginmentTimeout); } public override void RevokeAssignment(MessageInfo message, SubscriptionInfo subscription, OperationContext context) { Topic instance = _topicManager.GetTopic(message.Topic); if (instance != null) instance.RevokeAssignment(message, subscription); } public override IList<string> GetNotifiableClients() { return _topicManager.GetNotifiableClients(); } public override void RegiserTopicEventListener(ITopicEventListener listener) { _topicManager.RegisterTopicListener(listener); } public void RegisterSubscriptionEventListener(ISubscriptionEventListener listener) { } public override TopicState GetTopicsState() { return _topicManager.GetTopicsState(); } public override void SetTopicsState(TopicState topicState) { _topicManager.SetTopicsState(topicState); } public override TransferrableMessage GetTransferrableMessage(string topic, string messageId) { return _topicManager.GetTransferrableMessage(topic, messageId); } public override bool StoreTransferrableMessage(string topic, TransferrableMessage message) { bool result = _topicManager.StoreTransferrableMessage(topic, message); if (result && _context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return result; } public override void AcknowledgeMessageReceipt(string clientId, string topic, string messageId, OperationContext operationContext) { AcknowledgeMessageReceiptInternal(clientId, topic, messageId, operationContext); } public override OrderedDictionary GetMessageList(int bucketId, bool includeEventMessages) { return _topicManager.GetMessageList(); } public override long GetMessageCount(string topicName, OperationContext operationContext) { if (!IsCacheOperationAllowed(operationContext)) return default; if (topicName == default(string)) { throw new ArgumentNullException("topicName"); } Topic topic = _topicManager.GetTopic(topicName); if (topic != default(Topic)) { return topic.Count; } return 0; } public override Dictionary<string, TopicStats> GetTopicsStats(bool defaultTopicStats= false) { return _topicManager.GetTopicsStats(defaultTopicStats); } public override IDictionary<string, IList<string>> GetInActiveClientSubscriptions(TimeSpan inactivityThreshold) { return _topicManager.GetInActiveClientSubscriptions(inactivityThreshold); } public override IDictionary<string, IList<string>> GetActiveClientSubscriptions(TimeSpan inactivityThreshold) { return _topicManager.GetActiveClientSubscriptions(inactivityThreshold); } #endregion private void CreateEventsTopics() { try { //item level events _topicManager.CreateTopic(TopicConstant.ItemLevelEventsTopic); //Collection events _topicManager.CreateTopic(TopicConstant.CollectionEventsTopic); } catch (Exception) { } } } }
#if SILVERLIGHT using Microsoft.VisualStudio.TestTools.UnitTesting; #elif NETFX_CORE using DevExpress.TestFramework.NUnit; using Windows.UI.Xaml; #else using NUnit.Framework; #endif using System; using System.Windows; using System.Linq; namespace DevExpress.Mvvm.Tests { [TestFixture] public class ServiceContainerTests : BaseWpfFixture { protected override void TearDownCore() { base.TearDownCore(); ServiceContainer.Default = null; } public interface IService1 { } public interface IService2 { } public class TestService1 : IService1 { } public class TestService2 : IService2 { } public class TestService1_2 : IService1, IService2 { } [Test] public void ContainersLoopTest() { var child = new TestSupportServices(); var parent = new TestSupportServices(); child.ParentViewModel = parent; parent.ParentViewModel = child; var service1 = new TestService1(); child.ServiceContainer.RegisterService(service1, true); AssertHelper.AssertThrows<Exception>(() => { child.ServiceContainer.GetService<IService1>(); }, e => { Assert.AreEqual("A ServiceContainer should not be a direct or indirect parent for itself.", e.Message); }); } [Test] public void AddServicesWithoutKey() { IServiceContainer container = new ServiceContainer(null); TestService1 svc1 = new TestService1(); TestService1 svc1_ = new TestService1(); TestService2 svc2 = new TestService2(); container.RegisterService(svc1); Assert.AreEqual(svc1, container.GetService<IService1>()); container.RegisterService(svc2); Assert.AreEqual(svc1, container.GetService<IService1>()); Assert.AreEqual(svc2, container.GetService<IService2>()); container.RegisterService("svc1_", svc1_); Assert.AreEqual(svc1, container.GetService<IService1>()); Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_")); } [Test] public void AddServicesWithoutKey_2() { IServiceContainer container = new ServiceContainer(null); TestService1 svc1 = new TestService1(); TestService1 svc1_ = new TestService1(); TestService2 svc2 = new TestService2(); container.RegisterService("svc1_", svc1_); container.RegisterService(svc1); container.RegisterService(svc2); Assert.AreEqual(svc1, container.GetService<IService1>()); Assert.AreEqual(svc2, container.GetService<IService2>()); Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_")); } [Test] public void RemoveServices() { IServiceContainer container = new ServiceContainer(null); TestService1 svc1 = new TestService1(); TestService1 svc1_ = new TestService1(); TestService2 svc2 = new TestService2(); container.RegisterService(svc1); container.RegisterService(svc2); container.RegisterService("svc1_", svc1_); Assert.AreEqual(svc1, container.GetService<IService1>()); Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_")); Assert.AreEqual(svc2, container.GetService<IService2>()); container.UnregisterService(svc1); Assert.AreEqual(svc1_, container.GetService<IService1>()); Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_")); Assert.AreEqual(svc2, container.GetService<IService2>()); container.UnregisterService(svc1_); Assert.AreEqual(null, container.GetService<IService1>()); Assert.AreEqual(null, container.GetService<IService1>("svc1_")); Assert.AreEqual(svc2, container.GetService<IService2>()); container.UnregisterService(svc2); Assert.AreEqual(null, container.GetService<IService2>()); } [Test, ExpectedException(typeof(ArgumentException))] public void GetServiceNotByInterfaceType() { IServiceContainer container = new ServiceContainer(null); TestService1 svc1 = new TestService1(); container.RegisterService(svc1); container.GetService<TestService1>(); } [Test, ExpectedException(typeof(ArgumentException))] public void GetServiceNotByInterfaceTypeWinKeyName() { ServiceContainer container = new ServiceContainer(null); container.GetService<TestService1>("svc1_"); } [Test] public void AddServicesWithKey() { IServiceContainer container = new ServiceContainer(null); TestService1 svc1 = new TestService1(); TestService1 svc1_ = new TestService1(); container.RegisterService("svc1", svc1); container.RegisterService("svc1_", svc1_); Assert.AreEqual(svc1_, container.GetService<IService1>()); Assert.AreEqual(svc1, container.GetService<IService1>("svc1")); Assert.AreEqual(svc1_, container.GetService<IService1>("svc1_")); container.RegisterService(svc1_); Assert.AreEqual(svc1_, container.GetService<IService1>()); container.RegisterService(svc1); Assert.AreEqual(svc1, container.GetService<IService1>()); } [Test] public void GetServiceFromParent() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service1 = new TestService1(); child.ServiceContainer.RegisterService(service1); Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>()); var service2 = new TestService2(); parent.ServiceContainer.RegisterService(service2); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>()); child.ParentViewModel = parent; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>()); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly)); var service2Local = new TestService2(); child.ServiceContainer.RegisterService(service2Local); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly)); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents)); } [Test] public void B235125_GetServiceFromSecondParent() { var parent1 = new TestSupportServices(); var parent2 = new TestSupportServices(); var child = new TestSupportServices(); var service1 = new TestService1(); var service2 = new TestService1(); parent1.ServiceContainer.RegisterService(service1); parent2.ServiceContainer.RegisterService(service2); child.ParentViewModel = parent1; parent1.ParentViewModel = parent2; Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>()); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService1>(ServiceSearchMode.PreferParents)); } [Test] public void B235125_GetServiceFromSecondParentByKey() { var parent1 = new TestSupportServices(); var parent2 = new TestSupportServices(); var child = new TestSupportServices(); var service1 = new TestService1(); var service2 = new TestService1(); parent1.ServiceContainer.RegisterService("key", service1); parent2.ServiceContainer.RegisterService("key", service2); child.ParentViewModel = parent1; parent1.ParentViewModel = parent2; Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>("key")); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService1>("key", ServiceSearchMode.PreferParents)); } [Test] public void GetServiceFromParentByKey() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); parent.ServiceContainer.RegisterService("key", service2); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>("key")); child.ParentViewModel = parent; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key")); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly)); var service2Local = new TestService2(); child.ServiceContainer.RegisterService("key", service2Local); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly)); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferLocal)); } [Test] public void YieldToParentTest1() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); parent.ServiceContainer.RegisterService("key", service2); child.ParentViewModel = parent; var service2Local = new TestService2(); child.ServiceContainer.RegisterService("key", service2Local, true); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly)); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferLocal)); } [Test] public void YieldToParentTest2() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); parent.ServiceContainer.RegisterService(service2); child.ParentViewModel = parent; var service2Local = new TestService2(); child.ServiceContainer.RegisterService(service2Local, true); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly)); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferLocal)); } [Test] public void YieldToParentTest3() { var child = new TestSupportServices(); var service2Local = new TestService2(); child.ServiceContainer.RegisterService(service2Local, true); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.LocalOnly)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferLocal)); } [Test] public void YieldToParentTest4() { var child = new TestSupportServices(); var service2Local = new TestService2(); child.ServiceContainer.RegisterService("key", service2Local, true); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.LocalOnly)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents)); Assert.AreEqual(service2Local, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferLocal)); } [Test] public void GetService_PreferParent() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); child.ServiceContainer.RegisterService(service2); child.ParentViewModel = parent; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents)); } [Test] public void GetServiceByKey_PreferParent() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); child.ServiceContainer.RegisterService("key", service2); child.ParentViewModel = parent; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key", ServiceSearchMode.PreferParents)); } [Test] public void GetServiceFromParentByKey_InvalidParent() { var child = new TestSupportServices(); var service2 = new TestService2(); child.ServiceContainer.RegisterService("key", service2); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key")); Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>("key2")); child.ParentViewModel = child; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>("key")); Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>("key2")); } [Test] public void GetServiceFromParent_InvalidParent() { var child = new TestSupportServices(); var service2 = new TestService2(); child.ServiceContainer.RegisterService(service2); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>()); Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>()); child.ParentViewModel = child; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>()); Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>()); var service1 = new TestService1(); ServiceContainer.Default.RegisterService(service1); try { Assert.AreEqual(service1, child.ServiceContainer.GetService<IService1>()); } finally { ServiceContainer.Default.Clear(); } Assert.AreEqual(null, child.ServiceContainer.GetService<IService1>()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void RegisterNull() { var child = new TestSupportServices(); child.ServiceContainer.RegisterService(null); } [Test, ExpectedException(typeof(ArgumentNullException))] public void RegisterNullByKey() { var child = new TestSupportServices(); child.ServiceContainer.RegisterService("key", null); } [Test] public void RegisterByNullKey() { var child = new TestSupportServices(); var service = new TestService1(); child.ServiceContainer.RegisterService(null, service); Assert.AreEqual(service, child.ServiceContainer.GetService<IService1>()); } [Test] public void Clear() { var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); child.ServiceContainer.RegisterService(service2); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>()); child.ServiceContainer.Clear(); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>()); child.ServiceContainer.RegisterService("key", service2); child.ServiceContainer.Clear(); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>()); Assert.AreEqual(null, child.ServiceContainer.GetService<IService2>("key")); } [Test] public void RegisterServiceWithoutNameTwice() { var viewModel = new TestSupportServices(); viewModel.ServiceContainer.RegisterService(new TestService1()); var service1_2 = new TestService1_2(); viewModel.ServiceContainer.RegisterService(service1_2); Assert.AreEqual(service1_2, viewModel.ServiceContainer.GetService<IService1>()); Assert.AreEqual(service1_2, viewModel.ServiceContainer.GetService<IService2>()); var service2 = new TestService2(); viewModel.ServiceContainer.RegisterService(service2); Assert.AreEqual(service1_2, viewModel.ServiceContainer.GetService<IService1>()); Assert.AreEqual(service2, viewModel.ServiceContainer.GetService<IService2>()); } [Test] public void FindServiceWithoutKeyTest() { foreach(var useEmptyStringAsParentServiceKey in new bool?[] { null, false, true }) foreach(var useEmptyStringAsLocalServiceKey in new bool?[] { null, false, true }) { KeylessServiceSearchTestHelper tester = new KeylessServiceSearchTestHelper() { UseEmptyStringAsParentServiceKey = useEmptyStringAsParentServiceKey, UseEmptyStringAsLocalServiceKey = useEmptyStringAsLocalServiceKey }; tester.TestKeylessServiceSearch(29, parentHasKey: false, nestedHasKey: false, yieldToParent: false, preferLocal: false, assertActualIsNested: false); tester.TestKeylessServiceSearch(30, parentHasKey: false, nestedHasKey: false, yieldToParent: false, preferLocal: true, assertActualIsNested: true); tester.TestKeylessServiceSearch(31, parentHasKey: false, nestedHasKey: false, yieldToParent: true, preferLocal: false, assertActualIsNested: false); tester.TestKeylessServiceSearch(32, parentHasKey: false, nestedHasKey: false, yieldToParent: true, preferLocal: true, assertActualIsNested: false); tester.TestKeylessServiceSearch(33, parentHasKey: false, nestedHasKey: true, yieldToParent: false, preferLocal: false, assertActualIsNested: false); tester.TestKeylessServiceSearch(34, parentHasKey: false, nestedHasKey: true, yieldToParent: false, preferLocal: true, assertActualIsNested: false); tester.TestKeylessServiceSearch(35, parentHasKey: false, nestedHasKey: true, yieldToParent: true, preferLocal: false, assertActualIsNested: false); tester.TestKeylessServiceSearch(36, parentHasKey: false, nestedHasKey: true, yieldToParent: true, preferLocal: true, assertActualIsNested: false); tester.TestKeylessServiceSearch(37, parentHasKey: true, nestedHasKey: false, yieldToParent: false, preferLocal: false, assertActualIsNested: true); tester.TestKeylessServiceSearch(38, parentHasKey: true, nestedHasKey: false, yieldToParent: false, preferLocal: true, assertActualIsNested: true); tester.TestKeylessServiceSearch(39, parentHasKey: true, nestedHasKey: false, yieldToParent: true, preferLocal: false, assertActualIsNested: true); tester.TestKeylessServiceSearch(40, parentHasKey: true, nestedHasKey: false, yieldToParent: true, preferLocal: true, assertActualIsNested: true); tester.TestKeylessServiceSearch(41, parentHasKey: true, nestedHasKey: true, yieldToParent: false, preferLocal: false, assertActualIsNested: false); tester.TestKeylessServiceSearch(42, parentHasKey: true, nestedHasKey: true, yieldToParent: false, preferLocal: true, assertActualIsNested: true); tester.TestKeylessServiceSearch(43, parentHasKey: true, nestedHasKey: true, yieldToParent: true, preferLocal: false, assertActualIsNested: false); tester.TestKeylessServiceSearch(44, parentHasKey: true, nestedHasKey: true, yieldToParent: true, preferLocal: true, assertActualIsNested: false); } } [Test] public void GetApplicationService() { var defaultServiceContainer = new DefaultServiceContainer2(); var service2InApp = new TestService2(); defaultServiceContainer.Resources.Add("testService2", service2InApp); var service11 = new TestService1(); var service12 = new TestService1(); defaultServiceContainer.Resources.Add("testService11", service11); defaultServiceContainer.Resources.Add("testService12", service12); ServiceContainer.Default = defaultServiceContainer; var parent = new TestSupportServices(); var child = new TestSupportServices(); var service2 = new TestService2(); child.ServiceContainer.RegisterService(service2); child.ParentViewModel = parent; Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>(ServiceSearchMode.PreferParents)); Assert.AreEqual(service2, child.ServiceContainer.GetService<IService2>()); Assert.IsNotNull(child.ServiceContainer.GetService<IService1>()); Assert.AreEqual(service11, child.ServiceContainer.GetService<IService1>("testService11")); } [Test] public void GetLastParent() { var root = new TestSupportServices(); var parent = new TestSupportServices(); var child = new TestSupportServices(); parent.ParentViewModel = root; child.ParentViewModel = parent; var rootSrv = new TestService1(); var parentSrv = new TestService1(); var childSrv = new TestService1(); root.ServiceContainer.RegisterService(rootSrv); parent.ServiceContainer.RegisterService(parentSrv); child.ServiceContainer.RegisterService(childSrv); Assert.AreEqual(rootSrv, child.ServiceContainer.GetService<IService1>(ServiceSearchMode.PreferParents)); } [Test] public void GetApplicationService_DoNotUseServicesInMergedDictionaries() { var defaultServiceContainer = new DefaultServiceContainer2(); var service1 = new TestService1(); var mergedDictionary = new ResourceDictionary(); mergedDictionary.Add("testService2", service1); defaultServiceContainer.Resources.MergedDictionaries.Add(mergedDictionary); Assert.IsNull(defaultServiceContainer.GetService<IService1>()); } class KeylessServiceSearchTestHelper { public bool? UseEmptyStringAsParentServiceKey; public bool? UseEmptyStringAsLocalServiceKey; public void TestKeylessServiceSearch(int message, bool parentHasKey, bool nestedHasKey, bool yieldToParent, bool preferLocal, bool assertActualIsNested) { IServiceContainer parentContainer = new ServiceContainer(null); IServiceContainer nestedContainer = new ServiceContainer(new ParentServiceContainerWrapper(parentContainer)); TestService1 parentService = new TestService1(); RegisterService(parentHasKey, "p", parentService, false, parentContainer, UseEmptyStringAsParentServiceKey); TestService1 nestedService = new TestService1(); RegisterService(nestedHasKey, "n", nestedService, yieldToParent, nestedContainer, UseEmptyStringAsLocalServiceKey); string messageString = message.ToString() + " " + ToString(UseEmptyStringAsParentServiceKey) + " " + ToString(UseEmptyStringAsLocalServiceKey); Assert.AreEqual(assertActualIsNested ? nestedService : parentService, nestedContainer.GetService<IService1>(preferLocal ? ServiceSearchMode.PreferLocal : ServiceSearchMode.PreferParents), messageString); } void RegisterService<T>(bool registerWithKey, string key, T service, bool yieldToParent, IServiceContainer serviceContainer, bool? useEmptyStringAsServiceKey) { if(registerWithKey) serviceContainer.RegisterService(key, service, yieldToParent); else if(!useEmptyStringAsServiceKey.HasValue) serviceContainer.RegisterService(service, yieldToParent); else if(useEmptyStringAsServiceKey.Value) serviceContainer.RegisterService(string.Empty, service, yieldToParent); else serviceContainer.RegisterService(null, service, yieldToParent); } string ToString(bool? v) { return v == null ? "none" : v.Value ? "empty" : "null"; } } } public class TestSupportServices : ISupportServices, ISupportParentViewModel, ISupportParameter { readonly ServiceContainer serviceContainer; public TestSupportServices() { serviceContainer = new ServiceContainer(this); } public IServiceContainer ServiceContainer { get { return serviceContainer; } } public object ParentViewModel { get; set; } public object Parameter { get; set; } public void OnNavigatedTo(object parameter) { Parameter = parameter; } } public class ParentServiceContainerWrapper : ISupportParentViewModel { class ParentServiceContainerOwner : ISupportServices { IServiceContainer parentServiceContainer; public ParentServiceContainerOwner(IServiceContainer parentServiceContainer) { this.parentServiceContainer = parentServiceContainer; } IServiceContainer ISupportServices.ServiceContainer { get { return parentServiceContainer; } } } ParentServiceContainerOwner parentServiceContainerOwner; public ParentServiceContainerWrapper(IServiceContainer parentServiceContainer) { this.parentServiceContainerOwner = new ParentServiceContainerOwner(parentServiceContainer); } object ISupportParentViewModel.ParentViewModel { get { return parentServiceContainerOwner; } set { throw new NotSupportedException(); } } } class DefaultServiceContainer2 : DefaultServiceContainer { public DefaultServiceContainer2() : base() { Resources = new ResourceDictionary(); } public ResourceDictionary Resources { get; private set; } protected override ResourceDictionary GetApplicationResources() { return Resources; } } #if !FREE && !NETFX_CORE && !SILVERLIGHT [TestFixture] public class ServiceBaseTests : BaseWpfFixture { [Test] public void UnregisterServiceOnDataContextChanged() { Button control = new Button(); TestVM vm1 = TestVM.Create(); TestVM vm2 = TestVM.Create(); TestServiceBase service = new TestServiceBase(); Interaction.GetBehaviors(control).Add(service); control.DataContext = vm1; Assert.AreEqual(service, vm1.GetService<ITestService>()); control.DataContext = vm2; Assert.AreEqual(null, vm1.GetService<ITestService>()); Assert.AreEqual(service, vm2.GetService<ITestService>()); } [Test] public void UnregisterServiceOnDetaching() { Button control = new Button(); TestVM vm1 = TestVM.Create(); TestServiceBase service = new TestServiceBase(); Interaction.GetBehaviors(control).Add(service); control.DataContext = vm1; Assert.AreEqual(service, vm1.GetService<ITestService>()); Interaction.GetBehaviors(control).Remove(service); Assert.AreEqual(null, vm1.GetService<ITestService>()); } [Test] public void T250427() { Grid mainV = new Grid(); TestVM mainVM = TestVM.Create(); TestServiceBase mainService = new TestServiceBase(); Interaction.GetBehaviors(mainV).Add(mainService); mainV.DataContext = mainVM; Grid childV = new Grid(); TestVM childVM = TestVM.Create(); TestServiceBase childService = new TestServiceBase(); Interaction.GetBehaviors(childV).Add(childService); mainV.Children.Add(childV); Assert.AreEqual(childService, mainVM.GetService<ITestService>()); childV.DataContext = childVM; Assert.AreEqual(mainService, mainVM.GetService<ITestService>()); Assert.AreEqual(childService, childVM.GetService<ITestService>()); } public class TestVM { public static TestVM Create() { return ViewModelSource.Create(() => new TestVM()); } protected TestVM() { } } public interface ITestService { } public class TestServiceBase : ServiceBase, ITestService { } } #endif }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in. // It is available from http://www.codeplex.com/hyperAddin #define FEATURE_MANAGED_ETW #if !ES_BUILD_STANDALONE #define FEATURE_ACTIVITYSAMPLING #endif #if ES_BUILD_STANDALONE #define FEATURE_MANAGED_ETW_CHANNELS // #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS #endif #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; #endif using System; using System.Runtime.InteropServices; using System.Security; using System.Collections.ObjectModel; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; using System.Collections.Generic; using System.Text; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; using System.Collections.Generic; using System.Text; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { public partial class EventSource { private byte[] providerMetadata; /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> public EventSource( string eventSourceName) : this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> public EventSource( string eventSourceName, EventSourceSettings config) : this(eventSourceName, config, null) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// /// Also specify a list of key-value pairs called traits (you must pass an even number of strings). /// The first string is the key and the second is the value. These are not interpreted by EventSource /// itself but may be interprated the listeners. Can be fetched with GetTrait(string). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> /// <param name="traits">A collection of key-value strings (must be an even number).</param> public EventSource( string eventSourceName, EventSourceSettings config, params string[] traits) : this( eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName, config, traits) { if (eventSourceName == null) { throw new ArgumentNullException("eventSourceName"); } Contract.EndContractBlock(); } /// <summary> /// Writes an event with no fields and default options. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> [SecuritySafeCritical] public unsafe void Write(string eventName) { if (eventName == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); var data = new EmptyStruct(); this.WriteImpl(eventName, ref options, ref data, null, null); } /// <summary> /// Writes an event with no fields. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> [SecuritySafeCritical] public unsafe void Write(string eventName, EventSourceOptions options) { if (eventName == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } var data = new EmptyStruct(); this.WriteImpl(eventName, ref options, ref data, null, null); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, T data) { if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, ref data, null, null); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, EventSourceOptions options, T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, ref data, null, null); } /// <summary> /// Writes an event. /// This overload is for use with extension methods that wish to efficiently /// forward the options or data parameter without performing an extra copy. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, ref data, null, null); } /// <summary> /// Writes an event. /// This overload is meant for clients that need to manipuate the activityId /// and related ActivityId for the event. /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="activityId"> /// The GUID of the activity associated with this event. /// </param> /// <param name="relatedActivityId"> /// The GUID of another activity that is related to this activity, or Guid.Empty /// if there is no related activity. Most commonly, the Start operation of a /// new activity specifies a parent activity as its related activity. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref Guid activityId, ref Guid relatedActivityId, ref T data) { if (!this.IsEnabled()) { return; } fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId) { this.WriteImpl( eventName, ref options, ref data, pActivity, relatedActivityId == Guid.Empty ? null : pRelated); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// This method does a quick check on whether this event is enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> [SecuritySafeCritical] private unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { if (!this.IsEnabled()) { return; } byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// Attention: This API does not check whether the event is enabled or not. /// Please use WriteMultiMerge to avoid spending CPU cycles for events that are /// not enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> [SecuritySafeCritical] private unsafe void WriteMultiMergeInner( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventTypes.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventTypes.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags); if (nameInfo == null) { return; } identity = nameInfo.identity; EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if !ES_BUILD_PCL System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); for (int i = 0; i < eventTypes.typeInfos.Length; i++) { eventTypes.typeInfos[i].WriteObjectData(TraceLoggingDataCollector.Instance, values[i]); } this.WriteEventRaw( ref descriptor, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); } finally { this.WriteCleanup(pins, pinCount); } } } /// <summary> /// Writes an extended event, where the values of the event have already /// been serialized in "data". /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="data"> /// The previously serialized values to include in the event. Must not be null. /// The number and types of the values must match the number and types of the /// fields described by the eventTypes parameter. /// </param> [SecuritySafeCritical] internal unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, EventData* data) { if (!this.IsEnabled()) { return; } fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } // We make a descriptor for each EventData, and because we morph strings to counted strings // we may have 2 for each arg, so we allocate enough for this. var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); int numDescrs = 3; for (int i = 0; i < eventTypes.typeInfos.Length; i++) { // Until M3, we need to morph strings to a counted representation // When TDH supports null terminated strings, we can remove this. if (eventTypes.typeInfos[i].DataType == typeof(string)) { // Write out the size of the string descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size; descriptors[numDescrs].m_Size = 2; numDescrs++; descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator numDescrs++; } else { descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size; // old conventions for bool is 4 bytes, but meta-data assumes 1. if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool)) descriptors[numDescrs].m_Size = 1; numDescrs++; } } this.WriteEventRaw( ref descriptor, activityID, childActivityID, numDescrs, (IntPtr)descriptors); } } } [SecuritySafeCritical] private unsafe void WriteImpl<T>( string eventName, ref EventSourceOptions options, ref T data, Guid* pActivityId, Guid* pRelatedActivityId) { try { var eventTypes = SimpleEventTypes<T>.Instance; fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = this.providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if !ES_BUILD_PCL System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif EventOpcode opcode = (EventOpcode)descriptor.Opcode; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; if (pActivityId == null && pRelatedActivityId == null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relatedActivityId != Guid.Empty) pRelatedActivityId = &relatedActivityId; } try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); eventTypes.typeInfo.WriteData(TraceLoggingDataCollector.Instance, ref data); this.WriteEventRaw( ref descriptor, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); // TODO enable filtering for listners. if (m_Dispatchers != null) { var eventData = (EventPayload)(eventTypes.typeInfo.GetData(data)); WriteToAllListeners(eventName, pActivityId, eventData); } } catch(Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(ex); } finally { this.WriteCleanup(pins, pinCount); } } } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(ex); } } [SecurityCritical] private unsafe void WriteToAllListeners(string eventName, Guid* pActivityId, EventPayload payload) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventName = eventName; // Self described events do not have an id attached. We mark it internally with -1. eventCallbackArgs.EventId = -1; if (pActivityId != null) eventCallbackArgs.RelatedActivityId = *pActivityId; if (payload != null) { eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values); eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys); } DisptachToAllListeners(-1, pActivityId, eventCallbackArgs); } #if !ES_BUILD_PCL [System.Runtime.ConstrainedExecution.ReliabilityContract( System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] #endif [SecurityCritical] [NonEvent] private unsafe void WriteCleanup(GCHandle* pPins, int cPins) { DataCollector.ThreadInstance.Disable(); for (int i = 0; i != cPins; i++) { if (IntPtr.Zero != (IntPtr)pPins[i]) { pPins[i].Free(); } } } private void InitializeProviderMetadata() { if (m_traits != null) { List<byte> traitMetaData = new List<byte>(100); for (int i = 0; i < m_traits.Length - 1; i += 2) { if (m_traits[i].StartsWith("ETW_")) { string etwTrait = m_traits[i].Substring(4); byte traitNum; if (!byte.TryParse(etwTrait, out traitNum)) { if (etwTrait == "GROUP") traitNum = 1; else throw new ArgumentException(Environment.GetResourceString("UnknownEtwTrait", etwTrait), "traits"); } string value = m_traits[i + 1]; int lenPos = traitMetaData.Count; traitMetaData.Add(0); // Emit size (to be filled in later) traitMetaData.Add(0); traitMetaData.Add(traitNum); // Emit Trait number var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above. traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8)); } } providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0); int startPos = providerMetadata.Length-traitMetaData.Count; foreach (var b in traitMetaData) providerMetadata[startPos++] = b; } else providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0); } private static int AddValueToMetaData(List<byte> metaData, string value) { if (value.Length == 0) return 0; int startPos = metaData.Count; char firstChar = value[0]; if (firstChar == '@') metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1))); else if (firstChar == '{') metaData.AddRange(new Guid(value).ToByteArray()); else if (firstChar == '#') { for (int i = 1; i < value.Length; i++) { if (value[i] != ' ') // Skp spaces between bytes. { if (!(i + 1 < value.Length)) throw new ArgumentException(Environment.GetResourceString("EvenHexDigits"), "traits"); metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1]))); i++; } } } else if (' ' <= firstChar) // Is it alphabetic (excludes digits and most punctuation. metaData.AddRange(Encoding.UTF8.GetBytes(value)); else throw new ArgumentException(Environment.GetResourceString("IllegalValue", value), "traits"); return metaData.Count - startPos; } /// <summary> /// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception. /// </summary> private static int HexDigit(char c) { if ('0' <= c && c <= '9') return (c - '0'); if ('a' <= c) c = unchecked((char) (c - ('a' - 'A'))); // Convert to lower case if ('A' <= c && c <= 'F') return (c - 'A' + 10); throw new ArgumentException(Environment.GetResourceString("BadHexDigit", c), "traits"); } private NameInfo UpdateDescriptor( string name, TraceLoggingEventTypes eventInfo, ref EventSourceOptions options, out EventDescriptor descriptor) { NameInfo nameInfo = null; int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventInfo.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventInfo.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventInfo.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventInfo.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags); identity = nameInfo.identity; } descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); return nameInfo; } } }
//--------------------------------------------------------------------------- // // <copyright file=KeyGesture.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: The KeyGesture class is used by the developer to create Keyboard Input Bindings // // See spec at : http://avalon/coreUI/Specs/Commanding%20--%20design.htm // //* KeyGesture class serves the purpose of Input Bindings for Keyboard Device. //* one will be passing the instance of this around with CommandLink to represent Accelerator Keys // // History: // 06/01/2003 : chandras - Created // //--------------------------------------------------------------------------- using System; using System.Globalization; using System.Windows.Input; using System.Windows; using System.Windows.Markup; using System.ComponentModel; using MS.Internal.PresentationCore; namespace System.Windows.Input { /// <summary> /// KeyGesture - Key and Modifier combination. /// Can be set on properties of KeyBinding and RoutedCommand. /// </summary> [TypeConverter(typeof(KeyGestureConverter))] [ValueSerializer(typeof(KeyGestureValueSerializer))] public class KeyGesture : InputGesture { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// constructor /// </summary> /// <param name="key">key</param> public KeyGesture(Key key) : this(key, ModifierKeys.None) { } /// <summary> /// constructor /// </summary> /// <param name="modifiers">modifiers</param> /// <param name="key">key</param> public KeyGesture(Key key, ModifierKeys modifiers) : this(key, modifiers, String.Empty, true) { } /// <summary> /// constructor /// </summary> /// <param name="modifiers">modifiers</param> /// <param name="key">key</param> /// <param name="displayString">display string</param> public KeyGesture(Key key, ModifierKeys modifiers, string displayString) : this(key, modifiers, displayString, true) { } /// <summary> /// Internal constructor used by KeyBinding to avoid key and modifier validation /// This allows setting KeyBinding.Key and KeyBinding.Modifiers without regard /// to order. /// </summary> /// <param name="key">Key</param> /// <param name="modifiers">Modifiers</param> /// <param name="validateGesture">If true, throws an exception if the key and modifier are not valid</param> internal KeyGesture(Key key, ModifierKeys modifiers, bool validateGesture) : this(key, modifiers, String.Empty, validateGesture) { } /// <summary> /// Private constructor that does the real work. /// </summary> /// <param name="key">Key</param> /// <param name="modifiers">Modifiers</param> /// <param name="displayString">display string</param> /// <param name="validateGesture">If true, throws an exception if the key and modifier are not valid</param> private KeyGesture(Key key, ModifierKeys modifiers, string displayString, bool validateGesture) { if(!ModifierKeysConverter.IsDefinedModifierKeys(modifiers)) throw new InvalidEnumArgumentException("modifiers", (int)modifiers, typeof(ModifierKeys)); if(!IsDefinedKey(key)) throw new InvalidEnumArgumentException("key", (int)key, typeof(Key)); if (displayString == null) throw new ArgumentNullException("displayString"); if(validateGesture && !IsValid(key, modifiers)) { throw new NotSupportedException(SR.Get(SRID.KeyGesture_Invalid, modifiers, key)); } _modifiers = modifiers; _key = key; _displayString = displayString; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Modifier /// </summary> public ModifierKeys Modifiers { get { return _modifiers; } } /// <summary> /// Key /// </summary> public Key Key { get { return _key; } } /// <summary> /// DisplayString /// </summary> public string DisplayString { get { return _displayString; } } /// <summary> /// Returns a string that can be used to display the KeyGesture. If the /// DisplayString was set by the constructor, it is returned. Otherwise /// a suitable string is created from the Key and Modifiers, with any /// conversions being governed by the given CultureInfo. /// </summary> /// <param name="culture">the culture used when creating a string from Key and Modifiers</param> public string GetDisplayStringForCulture(CultureInfo culture) { // return the DisplayString, if it was set by the ctor if (!String.IsNullOrEmpty(_displayString)) { return _displayString; } // otherwise use the type converter return (string)_keyGestureConverter.ConvertTo(null, culture, this, typeof(string)); } /// <summary> /// Compares InputEventArgs with current Input /// </summary> /// <param name="targetElement">the element to receive the command</param> /// <param name="inputEventArgs">inputEventArgs to compare to</param> /// <returns>True - KeyGesture matches, false otherwise. /// </returns> public override bool Matches(object targetElement, InputEventArgs inputEventArgs) { KeyEventArgs keyEventArgs = inputEventArgs as KeyEventArgs; if(keyEventArgs != null && IsDefinedKey(keyEventArgs.Key)) { return ( ( (int)Key == (int)keyEventArgs.RealKey ) && ( this.Modifiers == Keyboard.Modifiers ) ); } return false; } // Check for Valid enum, as any int can be casted to the enum. internal static bool IsDefinedKey(Key key) { return (key >= Key.None && key <= Key.OemClear); } #endregion Public Methods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods ///<summary> /// Is Valid Keyboard input to process for commands ///</summary> internal static bool IsValid(Key key, ModifierKeys modifiers) { // // Don't enforce any rules on the Function keys or on the number pad keys. // if(!( ( key >= Key.F1 && key <= Key.F24 ) || ( key >= Key.NumPad0 && key <= Key.Divide ) )) { // // We check whether Control/Alt/Windows key is down for modifiers. We don't check // for shift at this time as Shift with any combination is already covered in above check. // Shift alone as modifier case, we defer to the next condition to avoid conflicing with // TextInput. if(( modifiers & ( ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Windows ) ) != 0) { switch(key) { case Key.LeftCtrl: case Key.RightCtrl: case Key.LeftAlt: case Key.RightAlt: case Key.LWin: case Key.RWin: return false; default: return true; } } else if(( key >= Key.D0 && key <= Key.D9 ) || ( key >= Key.A && key <= Key.Z )) { return false; } } return true; } /// <summary> /// Decode the strings keyGestures and displayStrings, creating a sequence /// of KeyGestures. Add each KeyGesture to the given InputGestureCollection. /// The two input strings typically come from a resource file. /// </summary> internal static void AddGesturesFromResourceStrings(string keyGestures, string displayStrings, InputGestureCollection gestures) { while (!String.IsNullOrEmpty(keyGestures)) { string keyGestureToken; string keyDisplayString; // break apart first gesture from the rest int index = keyGestures.IndexOf(MULTIPLEGESTURE_DELIMITER, StringComparison.Ordinal); if (index >= 0) { // multiple gestures exist keyGestureToken = keyGestures.Substring(0, index); keyGestures = keyGestures.Substring(index + 1); } else { keyGestureToken = keyGestures; keyGestures = String.Empty; } // similarly, break apart first display string from the rest index = displayStrings.IndexOf(MULTIPLEGESTURE_DELIMITER, StringComparison.Ordinal); if (index >= 0) { // multiple display strings exist keyDisplayString = displayStrings.Substring(0, index); displayStrings = displayStrings.Substring(index + 1); } else { keyDisplayString = displayStrings; displayStrings = String.Empty; } KeyGesture keyGesture = CreateFromResourceStrings(keyGestureToken, keyDisplayString); if (keyGesture != null) { gestures.Add(keyGesture); } } } internal static KeyGesture CreateFromResourceStrings(string keyGestureToken, string keyDisplayString) { // combine the gesture and the display string, producing a string // that the type converter will recognize if (!String.IsNullOrEmpty(keyDisplayString)) { keyGestureToken += KeyGestureConverter.DISPLAYSTRING_SEPARATOR + keyDisplayString; } return _keyGestureConverter.ConvertFromInvariantString(keyGestureToken) as KeyGesture; } #endregion Internal Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private ModifierKeys _modifiers = ModifierKeys.None; private Key _key = Key.None; private string _displayString; private const string MULTIPLEGESTURE_DELIMITER = ";"; private static TypeConverter _keyGestureConverter = new KeyGestureConverter(); //private static bool _classRegistered = false; #endregion Private Fields } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComMaterials.Inventory.DS { public class IV_BalanceBinDS { public IV_BalanceBinDS() { } private const string THIS = "PCSComMaterials.Inventory.DS.DS.IV_BalanceBinDS"; //************************************************************************** /// <Description> /// This method uses to add data to IV_BalanceBin /// </Description> /// <Inputs> /// IV_BalanceBinVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { IV_BalanceBinVO objObject = (IV_BalanceBinVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO IV_BalanceBin(" + IV_BalanceBinTable.EFFECTDATE_FLD + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "," + IV_BalanceBinTable.PRODUCTID_FLD + "," + IV_BalanceBinTable.LOCATIONID_FLD + "," + IV_BalanceBinTable.BINID_FLD + "," + IV_BalanceBinTable.STOCKUMID_FLD + ")" + "VALUES(?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceBinTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceBinTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceBinTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// AddAndReturnID /// </summary> /// <param name="pobjObjectVO"></param> /// <author>Trada</author> /// <date>Monday, October 9 2006</date> public int AddAndReturnID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddAndReturnID()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { IV_BalanceBinVO objObject = (IV_BalanceBinVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO IV_BalanceBin(" + IV_BalanceBinTable.EFFECTDATE_FLD + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "," + IV_BalanceBinTable.PRODUCTID_FLD + "," + IV_BalanceBinTable.LOCATIONID_FLD + "," + IV_BalanceBinTable.BINID_FLD + "," + IV_BalanceBinTable.STOCKUMID_FLD + ")" + "VALUES(?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceBinTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceBinTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); if (objObject.CommitQuantity != 0) { ocmdPCS.Parameters[IV_BalanceBinTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; } else { ocmdPCS.Parameters[IV_BalanceBinTable.COMMITQUANTITY_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.STOCKUMID_FLD, OleDbType.Integer)); if (objObject.StockUMID != 0) { ocmdPCS.Parameters[IV_BalanceBinTable.STOCKUMID_FLD].Value = objObject.StockUMID; } else { ocmdPCS.Parameters[IV_BalanceBinTable.STOCKUMID_FLD].Value = DBNull.Value; } strSql += " ; SELECT @@IDENTITY AS NEWID"; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); object objReturn = ocmdPCS.ExecuteScalar(); if (objReturn != null) { return int.Parse(objReturn.ToString()); } else { return 0; } } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from IV_BalanceBin /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + IV_BalanceBinTable.TABLE_NAME + " WHERE " + "BalanceBinID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from IV_BalanceBin /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// IV_BalanceBinVO /// </Outputs> /// <Returns> /// IV_BalanceBinVO /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + IV_BalanceBinTable.BALANCEBINID_FLD + "," + IV_BalanceBinTable.EFFECTDATE_FLD + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "," + IV_BalanceBinTable.PRODUCTID_FLD + "," + IV_BalanceBinTable.LOCATIONID_FLD + "," + IV_BalanceBinTable.BINID_FLD + "," + IV_BalanceBinTable.STOCKUMID_FLD + " FROM " + IV_BalanceBinTable.TABLE_NAME + " WHERE " + IV_BalanceBinTable.BALANCEBINID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); IV_BalanceBinVO objObject = new IV_BalanceBinVO(); while (odrPCS.Read()) { objObject.BalanceBinID = int.Parse(odrPCS[IV_BalanceBinTable.BALANCEBINID_FLD].ToString()); objObject.EffectDate = DateTime.Parse(odrPCS[IV_BalanceBinTable.EFFECTDATE_FLD].ToString()); objObject.OHQuantity = Decimal.Parse(odrPCS[IV_BalanceBinTable.OHQUANTITY_FLD].ToString()); objObject.CommitQuantity = Decimal.Parse(odrPCS[IV_BalanceBinTable.COMMITQUANTITY_FLD].ToString()); objObject.ProductID = int.Parse(odrPCS[IV_BalanceBinTable.PRODUCTID_FLD].ToString()); objObject.LocationID = int.Parse(odrPCS[IV_BalanceBinTable.LOCATIONID_FLD].ToString()); objObject.BinID = int.Parse(odrPCS[IV_BalanceBinTable.BINID_FLD].ToString()); objObject.StockUMID = int.Parse(odrPCS[IV_BalanceBinTable.STOCKUMID_FLD].ToString()); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to IV_BalanceBin /// </Description> /// <Inputs> /// IV_BalanceBinVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; IV_BalanceBinVO objObject = (IV_BalanceBinVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE IV_BalanceBin SET " + IV_BalanceBinTable.EFFECTDATE_FLD + "= ?" + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "= ?" + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "= ?" + "," + IV_BalanceBinTable.PRODUCTID_FLD + "= ?" + "," + IV_BalanceBinTable.LOCATIONID_FLD + "= ?" + "," + IV_BalanceBinTable.BINID_FLD + "= ?" + "," + IV_BalanceBinTable.STOCKUMID_FLD + "= ?" + " WHERE " + IV_BalanceBinTable.BALANCEBINID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceBinTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceBinTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); if (objObject.CommitQuantity != 0) { ocmdPCS.Parameters[IV_BalanceBinTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; } else { ocmdPCS.Parameters[IV_BalanceBinTable.COMMITQUANTITY_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.STOCKUMID_FLD, OleDbType.Integer)); if (objObject.StockUMID != 0) { ocmdPCS.Parameters[IV_BalanceBinTable.STOCKUMID_FLD].Value = objObject.StockUMID; } else { ocmdPCS.Parameters[IV_BalanceBinTable.STOCKUMID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceBinTable.BALANCEBINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceBinTable.BALANCEBINID_FLD].Value = objObject.BalanceBinID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from IV_BalanceBin /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + IV_BalanceBinTable.BALANCEBINID_FLD + "," + IV_BalanceBinTable.EFFECTDATE_FLD + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "," + IV_BalanceBinTable.PRODUCTID_FLD + "," + IV_BalanceBinTable.LOCATIONID_FLD + "," + IV_BalanceBinTable.BINID_FLD + "," + IV_BalanceBinTable.STOCKUMID_FLD + " FROM " + IV_BalanceBinTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, IV_BalanceBinTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + IV_BalanceBinTable.BALANCEBINID_FLD + "," + IV_BalanceBinTable.EFFECTDATE_FLD + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "," + IV_BalanceBinTable.PRODUCTID_FLD + "," + IV_BalanceBinTable.LOCATIONID_FLD + "," + IV_BalanceBinTable.BINID_FLD + "," + IV_BalanceBinTable.STOCKUMID_FLD + " FROM " + IV_BalanceBinTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, IV_BalanceBinTable.TABLE_NAME); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get all OnHand Balance Bin in this period and previous period /// </summary> /// <param name="pdtmEffectDate"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, October 11 2006</date> public DataSet GetAllOnHandBalanceBinInTwoPeriod(DateTime pdtmEffectDate) { const string METHOD_NAME = THIS + ".GetAllOnHandBalanceBinInTwoPeriod()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + IV_BalanceBinTable.BALANCEBINID_FLD + "," + IV_BalanceBinTable.EFFECTDATE_FLD + "," + IV_BalanceBinTable.OHQUANTITY_FLD + "," + IV_BalanceBinTable.COMMITQUANTITY_FLD + "," + IV_BalanceBinTable.PRODUCTID_FLD + "," + IV_BalanceBinTable.LOCATIONID_FLD + "," + IV_BalanceBinTable.BINID_FLD + "," + IV_BalanceBinTable.STOCKUMID_FLD + " FROM " + IV_BalanceBinTable.TABLE_NAME + " WHERE " + IV_BalanceBinTable.EFFECTDATE_FLD + " = '" + pdtmEffectDate.ToShortDateString() + "'" + " OR " + IV_BalanceBinTable.EFFECTDATE_FLD + " = '" + pdtmEffectDate.AddMonths(-1).ToShortDateString() + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, IV_BalanceBinTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataTable GetBalanceQuantity(DateTime pdtmDate) { const string METHOD_NAME = THIS + ".GetBalanceQuantity()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { DateTime dtmLastMonth = pdtmDate.AddMonths(-1); string strSql = "SELECT ProductID, SUM(ISNULL(OHQuantity,0)) AS OHQuantity" + " FROM IV_BalanceBin IB JOIN MST_BIN MB ON IB.BinID = MB.BinID" + " AND MB.BinTypeID <> " + (int)BinTypeEnum.LS + " WHERE DATEPART(year, EffectDate) = " + dtmLastMonth.Year + " AND DATEPART(month, EffectDate) = " + dtmLastMonth.Month + " GROUP BY ProductID ORDER BY ProductID"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataTable GetAvailableQuantityForPlan(DateTime pdtmDate) { const string METHOD_NAME = THIS + ".GetAvailableQuantityForPlan()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { DateTime dtmLastMonth = pdtmDate.AddMonths(-1); string strSql = "SELECT IB.LocationID, ProductID, SUM(ISNULL(OHQuantity,0)) AS SupplyQuantity" + " FROM IV_BalanceBin IB JOIN MST_BIN MB ON IB.BinID = MB.BinID" + " AND MB.BinTypeID NOT IN (" + (int)BinTypeEnum.NG + "," + (int)BinTypeEnum.LS + ")" + " WHERE DATEPART(year, EffectDate) = " + dtmLastMonth.Year + " AND DATEPART(month, EffectDate) = " + dtmLastMonth.Month + " GROUP BY IB.LocationID, ProductID ORDER BY IB.LocationID, ProductID"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); DataTable dtbData = new DataTable(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get balance in OK and Buffer bin /// </summary> /// <param name="pdtmDate">Effect Date</param> /// <returns></returns> public DataTable GetBeginBalance(DateTime pdtmDate) { const string METHOD_NAME = THIS + ".GetBeginBalance()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { DateTime dtmLastMonth = pdtmDate.AddMonths(-1); string strSql = "SELECT ProductID, SUM(ISNULL(OHQuantity,0)) AS Quantity" + " FROM IV_BalanceBin IB JOIN MST_BIN MB ON IB.BinID = MB.BinID" + " AND MB.BinTypeID NOT IN (" + (int)BinTypeEnum.LS + "," + (int)BinTypeEnum.NG + ")" + " WHERE DATEPART(year, EffectDate) = " + dtmLastMonth.Year + " AND DATEPART(month, EffectDate) = " + dtmLastMonth.Month + " GROUP BY ProductID ORDER BY ProductID"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); DataTable dtbData = new DataTable(IV_BalanceBinTable.TABLE_NAME); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbData); return dtbData; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { /// <summary>Provides a pool of connections to the same endpoint.</summary> internal sealed class HttpConnectionPool : IDisposable { /// <summary>Maximum number of milliseconds a connection is allowed to be idle in the pool before we remove it.</summary> private const int MaxIdleTimeMilliseconds = 100_000; /// <summary>List of idle connections stored in the pool.</summary> private readonly List<CachedConnection> _idleConnections = new List<CachedConnection>(); /// <summary>The maximum number of connections allowed to be associated with the pool.</summary> private readonly int _maxConnections; /// <summary>The head of a list of waiters waiting for a connection. Null if no one's waiting.</summary> private ConnectionWaiter _waitersHead; /// <summary>The tail of a list of waiters waiting for a connection. Null if no one's waiting.</summary> private ConnectionWaiter _waitersTail; /// <summary>The number of connections associated with the pool. Some of these may be in <see cref="_idleConnections"/>, others may be in use.</summary> private int _associatedConnectionCount; /// <summary>Whether the pool has been used since the last time a cleanup occurred.</summary> private bool _usedSinceLastCleanup = true; /// <summary>Whether the pool has been disposed.</summary> private bool _disposed; /// <summary>Initializes the pool.</summary> /// <param name="maxConnections">The maximum number of connections allowed to be associated with the pool at any given time.</param> public HttpConnectionPool(int maxConnections = int.MaxValue) // int.MaxValue treated as infinite { _maxConnections = maxConnections; } /// <summary>Object used to synchronize access to state in the pool.</summary> private object SyncObj => _idleConnections; public ValueTask<HttpConnection> GetConnectionAsync<TState>( Func<TState, CancellationToken, ValueTask<HttpConnection>> createConnection, TState state, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<HttpConnection>(Task.FromCanceled<HttpConnection>(cancellationToken)); } List<CachedConnection> list = _idleConnections; lock (SyncObj) { // Try to return a cached connection. We need to loop in case the connection // we get from the list is unusable. while (list.Count > 0) { CachedConnection cachedConnection = list[list.Count - 1]; HttpConnection conn = cachedConnection._connection; list.RemoveAt(list.Count - 1); if (cachedConnection.IsUsable()) { // We found a valid collection. Return it. if (NetEventSource.IsEnabled) conn.Trace("Found usable connection in pool."); return new ValueTask<HttpConnection>(conn); } // We got a connection, but it was already closed by the server or the // server sent unexpected data or the connection is too old. In any case, // we can't use the connection, so get rid of it and try again. if (NetEventSource.IsEnabled) conn.Trace("Found invalid connection in pool."); conn.Dispose(); } // No valid cached connections, so we need to create a new one. If // there's no limit on the number of connections associated with this // pool, or if we haven't reached such a limit, simply create a new // connection. if (_associatedConnectionCount < _maxConnections) { if (NetEventSource.IsEnabled) Trace("Creating new connection for pool."); IncrementConnectionCountNoLock(); return WaitForCreatedConnectionAsync(createConnection(state, cancellationToken)); } else { // There is a limit, and we've reached it, which means we need to // wait for a connection to be returned to the pool or for a connection // associated with the pool to be dropped before we can create a // new one. Create a waiter object and register it with the pool; it'll // be signaled with the created connection when one is returned or // space is available and the provided creation func has successfully // created the connection to be used. if (NetEventSource.IsEnabled) Trace("Limit reached. Waiting to create new connection."); var waiter = new ConnectionWaiter<TState>(this, createConnection, state, cancellationToken); EnqueueWaiter(waiter); if (cancellationToken.CanBeCanceled) { // If cancellation could be requested, register a callback for it that'll cancel // the waiter and remove the waiter from the queue. Note that this registration needs // to happen under the reentrant lock and after enqueueing the waiter. waiter._cancellationTokenRegistration = cancellationToken.Register(s => { var innerWaiter = (ConnectionWaiter)s; lock (innerWaiter._pool.SyncObj) { // If it's in the list, remove it and cancel it. if (innerWaiter._pool.RemoveWaiterForCancellation(innerWaiter)) { bool canceled = innerWaiter.TrySetCanceled(innerWaiter._cancellationToken); Debug.Assert(canceled); } } }, waiter); } return new ValueTask<HttpConnection>(waiter.Task); } // Note that we don't check for _disposed. We may end up disposing the // created connection when it's returned, but we don't want to block use // of the pool if it's already been disposed, as there's a race condition // between getting a pool and someone disposing of it, and we don't want // to complicate the logic about trying to get a different pool when the // retrieved one has been disposed of. In the future we could alternatively // try returning such connections to whatever pool is currently considered // current for that endpoint, if there is one. } } /// <summary>Enqueues a waiter to the waiters list.</summary> /// <param name="waiter">The waiter to add.</param> private void EnqueueWaiter(ConnectionWaiter waiter) { Debug.Assert(Monitor.IsEntered(SyncObj)); Debug.Assert(waiter != null); Debug.Assert(waiter._next == null); Debug.Assert(waiter._prev == null); waiter._next = _waitersHead; if (_waitersHead != null) { _waitersHead._prev = waiter; } else { Debug.Assert(_waitersTail == null); _waitersTail = waiter; } _waitersHead = waiter; } /// <summary>Dequeues a waiter from the waiters list. The list must not be empty.</summary> /// <returns>The dequeued waiter.</returns> private ConnectionWaiter DequeueWaiter() { Debug.Assert(Monitor.IsEntered(SyncObj)); Debug.Assert(_waitersTail != null); ConnectionWaiter waiter = _waitersTail; _waitersTail = waiter._prev; if (_waitersTail != null) { _waitersTail._next = null; } else { Debug.Assert(_waitersHead == waiter); _waitersHead = null; } waiter._next = null; waiter._prev = null; return waiter; } /// <summary>Removes the specified waiter from the waiters list as part of a cancellation request.</summary> /// <param name="waiter">The waiter to remove.</param> /// <returns>true if the waiter was in the list; otherwise, false.</returns> private bool RemoveWaiterForCancellation(ConnectionWaiter waiter) { Debug.Assert(Monitor.IsEntered(SyncObj)); Debug.Assert(waiter != null); Debug.Assert(waiter._cancellationToken.IsCancellationRequested); bool inList = waiter._next != null || waiter._prev != null || _waitersHead == waiter || _waitersTail == waiter; if (waiter._next != null) waiter._next._prev = waiter._prev; if (waiter._prev != null) waiter._prev._next = waiter._next; if (_waitersHead == waiter && _waitersTail == waiter) { _waitersHead = _waitersTail = null; } else if (_waitersHead == waiter) { _waitersHead = waiter._next; } else if (_waitersTail == waiter) { _waitersTail = waiter._prev; } waiter._next = null; waiter._prev = null; return inList; } /// <summary>Waits for and returns the created connection, decrementing the associated connection count if it fails.</summary> private async ValueTask<HttpConnection> WaitForCreatedConnectionAsync(ValueTask<HttpConnection> creationTask) { try { return await creationTask.ConfigureAwait(false); } catch { DecrementConnectionCount(); throw; } } /// <summary> /// Increments the count of connections associated with the pool. This is invoked /// any time a new connection is created for the pool. /// </summary> public void IncrementConnectionCount() { lock (SyncObj) IncrementConnectionCountNoLock(); } private void IncrementConnectionCountNoLock() { Debug.Assert(Monitor.IsEntered(SyncObj), $"Expected to be holding {nameof(SyncObj)}"); if (NetEventSource.IsEnabled) Trace(null); _usedSinceLastCleanup = true; Debug.Assert( _associatedConnectionCount >= 0 && _associatedConnectionCount < _maxConnections, $"Expected 0 <= {_associatedConnectionCount} < {_maxConnections}"); _associatedConnectionCount++; } /// <summary> /// Decrements the number of connections associated with the pool. /// If there are waiters on the pool due to having reached the maximum, /// this will instead try to transfer the count to one of them. /// </summary> public void DecrementConnectionCount() { if (NetEventSource.IsEnabled) Trace(null); lock (SyncObj) { Debug.Assert(_associatedConnectionCount > 0 && _associatedConnectionCount <= _maxConnections, $"Expected 0 < {_associatedConnectionCount} <= {_maxConnections}"); // Mark the pool as not being stale. _usedSinceLastCleanup = true; if (_waitersHead == null) { // There are no waiters to which the count should logically be transferred, // so simply decrement the count. _associatedConnectionCount--; } else { // There's at least one waiter to which we should try to logically transfer // the associated count. Get the waiter. Debug.Assert(_idleConnections.Count == 0, $"With {_idleConnections} connections, we shouldn't have a waiter."); ConnectionWaiter waiter = DequeueWaiter(); Debug.Assert(waiter != null, "Expected non-null waiter"); Debug.Assert(waiter.Task.Status == TaskStatus.WaitingForActivation, $"Expected {waiter.Task.Status} == {nameof(TaskStatus.WaitingForActivation)}"); waiter._cancellationTokenRegistration.Dispose(); // Having a waiter means there must not be any idle connections, so we need to create // one, and we do so using the logic associated with the waiter. ValueTask<HttpConnection> connectionTask = waiter.CreateConnectionAsync(); if (connectionTask.IsCompletedSuccessfully) { // We synchronously and successfully created a connection (this is rare). // Transfer the connection to the waiter. Since we already have a count // that's inflated due to the connection being disassociated, we don't // need to change the count here. waiter.SetResult(connectionTask.Result); } else { // We initiated a connection creation. When it completes, transfer the result to the waiter. connectionTask.AsTask().ContinueWith((innerConnectionTask, state) => { var innerWaiter = (ConnectionWaiter)state; try { // Get the resulting connection. HttpConnection result = innerConnectionTask.GetAwaiter().GetResult(); // Store the resulting connection into the waiter. As in the synchronous case, // since we already have a count that's inflated due to the connection being // disassociated, we don't need to change the count here. innerWaiter.SetResult(innerConnectionTask.Result); } catch (Exception e) { // The creation operation failed. Store the exception into the waiter. innerWaiter.SetException(e); // At this point, a connection was dropped and we failed to replace it, // which means our connection count still needs to be decremented. innerWaiter._pool.DecrementConnectionCount(); } }, waiter, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } } } /// <summary>Returns the connection to the pool for subsequent reuse.</summary> /// <param name="connection">The connection to return.</param> public void ReturnConnection(HttpConnection connection) { List<CachedConnection> list = _idleConnections; lock (SyncObj) { Debug.Assert(list.Count <= _maxConnections, $"Expected {list.Count} <= {_maxConnections}"); // Mark the pool as still being active. _usedSinceLastCleanup = true; // If there's someone waiting for a connection, simply // transfer this one to them rather than pooling it. if (_waitersTail != null) { ConnectionWaiter waiter = DequeueWaiter(); waiter._cancellationTokenRegistration.Dispose(); if (NetEventSource.IsEnabled) connection.Trace("Transferring connection returned to pool."); waiter.SetResult(connection); return; } // If the pool has been disposed of, dispose the connection being returned, // as the pool is being deactivated. We do this after the above in order to // use pooled connections to satisfy any requests that pended before the // the pool was disposed of. if (_disposed) { if (NetEventSource.IsEnabled) connection.Trace("Disposing connection returned to disposed pool."); connection.Dispose(); return; } // Pool the connection by adding it to the list. list.Add(new CachedConnection(connection)); if (NetEventSource.IsEnabled) connection.Trace("Stored connection in pool."); } } /// <summary>Disposes the </summary> public void Dispose() { List<CachedConnection> list = _idleConnections; lock (SyncObj) { if (!_disposed) { if (NetEventSource.IsEnabled) Trace("Disposing pool."); _disposed = true; list.ForEach(c => c._connection.Dispose()); list.Clear(); } Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0"); } } /// <summary> /// Removes any unusable connections from the pool, and if the pool /// is then empty and stale, disposes of it. /// </summary> /// <returns> /// true if the pool disposes of itself; otherwise, false. /// </returns> public bool CleanCacheAndDisposeIfUnused() { List<CachedConnection> list = _idleConnections; List<HttpConnection> toDispose = null; bool tookLock = false; try { if (NetEventSource.IsEnabled) Trace("Cleaning pool."); Monitor.Enter(SyncObj, ref tookLock); // Get the current time. This is compared against each connection's last returned // time to determine whether a connection is too old and should be closed. DateTimeOffset now = DateTimeOffset.Now; // Find the first item which needs to be removed. int freeIndex = 0; while (freeIndex < list.Count && list[freeIndex].IsUsable(now)) { freeIndex++; } // If freeIndex == list.Count, nothing needs to be removed. // But if it's < list.Count, at least one connection needs to be purged. if (freeIndex < list.Count) { // We know the connection at freeIndex is unusable, so dispose of it. toDispose = new List<HttpConnection> { list[freeIndex]._connection }; // Find the first item after the one to be removed that should be kept. int current = freeIndex + 1; while (current < list.Count) { // Look for the first item to be kept. Along the way, any // that shouldn't be kept are disposed of. while (current < list.Count && !list[current].IsUsable(now)) { toDispose.Add(list[current]._connection); current++; } // If we found something to keep, copy it down to the known free slot. if (current < list.Count) { // copy item to the free slot list[freeIndex++] = list[current++]; } // Keep going until there are no more good items. } // At this point, good connections have been moved below freeIndex, and garbage connections have // been added to the dispose list, so clear the end of the list past freeIndex. list.RemoveRange(freeIndex, list.Count - freeIndex); // If there are now no connections associated with this pool, we can dispose of it. We // avoid aggressively cleaning up pools that have recently been used but currently aren't; // if a pool was used since the last time we cleaned up, give it another chance. New pools // start out saying they've recently been used, to give them a bit of breathing room and time // for the initial collection to be added to it. if (_associatedConnectionCount == 0 && !_usedSinceLastCleanup) { Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0"); _disposed = true; return true; // Pool is disposed of. It should be removed. } } // Reset the cleanup flag. Any pools that are empty and not used since the last cleanup // will be purged next time around. _usedSinceLastCleanup = false; } finally { if (tookLock) { Monitor.Exit(SyncObj); } // Dispose the stale connections outside the pool lock. toDispose?.ForEach(c => c.Dispose()); } // Pool is active. Should not be removed. return false; } public override string ToString() => $"{nameof(HttpConnectionPool)}(Connections:{_associatedConnectionCount})"; // Description for diagnostic purposes private void Trace(string message, [CallerMemberName] string memberName = null) => NetEventSource.Log.HandlerMessage( GetHashCode(), // pool ID 0, // connection ID 0, // request ID memberName, // method name ToString() + ":" + message); // message /// <summary>A cached idle connection and metadata about it.</summary> [StructLayout(LayoutKind.Auto)] private readonly struct CachedConnection : IEquatable<CachedConnection> { /// <summary>The cached connection.</summary> internal readonly HttpConnection _connection; /// <summary>The last time the connection was used.</summary> internal readonly DateTimeOffset _returnedTime; /// <summary>Initializes the cached connection and its associated metadata.</summary> /// <param name="connection">The connection.</param> public CachedConnection(HttpConnection connection) { Debug.Assert(connection != null); _connection = connection; _returnedTime = DateTimeOffset.UtcNow; } /// <summary>Gets whether the connection is currently usable.</summary> /// <returns>true if we believe the connection can be reused; otherwise, false. See comments on other overload.</returns> public bool IsUsable() => !_connection.ReadAheadCompleted; /// <summary>Gets whether the connection is currently usable, factoring in expiration time.</summary> /// <param name="now">The current time. Passed in to amortize the cost of calling DateTime.UtcNow.</param> /// <returns> /// true if we believe the connection can be reused; otherwise, false. There is an inherent race condition here, /// in that the server could terminate the connection or otherwise make it unusable immediately after we check it, /// but there's not much difference between that and starting to use the connection and then having the server /// terminate it, which would be considered a failure, so this race condition is largely benign and inherent to /// the nature of connection pooling. /// </returns> public bool IsUsable(DateTimeOffset now) => now - _returnedTime <= TimeSpan.FromMilliseconds(MaxIdleTimeMilliseconds) && IsUsable(); public bool Equals(CachedConnection other) => ReferenceEquals(other._connection, _connection); public override bool Equals(object obj) => obj is CachedConnection && Equals((CachedConnection)obj); public override int GetHashCode() => _connection?.GetHashCode() ?? 0; } /// <summary>Provides a waiter object that supports a generic function and state type for creating connections.</summary> private sealed class ConnectionWaiter<TState> : ConnectionWaiter { /// <summary>The function to invoke if/when <see cref="CreateConnectionAsync"/> is invoked.</summary> private readonly Func<TState, CancellationToken, ValueTask<HttpConnection>> _createConnectionAsync; /// <summary>The state to pass to <paramref name="func"/> when it's invoked.</summary> private readonly TState _state; /// <summary>Initializes the waiter.</summary> /// <param name="func">The function to invoke if/when <see cref="CreateConnectionAsync"/> is invoked.</param> /// <param name="state">The state to pass to <paramref name="func"/> when it's invoked.</param> public ConnectionWaiter(HttpConnectionPool pool, Func<TState, CancellationToken, ValueTask<HttpConnection>> func, TState state, CancellationToken cancellationToken) : base(pool, cancellationToken) { _createConnectionAsync = func; _state = state; } /// <summary>Creates a connection by invoking <see cref="_createConnectionAsync"/> with <see cref="_state"/>.</summary> public override ValueTask<HttpConnection> CreateConnectionAsync() { try { return _createConnectionAsync(_state, _cancellationToken); } catch (Exception e) { return new ValueTask<HttpConnection>(Threading.Tasks.Task.FromException<HttpConnection>(e)); } } } /// <summary> /// Provides a waiter object that's used when we've reached the limit on connections /// associated with the pool. When a connection is available or created, it's stored /// into the waiter as a result, and if no connection is available from the pool, /// this waiter's logic is used to create the connection. /// </summary> /// <remarks> /// Implemented as a non-generic base type with a generic derived type to support /// passing in arbitrary funcs and associated state while minimizing allocations. /// The <see cref="CreateConnectionAsync"/> method will be implemented on the derived /// type that is able to work with the supplied state generically. /// </remarks> private abstract class ConnectionWaiter : TaskCompletionSource<HttpConnection> { /// <summary>The pool with which this waiter is associated.</summary> internal readonly HttpConnectionPool _pool; /// <summary>Cancellation token for the waiter.</summary> internal readonly CancellationToken _cancellationToken; /// <summary>Registration that removes the waiter from the registration list.</summary> internal CancellationTokenRegistration _cancellationTokenRegistration; /// <summary>Next waiter in the list.</summary> internal ConnectionWaiter _next; /// <summary>Previous waiter in the list.</summary> internal ConnectionWaiter _prev; /// <summary>Initializes the waiter.</summary> public ConnectionWaiter(HttpConnectionPool pool, CancellationToken cancellationToken) : base(TaskCreationOptions.RunContinuationsAsynchronously) { Debug.Assert(pool != null, "Expected non-null pool"); _pool = pool; _cancellationToken = cancellationToken; } /// <summary>Creates a connection.</summary> public abstract ValueTask<HttpConnection> CreateConnectionAsync(); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Linq; using ModestTree; namespace Zenject { public static class TypeAnalyzer { static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>(); public static ZenjectTypeInfo GetInfo<T>() { return GetInfo(typeof(T)); } public static ZenjectTypeInfo GetInfo(Type type) { #if UNITY_EDITOR using (ProfileBlock.Start("Zenject Reflection")) #endif { Assert.That(!type.IsAbstract(), "Tried to analyze abstract type '{0}'. This is not currently allowed.", type); ZenjectTypeInfo info; #if ZEN_MULTITHREADING lock (_typeInfo) #endif { if (!_typeInfo.TryGetValue(type, out info)) { info = CreateTypeInfo(type); _typeInfo.Add(type, info); } } return info; } } static ZenjectTypeInfo CreateTypeInfo(Type type) { var constructor = GetInjectConstructor(type); return new ZenjectTypeInfo( type, GetPostInjectMethods(type), constructor, GetFieldInjectables(type).ToList(), GetPropertyInjectables(type).ToList(), GetConstructorInjectables(type, constructor).ToList()); } static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo) { if (constructorInfo == null) { return Enumerable.Empty<InjectableInfo>(); } return constructorInfo.GetParameters().Select( paramInfo => CreateInjectableInfoForParam(parentType, paramInfo)); } static InjectableInfo CreateInjectableInfoForParam( Type parentType, ParameterInfo paramInfo) { var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList(); Assert.That(injectAttributes.Count <= 1, "Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType); var injectAttr = injectAttributes.SingleOrDefault(); object identifier = null; bool isOptional = false; InjectSources sourceType = InjectSources.Any; if (injectAttr != null) { identifier = injectAttr.Id; isOptional = injectAttr.Optional; sourceType = injectAttr.Source; } bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault; return new InjectableInfo( isOptionalWithADefaultValue || isOptional, identifier, paramInfo.Name, paramInfo.ParameterType, parentType, null, isOptionalWithADefaultValue ? paramInfo.DefaultValue : null, sourceType); } static List<PostInjectableInfo> GetPostInjectMethods(Type type) { // Note that unlike with fields and properties we use GetCustomAttributes // This is so that we can ignore inherited attributes, which is necessary // otherwise a base class method marked with [Inject] would cause all overridden // derived methods to be added as well var methods = type.GetAllInstanceMethods() .Where(x => x.GetCustomAttributes(typeof(InjectAttribute), false).Any()).ToList(); var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList(); // Order by base classes first // This is how constructors work so it makes more sense var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType)); var postInjectInfos = new List<PostInjectableInfo>(); foreach (var methodInfo in values) { var paramsInfo = methodInfo.GetParameters(); var injectAttr = methodInfo.AllAttributes<InjectAttribute>().Single(); Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any, "Parameters of InjectAttribute do not apply to constructors and methods"); postInjectInfos.Add( new PostInjectableInfo( methodInfo, paramsInfo.Select(paramInfo => CreateInjectableInfoForParam(type, paramInfo)).ToList())); } return postInjectInfos; } static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type) { var propInfos = type.GetAllInstanceProperties() .Where(x => x.HasAttribute(typeof(InjectAttributeBase))); foreach (var propInfo in propInfos) { yield return CreateForMember(propInfo, type); } } static IEnumerable<InjectableInfo> GetFieldInjectables(Type type) { var fieldInfos = type.GetAllInstanceFields() .Where(x => x.HasAttribute(typeof(InjectAttributeBase))); foreach (var fieldInfo in fieldInfos) { yield return CreateForMember(fieldInfo, type); } } static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType) { var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList(); Assert.That(injectAttributes.Count <= 1, "Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType); var injectAttr = injectAttributes.SingleOrDefault(); object identifier = null; bool isOptional = false; InjectSources sourceType = InjectSources.Any; if (injectAttr != null) { identifier = injectAttr.Id; isOptional = injectAttr.Optional; sourceType = injectAttr.Source; } Type memberType; Action<object, object> setter; if (memInfo is FieldInfo) { var fieldInfo = (FieldInfo)memInfo; setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value)); memberType = fieldInfo.FieldType; } else { Assert.That(memInfo is PropertyInfo); var propInfo = (PropertyInfo)memInfo; setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null)); memberType = propInfo.PropertyType; } return new InjectableInfo( isOptional, identifier, memInfo.Name, memberType, parentType, setter, null, sourceType); } static ConstructorInfo GetInjectConstructor(Type parentType) { var constructors = parentType.Constructors(); #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR // WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy)) // So just ignore that constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray(); #endif if (constructors.IsEmpty()) { return null; } if (constructors.HasMoreThan(1)) { var explicitConstructor = (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault(); if (explicitConstructor != null) { return explicitConstructor; } // If there is only one public constructor then use that // This makes decent sense but is also necessary on WSA sometimes since the WSA generated // constructor can sometimes be private with zero parameters var singlePublicConstructor = constructors.Where(x => !x.IsPrivate).OnlyOrDefault(); if (singlePublicConstructor != null) { return singlePublicConstructor; } return null; } return constructors[0]; } #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR static bool IsWp8GeneratedConstructor(ConstructorInfo c) { ParameterInfo[] args = c.GetParameters(); if (args.Length == 1) { return args[0].ParameterType == typeof(UIntPtr) && (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy"); } if (args.Length == 2) { return args[0].ParameterType == typeof(UIntPtr) && args[1].ParameterType == typeof(Int64*) && (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy") && (string.IsNullOrEmpty(args[1].Name) || args[1].Name == "dummy"); } return false; } #endif } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.ComponentModel; using Moq.Language.Flow; namespace Moq.Language { partial interface IReturns<TMock, TResult> { /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2) => arg1 + arg2); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2>(Func<T1, T2, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3) => arg1 + arg2 + arg3); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3>(Func<T1, T2, T3, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4) => arg1 + arg2 + arg3 + arg4); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4>(Func<T1, T2, T3, T4, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5) => arg1 + arg2 + arg3 + arg4 + arg5); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7>(Func<T1, T2, T3, T4, T5, T6, T7, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8>(Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13, string arg14) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <typeparam name="T15">The type of the fifteenth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13, string arg14, string arg15) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> valueFunction); /// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <typeparam name="T3">The type of the third argument of the invoked method.</typeparam> /// <typeparam name="T4">The type of the fourth argument of the invoked method.</typeparam> /// <typeparam name="T5">The type of the fifth argument of the invoked method.</typeparam> /// <typeparam name="T6">The type of the sixth argument of the invoked method.</typeparam> /// <typeparam name="T7">The type of the seventh argument of the invoked method.</typeparam> /// <typeparam name="T8">The type of the eighth argument of the invoked method.</typeparam> /// <typeparam name="T9">The type of the ninth argument of the invoked method.</typeparam> /// <typeparam name="T10">The type of the tenth argument of the invoked method.</typeparam> /// <typeparam name="T11">The type of the eleventh argument of the invoked method.</typeparam> /// <typeparam name="T12">The type of the twelfth argument of the invoked method.</typeparam> /// <typeparam name="T13">The type of the thirteenth argument of the invoked method.</typeparam> /// <typeparam name="T14">The type of the fourteenth argument of the invoked method.</typeparam> /// <typeparam name="T15">The type of the fifteenth argument of the invoked method.</typeparam> /// <typeparam name="T16">The type of the sixteenth argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;(), /// It.IsAny&lt;int&gt;())) /// .Returns((string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8, string arg9, string arg10, string arg11, string arg12, string arg13, string arg14, string arg15, string arg16) => arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15 + arg16); /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> valueFunction); } }
#region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Architecture; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; using BoundarySegment = Autodesk.Revit.DB.BoundarySegment; #endregion namespace SvgExport { [Transaction( TransactionMode.ReadOnly )] public class Command : IExternalCommand { const int _target_square_size = 100; /// <summary> /// Allow selection of room elements only. /// </summary> class RoomSelectionFilter : ISelectionFilter { public bool AllowElement( Element e ) { return e is Room; } public bool AllowReference( Reference r, XYZ p ) { return true; } } /// <summary> /// Get a room from the given document. /// If there is only one single room in the entire /// model, return that with no further ado. /// Otherwise, if any elements have been pre-selected, /// pick the first room encountered among them. /// Otherwise, prompt the user to interactively /// select a room or a room tag. /// </summary> Result GetRoom( UIDocument uidoc, out Room room ) { room = null; Document doc = uidoc.Document; // Get all rooms in the model. FilteredElementCollector rooms = new FilteredElementCollector( doc ) .OfClass( typeof( SpatialElement ) ); if( 1 == rooms.Count() && rooms.FirstElement() is Room ) { // If there is only one spatial element // and that is a room, pick that. room = rooms.FirstElement() as Room; } else { Selection sel = uidoc.Selection; // Check the preselacted elements. ICollection<ElementId> ids = sel.GetElementIds(); foreach( ElementId id in ids ) { Element e = doc.GetElement( id ); if( e is Room ) { room = e as Room; break; } if( e is RoomTag ) { room = ( e as RoomTag ).Room; break; } } if( null == room ) { // Prompt for interactive selection. try { Reference r = sel.PickObject( ObjectType.Element, new RoomSelectionFilter(), "Please select pick a room" ); room = doc.GetElement( r.ElementId ) as Room; } catch( Autodesk.Revit.Exceptions .OperationCanceledException ) { return Result.Cancelled; } } } return Result.Succeeded; } /// <summary> /// Return an SVG representation of the /// given XYZ point scaled, offset and /// Y flipped to the target square size. /// </summary> string GetSvgPointFrom( XYZ p, XYZ pmid, double scale ) { p -= pmid; p *= scale; int x = (int) ( p.X + 0.5 ); int y = (int) ( p.Y + 0.5 ); // The Revit Y coordinate points upwards, // the SVG one down, so flip the Y coord. y = -y; x += _target_square_size / 2; y += _target_square_size / 2; return x.ToString() + " " + y.ToString(); } /// <summary> /// Generate and return an SVG path definition to /// represent the given room boundary loop, scaled /// from the given bounding box to fit into a /// 100 x 100 canvas. Actually, the size is /// determined by _target_square_size. /// </summary> string GetSvgPathFrom( BoundingBoxXYZ bb, IList<BoundarySegment> loop ) { // Determine scaling and offsets to transform // from bounding box to (0,0)-(100,100). XYZ pmin = bb.Min; XYZ pmax = bb.Max; XYZ vsize = pmax - pmin; XYZ pmid = pmin + 0.5 * vsize; double size = Math.Max( vsize.X, vsize.Y ); double scale = _target_square_size / size; StringBuilder s = new StringBuilder(); int nSegments = loop.Count; XYZ p0 = null; // loop start point XYZ p; // segment start point XYZ q = null; // segment end point foreach( BoundarySegment seg in loop ) { Curve curve = seg.GetCurve(); // Todo: handle non-linear curve. // Especially: if two long lines have a // short arc in between them, skip the arc // and extend both lines. p = curve.GetEndPoint( 0 ); Debug.Assert( null == q || q.IsAlmostEqualTo( p ), "expected last endpoint to equal current start point" ); q = curve.GetEndPoint( 1 ); if( null == p0 ) { p0 = p; // save loop start point s.Append( "M" + GetSvgPointFrom( p, pmid, scale ) ); } s.Append( "L" + GetSvgPointFrom( q, pmid, scale ) ); } s.Append( "Z" ); Debug.Assert( q.IsAlmostEqualTo( p0 ), "expected last endpoint to equal loop start point" ); return s.ToString(); } /// <summary> /// Invoke the SVG node.js web server. /// Use a local or global base URL and append /// the SVG path definition as a query string. /// Compare this with the JavaScript version used in /// http://the3dwebcoder.typepad.com/blog/2015/04/displaying-2d-graphics-via-a-node-server.html /// </summary> void DisplaySvg( string path_data ) { var local = false; var base_url = local ? "http://127.0.0.1:5000" : "https://shielded-hamlet-1585.herokuapp.com"; var d = path_data.Replace( ' ', '+' ); var query_string = "d=" + d; string url = base_url + '?' + query_string; System.Diagnostics.Process.Start( url ); } public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Room room = null; Result rc = GetRoom( uidoc, out room ); SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions(); opt.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Center; // loops closed //SpatialElementBoundaryLocation.Finish; // loops not closed IList<IList<BoundarySegment>> loops = room.GetBoundarySegments( opt ); int nLoops = loops.Count; BoundingBoxXYZ bb = room.get_BoundingBox( null ); string path_data = GetSvgPathFrom( bb, loops[0] ); DisplaySvg( path_data ); return Result.Succeeded; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Data/DownloadUrlEntry.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Data { /// <summary>Holder for reflection information generated from POGOProtos/Data/DownloadUrlEntry.proto</summary> public static partial class DownloadUrlEntryReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Data/DownloadUrlEntry.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DownloadUrlEntryReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiZQT0dPUHJvdG9zL0RhdGEvRG93bmxvYWRVcmxFbnRyeS5wcm90bxIPUE9H", "T1Byb3Rvcy5EYXRhIlEKEERvd25sb2FkVXJsRW50cnkSEAoIYXNzZXRfaWQY", "ASABKAkSCwoDdXJsGAIgASgJEgwKBHNpemUYAyABKAUSEAoIY2hlY2tzdW0Y", "BCABKAdiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.DownloadUrlEntry), global::POGOProtos.Data.DownloadUrlEntry.Parser, new[]{ "AssetId", "Url", "Size", "Checksum" }, null, null, null) })); } #endregion } #region Messages public sealed partial class DownloadUrlEntry : pb::IMessage<DownloadUrlEntry> { private static readonly pb::MessageParser<DownloadUrlEntry> _parser = new pb::MessageParser<DownloadUrlEntry>(() => new DownloadUrlEntry()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<DownloadUrlEntry> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Data.DownloadUrlEntryReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DownloadUrlEntry() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DownloadUrlEntry(DownloadUrlEntry other) : this() { assetId_ = other.assetId_; url_ = other.url_; size_ = other.size_; checksum_ = other.checksum_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public DownloadUrlEntry Clone() { return new DownloadUrlEntry(this); } /// <summary>Field number for the "asset_id" field.</summary> public const int AssetIdFieldNumber = 1; private string assetId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AssetId { get { return assetId_; } set { assetId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "url" field.</summary> public const int UrlFieldNumber = 2; private string url_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Url { get { return url_; } set { url_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "size" field.</summary> public const int SizeFieldNumber = 3; private int size_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Size { get { return size_; } set { size_ = value; } } /// <summary>Field number for the "checksum" field.</summary> public const int ChecksumFieldNumber = 4; private uint checksum_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint Checksum { get { return checksum_; } set { checksum_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as DownloadUrlEntry); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(DownloadUrlEntry other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (AssetId != other.AssetId) return false; if (Url != other.Url) return false; if (Size != other.Size) return false; if (Checksum != other.Checksum) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (AssetId.Length != 0) hash ^= AssetId.GetHashCode(); if (Url.Length != 0) hash ^= Url.GetHashCode(); if (Size != 0) hash ^= Size.GetHashCode(); if (Checksum != 0) hash ^= Checksum.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (AssetId.Length != 0) { output.WriteRawTag(10); output.WriteString(AssetId); } if (Url.Length != 0) { output.WriteRawTag(18); output.WriteString(Url); } if (Size != 0) { output.WriteRawTag(24); output.WriteInt32(Size); } if (Checksum != 0) { output.WriteRawTag(37); output.WriteFixed32(Checksum); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (AssetId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AssetId); } if (Url.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Url); } if (Size != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Size); } if (Checksum != 0) { size += 1 + 4; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(DownloadUrlEntry other) { if (other == null) { return; } if (other.AssetId.Length != 0) { AssetId = other.AssetId; } if (other.Url.Length != 0) { Url = other.Url; } if (other.Size != 0) { Size = other.Size; } if (other.Checksum != 0) { Checksum = other.Checksum; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { AssetId = input.ReadString(); break; } case 18: { Url = input.ReadString(); break; } case 24: { Size = input.ReadInt32(); break; } case 37: { Checksum = input.ReadFixed32(); break; } } } } } #endregion } #endregion Designer generated code
// 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; /// <summary> /// System.Array.LastIndexOf(System.Array,System.Object,System.Int32,System.Int32) /// </summary> public class ArrayLastIndexOf1 { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1:Test the array of many elements which have the same value "); try { int length = TestLibrary.Generator.GetInt16(-55); int value = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; for (int i = 0; i < length; i++) { i1[i] = value; } for (int i = length - 1; i >= 0; i--) // travel the array { if (Array.LastIndexOf(i1, value, i, i + 1) != i) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Test the empty string "); try { int length = TestLibrary.Generator.GetByte(-55); string[] s1 = new string[length]; for (int i = 0; i < length; i++) { s1[i] = ""; } for (int i = length - 1; i >= 0; i--) // travel the array { if (Array.LastIndexOf(s1, "", i, i + 1) != i) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Test the null element of the string array "); try { int length; string value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); int index1, index2; do { length = TestLibrary.Generator.GetInt16(-55); } while (10 > length); do { index1 = this.GetInt32(0, length); index2 = this.GetInt32(0, length); } while (index1 == index2); string[] s1 = new string[length]; for (int i = 0; i < length; i++) { if (i != index1 && (i != index2)) { s1[i] = value; } else { s1[i] = null; } } if (index1 < index2) { if (Array.LastIndexOf(s1, null, length - 1, length) != index2) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } else { if (Array.LastIndexOf(s1, null, length - 1, length) != index1) { TestLibrary.TestFramework.LogError("006", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Find out no result "); try { string[] s1 = new string[5]{"Jack", "Mary", "Mike", "Peter", "Joan"}; if (Array.LastIndexOf(s1, "Jaon", 4, 5) != -1) { TestLibrary.TestFramework.LogError("008", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest5: Find the second last value because of the startIndex "); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Mary", "Joan"}; if (Array.LastIndexOf(s1, "Mary", 3, 4) != 1) { TestLibrary.TestFramework.LogError("010", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest6: Find out no value because of the count argument "); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Mary", "Joan"}; if (Array.LastIndexOf(s1, "Mike", 5, 3) != -1) { TestLibrary.TestFramework.LogError("012", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Find out no value because of different type "); try { int[] i1 = new int[5] { 1, 2, 34, 67, 10 }; Int16 value = 34; int result = Array.LastIndexOf(i1, (object)value, 4, 5); if (result != -1) { TestLibrary.TestFramework.LogError("014", "The result is not the value as expected: Expected(-1) Actual("+result+")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("015", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is a null reference "); try { string[] s1 = null; int i1 = Array.LastIndexOf(s1, "", 1, 0); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: Set the negative startIndex argument"); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Mary", "Joan"}; int i1 = Array.LastIndexOf(s1, "", -1, 3); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: Set the startIndex greater than the max index of the array"); try { int[] i1 = new int[6] { 2, 34, 56, 87, 23, 209 }; int i2 = Array.LastIndexOf(i1, 56, 6, 3); TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: Count argument is less than zero"); try { int[] i1 = new int[6] { 2, 34, 56, 87, 23, 209 }; int i2 = Array.LastIndexOf(i1, 56, 3, -3); TestLibrary.TestFramework.LogError("107", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: Count argument do not specify a valid section in array"); try { int[] i1 = new int[6] { 2, 34, 56, 87, 23, 209 }; int i2 = Array.LastIndexOf(i1, 56, 3, 5); TestLibrary.TestFramework.LogError("109", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: The array is not a one dimension array "); try { int[,] i1 = new int[2, 3] { { 2, 3, 5 }, { 34, 56, 77 } }; int i2 = Array.LastIndexOf(i1, 3, 1, 0); TestLibrary.TestFramework.LogError("111", "The RankException was not thrown as expected"); retVal = false; } catch (RankException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArrayLastIndexOf1 test = new ArrayLastIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ArrayLastIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public Int32 GetInt32(int min, int max) { return min + TestLibrary.Generator.GetInt32(-55) % (max - min); } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SlimManualResetEvent.cs // // // An manual-reset event that mixes a little spinning with a true Win32 event. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; namespace System.Threading { // ManualResetEventSlim wraps a manual-reset event internally with a little bit of // spinning. When an event will be set imminently, it is often advantageous to avoid // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to // a brief amount of spinning that should, on the average, make using the slim event // cheaper than using Win32 events directly. This can be reset manually, much like // a Win32 manual-reset would be. // // Notes: // We lazily allocate the Win32 event internally. Therefore, the caller should // always call Dispose to clean it up, just in case. This API is a no-op of the // event wasn't allocated, but if it was, ensures that the event goes away // eagerly, instead of waiting for finalization. /// <summary> /// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>. /// </summary> /// <remarks> /// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [DebuggerDisplay("Set = {IsSet}")] public class ManualResetEventSlim : IDisposable { // These are the default spin counts we use on single-proc and MP machines. private const int DEFAULT_SPIN_SP = 1; private volatile object m_lock; // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting. // -- State -- // //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below. //1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 private const int SignalledState_ShiftCount = 31; //1-bit for disposed state private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000 //11-bits for m_spinCount private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000 private const int SpinCountState_ShiftCount = 19; private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047 //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 private const int NumWaitersState_ShiftCount = 0; private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1 // ----------- // #if DEBUG private static int s_nextId; // The next id that will be given out. private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only. private long m_lastSetTime; private long m_lastResetTime; #endif /// <summary> /// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see /// cref="ManualResetEventSlim"/>. /// </summary> /// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see /// cref="ManualResetEventSlim"/>.</value> /// <remarks> /// Accessing this property forces initialization of an underlying event object if one hasn't /// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>, /// the public Wait methods should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); if (m_eventObj == null) { // Lazily initialize the event object if needed. LazyInitializeEvent(); } return m_eventObj; } } /// <summary> /// Gets whether the event is set. /// </summary> /// <value>true if the event has is set; otherwise, false.</value> public bool IsSet { get { return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); } private set { UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); } } /// <summary> /// Gets the number of spin waits that will be occur before falling back to a true wait. /// </summary> public int SpinCount { get { return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); } private set { Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); // Don't worry about thread safety because it's set one time from the constructor m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); } } /// <summary> /// How many threads are waiting. /// </summary> private int Waiters { get { return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); } set { //setting to <0 would indicate an internal flaw, hence Assert is appropriate. Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } } //----------------------------------------------------------------------------------- // Constructs a new event, optionally specifying the initial state and spin count. // The defaults are that the event is unsignaled and some reasonable default spin. // /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with an initial state of nonsignaled. /// </summary> public ManualResetEventSlim() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a boolean value indicating whether to set the initial state to signaled. /// </summary> /// <param name="initialState">true to set the initial state signaled; false to set the initial state /// to nonsignaled.</param> public ManualResetEventSlim(bool initialState) { // Specify the defualt spin count, and use default spin if we're // on a multi-processor machine. Otherwise, we won't. Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait); } /// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim"/> /// class with a Boolean value indicating whether to set the initial state to signaled and a specified /// spin count. /// </summary> /// <param name="initialState">true to set the initial state to signaled; false to set the initial state /// to nonsignaled.</param> /// <param name="spinCount">The number of spin waits that will occur before falling back to a true /// wait.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than /// 0 or greater than the maximum allowed value.</exception> public ManualResetEventSlim(bool initialState, int spinCount) { if (spinCount < 0) { throw new ArgumentOutOfRangeException(nameof(spinCount)); } if (spinCount > SpinCountState_MaxValue) { throw new ArgumentOutOfRangeException( nameof(spinCount), String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. Initialize(initialState, spinCount); } /// <summary> /// Initializes the internal state of the event. /// </summary> /// <param name="initialState">Whether the event is set initially or not.</param> /// <param name="spinCount">The spin count that decides when the event will block.</param> private void Initialize(bool initialState, int spinCount) { m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; //the spinCount argument has been validated by the ctors. //but we now sanity check our predefined constants. Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; } /// <summary> /// Helper to ensure the lock object is created before first use. /// </summary> private void EnsureLockObjectCreated() { if (m_lock != null) return; object newObj = new object(); Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. } /// <summary> /// This method lazily initializes the event object. It uses CAS to guarantee that /// many threads racing to call this at once don't result in more than one event /// being stored and used. The event will be signaled or unsignaled depending on /// the state of the thin-event itself, with synchronization taken into account. /// </summary> /// <returns>True if a new event was created and stored, false otherwise.</returns> private bool LazyInitializeEvent() { bool preInitializeIsSet = IsSet; ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); // We have to CAS this in case we are racing with another thread. We must // guarantee only one event is actually stored in this field. if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) { // Someone else set the value due to a race condition. Destroy the garbage event. newEventObj.Close(); return false; } else { // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from // the CAS above (in addition to m_state being volatile) prevents this read // from moving earlier and being collapsed with our original one. bool currentIsSet = IsSet; if (currentIsSet != preInitializeIsSet) { Debug.Assert(currentIsSet, "The only safe concurrent transition is from unset->set: detected set->unset."); // We saw it as unsignaled, but it has since become set. lock (newEventObj) { // If our event hasn't already been disposed of, we must set it. if (m_eventObj == newEventObj) { newEventObj.Set(); } } } return true; } } /// <summary> /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to /// proceed. /// </summary> public void Set() { Set(false); } /// <summary> /// Private helper to actually perform the Set. /// </summary> /// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param> /// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception> private void Set(bool duringCancellation) { // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj // This would be a legal movement according to the .NET memory model. // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. IsSet = true; // If there are waiting threads, we need to pulse them. if (Waiters > 0) { Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. lock (m_lock) { Monitor.PulseAll(m_lock); } } ManualResetEvent eventObj = m_eventObj; //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic if (eventObj != null && !duringCancellation) { // We must surround this call to Set in a lock. The reason is fairly subtle. // Sometimes a thread will issue a Wait and wake up after we have set m_state, // but before we have gotten around to setting m_eventObj (just below). That's // because Wait first checks m_state and will only access the event if absolutely // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is // quite common, and we must support it. If the waiter woke up and disposed of // the event object before the setter has finished, however, we would try to set a // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to // protect access to the event object when setting and disposing of it. We also // double-check that the event has not become null in the meantime when in the lock. lock (eventObj) { if (m_eventObj != null) { // If somebody is waiting, we must set the event. m_eventObj.Set(); } } } #if DEBUG m_lastSetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Sets the state of the event to nonsignaled, which causes threads to block. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Reset() { ThrowIfDisposed(); // If there's an event, reset it. if (m_eventObj != null) { m_eventObj.Reset(); } // There is a race condition here. If another thread Sets the event, we will get into a state // where m_state will be unsignaled, yet the Win32 event object will have been signaled. // This could cause waiting threads to wake up even though the event is in an // unsignaled state. This is fine -- those that are calling Reset concurrently are // responsible for doing "the right thing" -- e.g. rechecking the condition and // resetting the event manually. // And finally set our state back to unsignaled. IsSet = false; #if DEBUG m_lastResetTime = DateTime.UtcNow.Ticks; #endif } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal, /// while observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was /// canceled.</exception> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds /// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The maximum number of waiters has been exceeded. /// </exception> /// <exception cref="T:System.Threading.OperationCanceledException"><paramref /// name="cancellationToken"/> was canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); // an early convenience check if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } if (!IsSet) { if (millisecondsTimeout == 0) { // For 0-timeouts, we just return immediately. return false; } // We spin briefly before falling back to allocating and/or waiting on a true event. uint startTime = 0; bool bNeedTimeoutAdjustment = false; int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary. if (millisecondsTimeout != Timeout.Infinite) { // We will account for time spent spinning, so that we can decrement it from our // timeout. In most cases the time spent in this section will be negligible. But // we can't discount the possibility of our thread being switched out for a lengthy // period of time. The timeout adjustments only take effect when and if we actually // decide to block in the kernel below. startTime = TimeoutHelper.GetTime(); bNeedTimeoutAdjustment = true; } // Spin int spinCount = SpinCount; var spinner = new SpinWait(); while (spinner.Count < spinCount) { spinner.SpinOnce(SpinWait.Sleep1ThresholdForSpinBeforeWait); if (IsSet) { return true; } if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count cancellationToken.ThrowIfCancellationRequested(); } // Now enter the lock and wait. EnsureLockObjectCreated(); // We must register and deregister the token outside of the lock, to avoid deadlocks. using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this)) { lock (m_lock) { // Loop to cope with spurious wakeups from other waits being canceled while (!IsSet) { // If our token was canceled, we must throw and exit. cancellationToken.ThrowIfCancellationRequested(); //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) if (bNeedTimeoutAdjustment) { realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (realMillisecondsTimeout <= 0) return false; } // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, // so after updating waiters, we must check IsSet again. // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange // operation which provides a full memory barrier. // If we see IsSet=false, then we are guaranteed that Set() will see that we are // waiting and will pulse the monitor correctly. Waiters = Waiters + 1; if (IsSet) //This check must occur after updating Waiters. { Waiters--; //revert the increment. return true; } // Now finally perform the wait. try { // ** the actual wait ** if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) return false; //return immediately if the timeout has expired. } finally { // Clean up: we're done waiting. Waiters = Waiters - 1; } // Now just loop back around, and the right thing will happen. Either: // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) // or 2. the wait was successful. (the loop will break) } } } } // automatically disposes (and deregisters) the callback return true; //done. The wait was satisfied. } /// <summary> /// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if ((m_combinedState & Dispose_BitMask) != 0) return; // already disposed m_combinedState |= Dispose_BitMask; //set the dispose bit if (disposing) { // We will dispose of the event object. We do this under a lock to protect // against the race condition outlined in the Set method above. ManualResetEvent eventObj = m_eventObj; if (eventObj != null) { lock (eventObj) { eventObj.Close(); m_eventObj = null; } } } } /// <summary> /// Throw ObjectDisposedException if the MRES is disposed /// </summary> private void ThrowIfDisposed() { if ((m_combinedState & Dispose_BitMask) != 0) throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed); } /// <summary> /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// </summary> private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback); private static void CancellationTokenCallback(object obj) { ManualResetEventSlim mre = obj as ManualResetEventSlim; Debug.Assert(mre != null, "Expected a ManualResetEventSlim"); Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. lock (mre.m_lock) { Monitor.PulseAll(mre.m_lock); // awaken all waiters } } /// <summary> /// Private helper method for updating parts of a bit-string state value. /// Mainly called from the IsSet and Waiters properties setters /// </summary> /// <remarks> /// Note: the parameter types must be int as CompareExchange cannot take a Uint /// </remarks> /// <param name="newBits">The new value</param> /// <param name="updateBitsMask">The mask used to set the bits</param> private void UpdateStateAtomically(int newBits, int updateBitsMask) { SpinWait sw = new SpinWait(); Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); do { int oldState = m_combinedState; // cache the old value for testing in CAS // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] int newState = (oldState & ~updateBitsMask) | newBits; if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) { return; } sw.SpinOnce(); } while (true); } /// <summary> /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> /// <param name="rightBitShiftCount"></param> /// <returns></returns> private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) { //convert to uint before shifting so that right-shift does not replicate the sign-bit, //then convert back to int. return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); } /// <summary> /// Performs a Mask operation, but does not perform the shift. /// This is acceptable for boolean values for which the shift is unnecessary /// eg (val &amp; Mask) != 0 is an appropriate way to extract a boolean rather than using /// ((val &amp; Mask) &gt;&gt; shiftAmount) == 1 /// /// ?? is there a common place to put this rather than being private to MRES? /// </summary> /// <param name="state"></param> /// <param name="mask"></param> private static int ExtractStatePortion(int state, int mask) { return state & mask; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq.Expressions; namespace MvcContrib.CommandProcessor.Helpers { public abstract class ExpressionVisitor { public virtual Expression Visit(Expression exp) { if (exp == null) return exp; switch (exp.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return VisitUnary((UnaryExpression)exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return VisitBinary((BinaryExpression)exp); case ExpressionType.TypeIs: return VisitTypeIs((TypeBinaryExpression)exp); case ExpressionType.Conditional: return VisitConditional((ConditionalExpression)exp); case ExpressionType.Constant: return VisitConstant((ConstantExpression)exp); case ExpressionType.Parameter: return VisitParameter((ParameterExpression)exp); case ExpressionType.MemberAccess: return VisitMemberAccess((MemberExpression)exp); case ExpressionType.Call: return VisitMethodCall((MethodCallExpression)exp); case ExpressionType.Lambda: return VisitLambda((LambdaExpression)exp); case ExpressionType.New: return VisitNew((NewExpression)exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return VisitNewArray((NewArrayExpression)exp); case ExpressionType.Invoke: return VisitInvocation((InvocationExpression)exp); case ExpressionType.MemberInit: return VisitMemberInit((MemberInitExpression)exp); case ExpressionType.ListInit: return VisitListInit((ListInitExpression)exp); default: throw new NotSupportedException(String.Format("Unhandled expression type: '{0}'", exp.NodeType)); } } protected virtual MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment)binding); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding)binding); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding)binding); default: throw new NotSupportedException(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } protected virtual ElementInit VisitElementInitializer(ElementInit initializer) { ReadOnlyCollection<Expression> arguments = VisitList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } protected virtual Expression VisitUnary(UnaryExpression u) { Expression operand = Visit(u.Operand); if (operand != u.Operand) { return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); } return u; } protected virtual Expression VisitBinary(BinaryExpression b) { Expression left = Visit(b.Left); Expression right = Visit(b.Right); Expression conversion = Visit(b.Conversion); if (left != b.Left || right != b.Right || conversion != b.Conversion) { if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) return Expression.Coalesce(left, right, conversion as LambdaExpression); return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } return b; } protected virtual Expression VisitTypeIs(TypeBinaryExpression b) { Expression expr = Visit(b.Expression); if (expr != b.Expression) { return Expression.TypeIs(expr, b.TypeOperand); } return b; } protected virtual Expression VisitConstant(ConstantExpression c) { return c; } protected virtual Expression VisitConditional(ConditionalExpression c) { Expression test = Visit(c.Test); Expression ifTrue = Visit(c.IfTrue); Expression ifFalse = Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } protected virtual Expression VisitParameter(ParameterExpression p) { return p; } protected virtual Expression VisitMemberAccess(MemberExpression m) { Expression exp = Visit(m.Expression); if (exp != m.Expression) { return Expression.MakeMemberAccess(exp, m.Member); } return m; } protected virtual Expression VisitMethodCall(MethodCallExpression m) { Expression obj = Visit(m.Object); IEnumerable<Expression> args = VisitList(m.Arguments); if (obj != m.Object || args != m.Arguments) { return Expression.Call(obj, m.Method, args); } return m; } protected virtual ReadOnlyCollection<Expression> VisitList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { Expression p = Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) return list.AsReadOnly(); return original; } protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { Expression e = Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { IEnumerable<MemberBinding> bindings = VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { IEnumerable<ElementInit> initializers = VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { MemberBinding b = VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) return list; return original; } protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { ElementInit init = VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) return list; return original; } protected virtual Expression VisitLambda(LambdaExpression lambda) { Expression body = Visit(lambda.Body); if (body != lambda.Body) { return Expression.Lambda(lambda.Type, body, lambda.Parameters); } return lambda; } protected virtual NewExpression VisitNew(NewExpression nex) { IEnumerable<Expression> args = VisitList(nex.Arguments); if (args != nex.Arguments) { if (nex.Members != null) return Expression.New(nex.Constructor, args, nex.Members); return Expression.New(nex.Constructor, args); } return nex; } protected virtual Expression VisitMemberInit(MemberInitExpression init) { NewExpression n = VisitNew(init.NewExpression); IEnumerable<MemberBinding> bindings = VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } protected virtual Expression VisitListInit(ListInitExpression init) { NewExpression n = VisitNew(init.NewExpression); IEnumerable<ElementInit> initializers = VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } protected virtual Expression VisitNewArray(NewArrayExpression na) { IEnumerable<Expression> exprs = VisitList(na.Expressions); if (exprs != na.Expressions) { if (na.NodeType == ExpressionType.NewArrayInit) return Expression.NewArrayInit(na.Type.GetElementType(), exprs); return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } return na; } protected virtual Expression VisitInvocation(InvocationExpression iv) { IEnumerable<Expression> args = VisitList(iv.Arguments); Expression expr = Visit(iv.Expression); if (args != iv.Arguments || expr != iv.Expression) { return Expression.Invoke(expr, args); } return iv; } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.IO; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; namespace LameDOTnet { /// <summary> /// This class contains the lame_enc.dll wrapper. /// </summary> public class Lame { # region " lame structs, enums and variables" /// <summary> /// Error codes of the lame-encoder /// </summary> protected enum LAME_ERR : uint { SUCCESSFUL = 0, INVALID_FORMAT = 1, INVALID_FORMAT_PARAMETERS = 2, NO_MORE_HANDLES = 3, INVALID_HANDLE = 4 } private const uint LAME_ERR_SUCCESSFUL = 0; private const uint LAME_ERR_INVALID_FORMAT = 1; private const uint LAME_ERR_INVALID_FORMAT_PARAMETERS = 2; private const uint LAME_ERR_NO_MORE_HANDLES = 3; private const uint LAME_ERR_INVALID_HANDLE = 4; /// <summary> /// The quality presets for lame. /// </summary> public enum LAME_QUALITY_PRESET : int { LQP_NOPRESET =-1, LQP_NORMAL_QUALITY = 0, LQP_LOW_QUALITY = 1, LQP_HIGH_QUALITY = 2, LQP_VOICE_QUALITY = 3, LQP_R3MIX = 4, LQP_VERYHIGH_QUALITY = 5, LQP_STANDARD = 6, LQP_FAST_STANDARD = 7, LQP_EXTREME = 8, LQP_FAST_EXTREME = 9, LQP_INSANE = 10, LQP_ABR = 11, LQP_CBR = 12, LQP_MEDIUM = 13, LQP_FAST_MEDIUM = 14, LQP_PHONE = 1000, LQP_SW = 2000, LQP_AM = 3000, LQP_FM = 4000, LQP_VOICE = 5000, LQP_RADIO = 6000, LQP_TAPE = 7000, LQP_HIFI = 8000, LQP_CD = 9000, LQP_STUDIO = 10000 } /// <summary> /// The channel mode of / for an mpeg-stream. /// </summary> protected enum MPEG_MODE : uint { STEREO = 0, JOINT_STEREO, /// <summary> /// Not supported! /// </summary> DUAL_CHANNEL, MONO, NOT_SET, /// <summary> /// Do not use! /// </summary> MAX_INDICATOR } /// <summary> /// VBR method for encoding. /// </summary> public enum VBR_METHOD : int { VBR_METHOD_NONE = -1, VBR_METHOD_DEFAULT = 0, VBR_METHOD_OLD = 1, VBR_METHOD_NEW = 2, VBR_METHOD_MTRH = 3, VBR_METHOD_ABR = 4 } /// <summary> /// Sound format. /// </summary> protected enum SOUND_FORMAT { # region " standard formats " /// <summary> /// Microsoft WAV format (little endian). /// </summary> WAV = 0x010000, /// <summary> /// Apple/SGI AIFF format (big endian). /// </summary> AIFF = 0x020000, /// <summary> /// Sun/NeXT AU format (big endian). /// </summary> AU = 0x030000, /// <summary> /// RAW PCM data. /// </summary> RAW = 0x040000, /// <summary> /// Ensoniq PARIS file format. /// </summary> PAF = 0x050000, /// <summary> /// Amiga IFF / SVX8 / SV16 format. /// </summary> SVX = 0x060000, /// <summary> /// Sphere NIST format. /// </summary> NIST = 0x070000, /// <summary> /// VOC files. /// </summary> VOC = 0x080000, /// <summary> /// Berkeley/IRCAM/CARL. /// </summary> IRCAM = 0x0A0000, /// <summary> /// Sonic Foundry's 64 bit RIFF/WAV. /// </summary> WAV64 = 0x0B0000, /// <summary> /// Matlab (tm) V4.2. /// </summary> MATLAB4 = 0x0C0000, /// <summary> /// Matlab (tm) V5.0. /// </summary> MATLAB5 = 0x0D0000, /// <summary> /// Portable Voice Format. /// </summary> PVF = 0x0E0000, /// <summary> /// Fast tracker 2 Extended Instrument. /// </summary> FT2EI = 0x0F0000, /// <summary> /// HMM Tool Kit format. /// </summary> HTK = 0x100000, /// <summary> /// Midi Sample Dump Standard. /// </summary> MSDS = 0x110000, # endregion # region " PCM sub formats " /// <summary> /// Signed 8 bit PCM data. /// </summary> PCM_S8 = 0x0001, /// <summary> /// Signed 16 bit PCM data. /// </summary> PCM_S16 = 0x0002, /// <summary> /// Signed 24 bit PCM data. /// </summary> PCM_S24 = 0x0003, /// <summary> /// Signed 32 bit PCM data. /// </summary> PCM_S32 = 0x0004, /// <summary> /// Unsigned 8 bit WAV or RAW data /// </summary> PCM_U8 = 0x0005, # endregion # region " ADPCM formats" /// <summary> /// Dialogix ADPCM /// </summary> DX_ADPCM = 0x0021, /// <summary> /// 32kbs G721 ADPCM. /// </summary> G721_32 = 0x0030, /// <summary> /// 24kbs G723 ADPCM. /// </summary> G723_24 = 0x0031, /// <summary> /// 40kbs G723 ADPCM. /// </summary> G723_40 = 0x0032, /// <summary> /// IMA ADPCM. /// </summary> ADPCM_IMA = 0x0012, /// <summary> /// Microsoft ADPCM. /// </summary> ADPCM_MS = 0x0013, # endregion # region " Delta Width Variable Word formats " /// <summary> /// 12bit Delta Width Variable Word. /// </summary> DWVW_12 = 0x0040, /// <summary> /// 16bit Delta Width Variable Word. /// </summary> DWVW_16 = 0x0041, /// <summary> /// 24bit Delta Width Variable Word. /// </summary> DWVW_24 = 0x0042, /// <summary> /// n-bit Delta Width Variable Word. /// </summary> DWVM_N = 0x0043, # endregion # region " DPCM formats " /// <summary> /// 8 bit differential PCM. /// </summary> DPCM_8 = 0x0050, /// <summary> /// 16 bit differential PCM. /// </summary> DPCM_16 = 0x0051, # endregion # region " float data " /// <summary> /// 32bit float data. /// </summary> FLOAT = 0x0006, /// <summary> /// 64bit float data. /// </summary> DOUBLE = 0x0007, # endregion # region " other formats " /// <summary> /// U-Law. /// </summary> ULAW = 0x0010, /// <summary> /// A-Law. /// </summary> ALAW = 0x0011, /// <summary> /// GSM 6.10. /// </summary> GSM610 = 0x0020, # endregion # region " endian options " /// <summary> /// File endian. /// </summary> ENDIAN_FILE = 0x00000000, /// <summary> /// Little endian. /// </summary> ENDIAN_LITTLE = 0x10000000, /// <summary> /// Big endian. /// </summary> ENDIAN_BIG = 0x20000000, /// <summary> /// CPU endian. /// </summary> ENDIAN_CPU = 0x30000000, # endregion # region " other " FORMAT_SUBMASK = 0x0000FFFF, FORMAT_TYPEMASK = 0x0FFF0000, FORMAT_ENDMASK = 0x30000000 # endregion } /// <summary> /// Holds all version informations of a lame_enc.dll /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class LAME_VERSION { public const uint BE_MAX_HOMEPAGE = 256; public byte byDLLMajorVersion; public byte byDLLMinorVersion; public byte byMajorVersion; public byte byMinorVersion; // Release date of the linked lame_enc.dll: public byte byDay; public byte byMonth; public ushort wYear; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)] public string zHomepage; public byte byAlphaLevel; public byte byBetaLevel; public byte byMMXEnabled; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 125)] public byte[] btReserved; public LAME_VERSION() { btReserved = new byte[125]; } } /// <summary> /// Holds the config of a lame-encoder. /// </summary> [StructLayout(LayoutKind.Sequential), Serializable] protected class LAME_CONFIG { public const uint BE_CONFIG_MP3 = 0; public const uint BE_CONFIG_LAME = 256; public uint dwConfig; public config union; public LAME_CONFIG(SOUND_INFO soundInfo, MP3_Settings settings) { dwConfig = BE_CONFIG_LAME; union = new config(soundInfo, settings); } } /// <summary> /// Hold de detailed configuration. /// </summary> [StructLayout(LayoutKind.Explicit), Serializable] protected class config { [FieldOffset(0)] public MP3 mp3; [FieldOffset(0)] public LameHeaderVersion1 lhv1; [FieldOffset(0)] public ACC acc; public config(SOUND_INFO soundInfo, MP3_Settings settings) { lhv1 = new LameHeaderVersion1(soundInfo, settings); } } /// <summary> /// The acc settings. /// </summary> [StructLayout(LayoutKind.Sequential), Serializable] protected struct ACC { public uint dwSampleRate; public byte byMode; public ushort wBitrate; public byte byEncodingMethod; } /// <summary> /// The lame header configuration. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 327), Serializable] protected struct LameHeaderVersion1 { # region " mpeg-version " public const uint MPEG1 = 1; public const uint MPEG2 = 0; # endregion # region " informations " public uint dwStructVersion; public uint dwStructSize; # endregion # region " encoder settings " /// <summary> /// Sample rate of the input file. /// </summary> public uint dwSampleRate; /// <summary> /// Sample rate for resampling; 0 = lame will decide. /// </summary> public uint dwReSampleRate; /// <summary> /// Stereo or mono. /// </summary> public MPEG_MODE nMode; /// <summary> /// CBR bitrate or VBR min. bitrate. /// </summary> public uint dwBitrate; /// <summary> /// Max. bitrate for VBR; ignored at CBR. /// </summary> public uint dwMaxBitrate; /// <summary> /// The quality preset. /// </summary> public LAME_QUALITY_PRESET nPreset; /// <summary> /// mpeg-version (MPEG-1 or MPEG-2). /// </summary> public uint dwMpegVersion; /// <summary> /// For future use, set to 0. /// </summary> public uint dwPsyModel; /// <summary> /// For future use, set to 0. /// </summary> public uint dwEmphasis; # endregion # region " bit settings " /// <summary> /// Set the private bit; 0 = false, 1 = true. /// </summary> public int bPrivate; /// <summary> /// Set the CRC bit; 0 = false, 1 = true. /// </summary> public int bCRC; /// <summary> /// Set the copyright bit; 0 = false, 1 = true. /// </summary> public int bCopyright; /// <summary> /// Set the original bit; 0 = false, 1 = true. /// </summary> public int bOriginal; # endregion # region " VBR settings " /// <summary> /// Write the XING VBR header; 0 = false, 1 = true. /// </summary> public int bWriteVBRHeader; /// <summary> /// Use VBR encoding; 0 = false, 1 = true. /// </summary> public int bEnableVBR; /// <summary> /// VBR quality mode; 0...9. /// </summary> public int nVBRQuality; /// <summary> /// Use ABR in stead of VBR. /// </summary> public uint dwVbrAbr_bps; /// <summary> /// VBR method /// </summary> public VBR_METHOD nVbrMethod; /// <summary> /// Disable bit reservoir; 0 = false, 1 = true. /// </summary> public int bNoRes; # endregion # region " other settings " /// <summary> /// Use strict ISO encoding rules; 0 = false, 1 = true. /// </summary> public int bStrictIso; /// <summary> /// Quality settings, high byte should not be low byte, otherwise quality = 5. /// </summary> public ushort nQuality; # endregion # region " constructor " public LameHeaderVersion1(SOUND_INFO soundInfo, MP3_Settings settings) { #region " Check the input format " if (soundInfo.format != ((int)SOUND_FORMAT.WAV | (int)SOUND_FORMAT.PCM_S16)) { throw new InvalidDataException("Wrong format!", new Exception("Only 16 bit uncompressed WAV supported. You gave " + soundInfo.format)); } # endregion dwStructVersion = 1; dwStructSize = (uint)Marshal.SizeOf(typeof(LAME_CONFIG)); # region " Check input sample rate " switch (soundInfo.samplerate) { case 16000: case 22050: case 24000: dwMpegVersion = MPEG2; break; case 32000: case 44100: case 48000: dwMpegVersion = MPEG1; break; default: throw new InvalidDataException("Wrong format!", new Exception("Sample rate " + soundInfo.samplerate + " not supported.")); } # endregion dwSampleRate = (uint)soundInfo.samplerate; dwReSampleRate = 0; # region " Set encoding channels " switch (soundInfo.channels) { case 1: nMode = MPEG_MODE.MONO; break; case 2: nMode = MPEG_MODE.STEREO; break; default: throw new InvalidDataException("Wrong format!", new Exception("Invalid number of channels:" + soundInfo.channels)); } # endregion # region " Check encoding bit rate " switch (settings.Bitrate) { case 32: case 40: case 48: case 56: case 64: case 80: case 96: case 112: case 128: case 160: break; // Allowed only in MPEG1: case 192: case 224: case 256: case 320: if (dwMpegVersion != MPEG1) { throw new InvalidDataException("Wrong mp3 bit rate!", new Exception("Incompatible bit rate:" + settings.Bitrate)); } break; // Allowed only in MPEG2: case 8: case 16: case 24: case 144: if (dwMpegVersion != MPEG2) { throw new InvalidDataException("Wrong mp3 bit rate!", new Exception("Incompatible bit rate:" + settings.Bitrate)); } break; default: throw new InvalidDataException("Wrong mp3 bit rate!", new Exception("Can't support bit rate")); } # endregion dwBitrate = settings.Bitrate; nPreset = settings.QualityPreset; bEnableVBR = settings.VBR_enabled ? 1 : 0; dwMaxBitrate = settings.VBR_maxBitrate; dwVbrAbr_bps = 0; nQuality = 0; nVbrMethod = settings.VBR_method; nVBRQuality = settings.VBR_Quality; bWriteVBRHeader = settings.VBR_WriteHeader ? 1 : 0; bOriginal = settings.OriginalBit ? 1 : 0; bCopyright = settings.CopyrightBit ? 1 : 0; bCRC = settings.CRC_Bit ? 1 : 0; bPrivate = settings.PrivatBit ? 1 : 0; bNoRes = settings.DisableBitReservoir ? 1 : 0; bStrictIso = settings.StrictISOencoding ? 1 : 0; dwPsyModel = 0; dwEmphasis = 0; } # endregion } /// <summary> /// MP3 configuration /// </summary> [StructLayout(LayoutKind.Sequential), Serializable] protected struct MP3 { /// <summary> /// Sample rate; 48000, 44100 and 32000 allowed. /// </summary> public uint dwSampleRate; /// <summary> /// Encoding mode (STEREO, DUALCHANNEL or MONO). /// </summary> public byte byMode; /// <summary> /// Encoding bitrate: 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256 and 320 allowed. /// </summary> public ushort wBitrate; /// <summary> /// Private bit. /// </summary> public int bPrivate; /// <summary> /// CRC bit. /// </summary> public int bCRC; /// <summary> /// Copyright bit. /// </summary> public int bCopyright; /// <summary> /// Original bit. /// </summary> public int bOriginal; } /// <summary> /// Holds all information about an audio file. /// </summary> [StructLayout(LayoutKind.Sequential)] protected struct SOUND_INFO { public System.Int64 frames; public int samplerate; public int channels; public int format; public int sections; public int seekable; }; # endregion # region " lame_enc.dll and libsndfile.dll inter ops " /// <summary> /// This function is the first to call before starting an encoding stream. /// </summary> /// <param name="Config">Encoder settings</param> /// <param name="Samples">Receives the number of samples (not bytes, each sample is a SHORT) to send to each beEncodeChunk() on return.</param> /// <param name="OutputBufferSize">Receives the minimum number of bytes that must have the output(result) buffer</param> /// <param name="StreamHandle">Receives the stream handle on return</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> [DllImport("lame_enc.dll")] protected static extern uint beInitStream(LAME_CONFIG Config, ref uint Samples, ref uint OutputBufferSize, ref uint StreamHandle); /// <summary> /// Encodes a chunk of samples. Please note that if you have set the output to /// generate mono MP3 files you must feed beEncodeChunk() with mono samples /// </summary> /// <param name="StreamHandle">Handle of the stream.</param> /// <param name="Samples">Number of samples to be encoded for this call. /// This should be identical to what is returned by beInitStream(), /// unless you are encoding the last chunk, which might be smaller.</param> /// <param name="InSamples">Array of 16-bit signed samples to be encoded. /// These should be in stereo when encoding a stereo MP3 /// and mono when encoding a mono MP3</param> /// <param name="Output">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="Written">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> [DllImport("lame_enc.dll")] private static extern uint beEncodeChunk(uint StreamHandle, uint Samples, short[] InSamples, [In, Out] byte[] Output, ref uint Written); /// <summary> /// Encodes a chunk of samples. Please note that if you have set the output to /// generate mono MP3 files you must feed beEncodeChunk() with mono samples /// </summary> /// <param name="StreamHandle">Handle of the stream.</param> /// <param name="SampleCount">Number of samples to be encoded for this call. /// This should be identical to what is returned by beInitStream(), /// unless you are encoding the last chunk, which might be smaller.</param> /// <param name="Samples">Pointer at the 16-bit signed samples to be encoded. /// InPtr is used to pass any type of array without need of make memory copy, /// then gaining in performance. Note that nSamples is not the number of bytes, /// but samples (is sample is a SHORT)</param> /// <param name="Output">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="Written">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> [DllImport("lame_enc.dll")] private static extern uint beEncodeChunk(uint StreamHandle, uint SampleCount, IntPtr Samples, [In, Out] byte[] Output, ref uint Written); /// <summary> /// Encodes a chunk of samples. Samples are contained in a byte array /// </summary> /// <param name="StreamHandle">Handle of the stream.</param> /// <param name="buffer">Bytes to encode</param> /// <param name="index">Position of the first byte to encode</param> /// <param name="bytes">Number of bytes to encode (not samples, samples are two byte length)</param> /// <param name="Output">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="Written">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> protected static uint EncodeChunk(uint StreamHandle, byte[] buffer, int index, uint bytes, byte[] Output, ref uint Written) { uint res; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { IntPtr ptr = (IntPtr)(handle.AddrOfPinnedObject().ToInt32() + index); res = beEncodeChunk(StreamHandle, bytes / 2, ptr, Output, ref Written); } finally { handle.Free(); } return res; } /// <summary> /// Encodes a chunk of samples. Samples are contained in a byte array /// </summary> /// <param name="StreamHandle">Handle of the stream.</param> /// <param name="buffer">Bytes to encode</param> /// <param name="Output">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="Written">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> protected static uint EncodeChunk(uint StreamHandle, byte[] buffer, byte[] Output, ref uint Written) { return EncodeChunk(StreamHandle, buffer, 0, (uint)buffer.Length, Output, ref Written); } /// <summary> /// This function should be called after encoding the last chunk in order to flush /// the encoder. It writes any encoded data that still might be left inside the /// encoder to the output buffer. This function should NOT be called unless /// you have encoded all of the chunks in your stream. /// </summary> /// <param name="StreamHandle">Handle of the stream.</param> /// <param name="Output">Where to write the encoded data. This buffer should be /// at least of the minimum size returned by beInitStream().</param> /// <param name="Written">Returns number of bytes of encoded data written.</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> [DllImport("lame_enc.dll")] protected static extern uint beDeinitStream(uint StreamHandle, [In, Out] byte[] Output, ref uint Written); /// <summary> /// Last function to be called when finished encoding a stream. /// Should unlike beDeinitStream() also be called if the encoding is canceled. /// </summary> /// <param name="StreamHandle">Handle of the stream.</param> /// <returns>On success: LAME_ERR_SUCCESSFUL</returns> [DllImport("lame_enc.dll")] protected static extern uint beCloseStream(uint StreamHandle); /// <summary> /// Returns information like version numbers (both of the DLL and encoding engine), /// release date and URL for lame_enc's homepage. /// All this information should be made available to the user of your product /// through a dialog box or something similar. /// </summary> /// <param name="version">Where version number, release date and URL for homepage is returned.</param> [DllImport("lame_enc.dll")] protected static extern void beVersion([Out] LAME_VERSION version); [DllImport("lame_enc.dll", CharSet = CharSet.Ansi)] protected static extern void beWriteVBRHeader(string MP3FileName); [DllImport("lame_enc.dll")] protected static extern uint beEncodeChunkFloatS16NI(uint StreamHandle, uint Samples, [In]float[] buffer_l, [In]float[] buffer_r, [In, Out]byte[] Output, ref uint Written); [DllImport("lame_enc.dll")] protected static extern uint beFlushNoGap(uint StreamHandle, [In, Out]byte[] Output, ref uint Written); [DllImport("lame_enc.dll", CharSet = CharSet.Ansi)] protected static extern uint beWriteInfoTag(uint StreamHandle, string FileName); /// <summary> /// Get some infos about an audio file. /// </summary> /// <param name="filename">The filename.</param> /// <param name="soundInfo">The info.</param> /// <returns></returns> protected int GetSoundFileInfo(string filename, ref SOUND_INFO soundInfo) { IntPtr errorRef = sf_open(filename, 0x10, ref soundInfo); int status = sf_error(errorRef); int c = sf_close(errorRef); return status; } [DllImport("libsndfile.dll")] private static extern IntPtr sf_open([MarshalAs(UnmanagedType.LPStr)] string path, int mode, ref SOUND_INFO soundInfo); [DllImport("libsndfile.dll")] private static extern int sf_error(IntPtr sndfile); [DllImport("libsndfile.dll")] private static extern int sf_close(IntPtr sndfile); # endregion # region " variables " private bool closed = true; private uint Samples; private uint outputBufferSize; public uint OutputBufferSize { get { return outputBufferSize; } } private uint StreamHandle; private int optimalBufferSize; public int OptimalBufferSize { get { return optimalBufferSize; } } private string inputWaveFile; private Stream InputStream; private Stream OutputStream; private byte[] InputBuffer; private byte[] OutputBuffer; # endregion # region " mp3 settings " public class MP3_Settings { # region " basic settings " /// <summary> /// Encoding bitrate: 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256 and 320 allowed. /// Min. bitrate in VBR mode. /// </summary> public uint Bitrate = 128; /// <summary> /// The overall quality of the encoding. /// </summary> public LAME_QUALITY_PRESET QualityPreset = LAME_QUALITY_PRESET.LQP_NORMAL_QUALITY; # endregion # region " VBR settings " /// <summary> /// If <i>true</i>, the encoder uses VBR. /// </summary> public bool VBR_enabled = false; /// <summary> /// Max. bitrate in VBR mode. /// </summary> public uint VBR_maxBitrate = 192; /// <summary> /// The used method for VBR encoding. /// </summary> public VBR_METHOD VBR_method = VBR_METHOD.VBR_METHOD_DEFAULT; /// <summary> /// The quality for the VBR encoding, must be value between 0...8. /// </summary> public int VBR_Quality = 0; /// <summary> /// If <i>true</i>, an extra XING VBR header will be written. /// </summary> public bool VBR_WriteHeader = false; # endregion # region " bit settings " /// <summary> /// If <i>true</i>, the original bit will be set. /// </summary> public bool OriginalBit = true; /// <summary> /// If <i>true</i>, the copyright bit will be set. /// </summary> public bool CopyrightBit = false; /// <summary> /// If <i>true</i>, the CRC bit will be set. /// </summary> public bool CRC_Bit = false; /// <summary> /// If <i>true</i>, the private bit will be set. /// </summary> public bool PrivatBit = false; # endregion # region " other settings /// <summary> /// If <i>true</i>, the bit reservoir will be disabled. /// </summary> public bool DisableBitReservoir = false; /// <summary> /// If <i>true</i>, the encoder will use a strict ISO encoding. /// </summary> public bool StrictISOencoding = false; # endregion }; # endregion # region " constructor " /// <summary> /// Initializes a new instance of the <see cref="Lame"/> class. /// </summary> /// <param name="settings">The encoding settings.</param> public Lame(MP3_Settings settings, int Channels, int SampleRate) { SOUND_INFO info = new SOUND_INFO(); info.format = 0x010002; info.samplerate = SampleRate; info.channels = Channels; LAME_CONFIG mp3config = new LAME_CONFIG(info, settings); if (beInitStream(mp3config, ref Samples, ref outputBufferSize, ref StreamHandle) != LAME_ERR_SUCCESSFUL) throw new Exception("Failed to initialize lame!"); optimalBufferSize = 2 * (int)Samples; InputBuffer = new byte[optimalBufferSize]; OutputBuffer = new byte[OutputBufferSize]; } /// <summary> /// Initializes a new instance of the <see cref="Lame"/> class. /// </summary> /// <param name="InputWaveFile">The input wave file.</param> /// <param name="settings">The encoding settings.</param> public Lame(string InputWaveFile, MP3_Settings settings) { inputWaveFile = InputWaveFile; SOUND_INFO info = new SOUND_INFO(); GetSoundFileInfo(InputWaveFile, ref info); LAME_CONFIG mp3config = new LAME_CONFIG(info, settings); if (beInitStream(mp3config, ref Samples, ref outputBufferSize, ref StreamHandle) != LAME_ERR_SUCCESSFUL) throw new Exception("Failed to initialize lame!"); optimalBufferSize = 2 * (int)Samples; InputBuffer = new byte[optimalBufferSize]; OutputBuffer = new byte[OutputBufferSize]; } # endregion # region " encoding " /// <summary> /// Encodes to the specified output Mp3 file. /// </summary> /// <param name="OutputMP3File">The output Mp3 file.</param> /// <param name="status">The status.</param> public void EncodeWAV(string OutputMP3File, Delegate status) { closed = false; InputStream = File.OpenRead(inputWaveFile); OutputStream = File.Open(OutputMP3File, FileMode.Create); long total = InputStream.Length; int readed = 0; int read = 0; while ((read = InputStream.Read(InputBuffer, 0, InputBuffer.Length)) > 0) { uint encoded = 0; if (EncodeChunk(StreamHandle, InputBuffer, OutputBuffer, ref encoded) == LAME_ERR_SUCCESSFUL) { if (encoded > 0) OutputStream.Write(OutputBuffer, 0, (int)encoded); } else throw new Exception("Chunk failed to encode"); readed += read; double pos = ((double)readed * (double)100) / (double)total; status.DynamicInvoke(new object[] { pos }); } } /// <summary> /// Encodes the specified chunk to Mp3. /// </summary> /// <param name="InputBuffer">The input buffer.</param> /// <param name="OutputBuffer">The output buffer.</param> public uint EncodeChunk(byte[] InputBuffer, byte[] OutputBuffer) { closed = false; uint encoded = 0; if (EncodeChunk(StreamHandle, InputBuffer, OutputBuffer, ref encoded) != LAME_ERR_SUCCESSFUL) throw new Exception("Chunk failed to encode"); return encoded; } # endregion # region " other methods " /// <summary> /// Closes this stream. /// </summary> public void Close() { try { if (!closed) { uint encoded = 0; if (beDeinitStream(StreamHandle, OutputBuffer, ref encoded) == LAME_ERR_SUCCESSFUL) { if ((OutputStream != null) && (encoded > 0)) OutputStream.Write(OutputBuffer, 0, (int)encoded); } beCloseStream(StreamHandle); } } finally { if (InputStream != null) InputStream.Close(); if (OutputStream != null) OutputStream.Close(); } closed = true; } /// <summary> /// Closes this stream. /// </summary> /// <param name="lastData">The last data to write into the Mp3 file.</param> /// <returns>The count of the last bytes, if 0 no more data available.</returns> public uint Close(byte[] lastData) { uint encoded = 0; if (!closed) { if (beDeinitStream(StreamHandle, lastData, ref encoded) != LAME_ERR_SUCCESSFUL) encoded = 0; beCloseStream(StreamHandle); } closed = true; return encoded; } /// <summary> /// Gets the version of lame. /// </summary> /// <returns></returns> public static LAME_VERSION GetVersion() { LAME_VERSION version = new LAME_VERSION(); beVersion(version); return version; } # endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.FluentInterfaceTests; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface { [TestFixture] public class HasManyToManyConventionTests { private PersistenceModel model; private IMappingProvider mapping; private Type mappingType; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void AccessShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Access.Field()); Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("field")); } [Test] public void BatchSizeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.BatchSize(10)); Convention(x => x.BatchSize(100)); VerifyModel(x => x.BatchSize.ShouldEqual(10)); } [Test] public void CacheShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Cache.ReadOnly()); Convention(x => x.Cache.ReadWrite()); VerifyModel(x => x.Cache.Usage.ShouldEqual("read-only")); } [Test] public void CascadeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Cascade.All()); Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("all")); } [Test] public void CheckConstraintShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Check("constraint = 1")); Convention(x => x.Check("constraint = 0")); VerifyModel(x => x.Check.ShouldEqual("constraint = 1")); } [Test] public void CollectionTypeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.CollectionType<int>()); Convention(x => x.CollectionType<string>()); VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(int))); } [Test] public void FetchShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Fetch.Join()); Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("join")); } [Test] public void GenericShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Generic()); Convention(x => x.Not.Generic()); VerifyModel(x => x.Generic.ShouldBeTrue()); } [Test] public void InverseShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Inverse()); Convention(x => x.Not.Inverse()); VerifyModel(x => x.Inverse.ShouldBeTrue()); } [Test] public void ParentKeyColumnNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.ParentKeyColumn("name")); Convention(x => x.Key.Column("xxx")); VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("name")); } [Test] public void ChildKeyColumnNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.ChildKeyColumn("name")); Convention(x => x.Relationship.Column("xxx")); VerifyModel(x => ((ManyToManyMapping)x.Relationship).Columns.First().Name.ShouldEqual("name")); } [Test] public void LazyShouldntBeOverwritten() { Mapping(x => x.Children, x => x.LazyLoad()); Convention(x => x.Not.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(true)); } [Test] public void OptimisticLockShouldntBeOverwritten() { Mapping(x => x.Children, x => x.OptimisticLock.All()); Convention(x => x.OptimisticLock.Dirty()); VerifyModel(x => x.OptimisticLock.ShouldEqual("all")); } [Test] public void PersisterShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Persister<CustomPersister>()); Convention(x => x.Persister<SecondCustomPersister>()); VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister))); } [Test] public void SchemaShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Schema("dbo")); Convention(x => x.Schema("test")); VerifyModel(x => x.Schema.ShouldEqual("dbo")); } [Test] public void WhereShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Where("x = 1")); Convention(x => x.Where("y = 2")); VerifyModel(x => x.Where.ShouldEqual("x = 1")); } [Test] public void TableNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Table("table")); Convention(x => x.Table("xxx")); VerifyModel(x => x.TableName.ShouldEqual("table")); } #region Helpers private void Convention(Action<IManyToManyCollectionInstance> convention) { model.Conventions.Add(new ManyToManyCollectionConventionBuilder().Always(convention)); } private void Mapping<TChild>(Expression<Func<ExampleInheritedClass, IEnumerable<TChild>>> property, Action<ManyToManyPart<TChild>> mappingDefinition) { var classMap = new ClassMap<ExampleInheritedClass>(); var map = classMap.HasManyToMany(property); mappingDefinition(map); mapping = classMap; mappingType = typeof(ExampleInheritedClass); } private void VerifyModel(Action<ICollectionMapping> modelVerification) { model.Add(mapping); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null) .Classes.First() .Collections.First(); modelVerification(modelInstance); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #region Assembly System.Windows.dll, v2.0.50727 // C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\Profile\WindowsPhone\System.Windows.dll #endregion using System; using System.Diagnostics.Contracts; namespace System.Windows { // Summary: // Represents the duration of time that a System.Windows.Media.Animation.Timeline // is active. public struct Duration { // // Summary: // Initializes a new instance of the System.Windows.Duration structure with // the supplied System.TimeSpan value. // // Parameters: // timeSpan: // Represents the initial time interval of this duration. // // Exceptions: // System.ArgumentException: // timeSpan evaluates as less than System.TimeSpan.Zero. extern public Duration(TimeSpan timeSpan); // Summary: // Subtracts the value of one System.Windows.Duration from another. // // Parameters: // t1: // The first System.Windows.Duration. // // t2: // The System.Windows.Duration to subtract. // // Returns: // If each System.Windows.Duration has values, a System.Windows.Duration that // represents the value of t1 minus t2. If t1 has a value of System.Windows.Duration.Forever // and t2 has a value of System.Windows.Duration.TimeSpan, this method returns // System.Windows.Duration.Forever. Otherwise this method returns null. extern public static Duration operator -(Duration t1, Duration t2); // // Summary: // Determines if two System.Windows.Duration cases are not equal. // // Parameters: // t1: // The first System.Windows.Duration to compare. // // t2: // The second System.Windows.Duration to compare. // // Returns: // true if exactly one of t1 or t2 represent a value, or if they both represent // values that are not equal; otherwise, false. extern public static bool operator !=(Duration t1, Duration t2); // // Summary: // Returns the specified System.Windows.Duration. // // Parameters: // duration: // The System.Windows.Duration to get. // // Returns: // A System.Windows.Duration. extern public static Duration operator +(Duration duration); // // Summary: // Adds two System.Windows.Duration values together. // // Parameters: // t1: // The first System.Windows.Duration to add. // // t2: // The second System.Windows.Duration to add. // // Returns: // If both System.Windows.Duration values have System.TimeSpan values, this // method returns the sum of those two values. If either value is set to System.Windows.Duration.Automatic, // the method returns System.Windows.Duration.Automatic. If either value is // set to System.Windows.Duration.Forever, the method returns System.Windows.Duration.Forever.If // either t1 or t2 has no value, this method returns null. extern public static Duration operator +(Duration t1, Duration t2); // // Summary: // Determines if a System.Windows.Duration is less than the value of another // instance. // // Parameters: // t1: // The first System.Windows.Duration to compare. // // t2: // The second System.Windows.Duration to compare. // // Returns: // true if both t1 and t2 have values and t1 is less than t2; otherwise, false. extern public static bool operator <(Duration t1, Duration t2); // // Summary: // Determines if a System.Windows.Duration is less than or equal to another. // // Parameters: // t1: // The System.Windows.Duration to compare. // // t2: // The System.Windows.Duration to compare. // // Returns: // true if both t1 and t2 have values and t1 is less than or equal to t2; otherwise, // false. extern public static bool operator <=(Duration t1, Duration t2); // // Summary: // Determines whether two System.Windows.Duration cases are equal. // // Parameters: // t1: // The first System.Windows.Duration to compare. // // t2: // The second System.Windows.Duration to compare. // // Returns: // true if both System.Windows.Duration values have equal property values, or // if all System.Windows.Duration values are null. Otherwise, this method returns // false. extern public static bool operator ==(Duration t1, Duration t2); // // Summary: // Determines if one System.Windows.Duration is greater than another. // // Parameters: // t1: // The System.Windows.Duration value to compare. // // t2: // The second System.Windows.Duration value to compare. // // Returns: // true if both t1 and t2 have values and t1 is greater than t2; otherwise, // false. extern public static bool operator >(Duration t1, Duration t2); // // Summary: // Determines whether a System.Windows.Duration is greater than or equal to // another. // // Parameters: // t1: // The first instance of System.Windows.Duration to compare. // // t2: // The second instance of System.Windows.Duration to compare. // // Returns: // true if both t1 and t2 have values and t1 is greater than or equal to t2; // otherwise, false. extern public static bool operator >=(Duration t1, Duration t2); // // Summary: // Implicitly creates a System.Windows.Duration from a given System.TimeSpan. // // Parameters: // timeSpan: // System.TimeSpan from which a System.Windows.Duration is implicitly created. // // Returns: // A created System.Windows.Duration. // // Exceptions: // System.ArgumentException: // timeSpan evaluates as less than System.TimeSpan.Zero. extern public static implicit operator Duration(TimeSpan timeSpan); // Summary: // Gets a System.Windows.Duration value that is automatically determined. // // Returns: // A System.Windows.Duration initialized to an automatic value. public static Duration Automatic { get { return default(Duration); } } // // Summary: // Gets a System.Windows.Duration value that represents an infinite interval. // // Returns: // A System.Windows.Duration initialized to a forever value. public static Duration Forever { get { return default(Duration); } } // // Summary: // Gets a value that indicates if this System.Windows.Duration represents a // System.TimeSpan value. // // Returns: // true if this System.Windows.Duration is a System.TimeSpan value; otherwise, // false. //public bool HasTimeSpan { get; } // // Summary: // Gets the System.TimeSpan value that this System.Windows.Duration represents. // // Returns: // The System.TimeSpan value that this System.Windows.Duration represents. // // Exceptions: // System.InvalidOperationException: // The System.Windows.Duration does not represent a System.TimeSpan. //public TimeSpan TimeSpan { get; } // Summary: // Adds the value of the specified System.Windows.Duration to this System.Windows.Duration. // // Parameters: // duration: // An instance of System.Windows.Duration that represents the value of the current // instance plus duration. // // Returns: // If each involved System.Windows.Duration has values, a System.Windows.Duration // that represents the combined values. Otherwise this method returns null. extern public Duration Add(Duration duration); // // Summary: // Compares one System.Windows.Duration value to another. // // Parameters: // t1: // The first instance of System.Windows.Duration to compare. // // t2: // The second instance of System.Windows.Duration to compare. // // Returns: // If t1 is less than t2, a negative value that represents the difference. If // t1 is equal to t2, a value of 0. If t1 is greater than t2, a positive value // that represents the difference. extern public static int Compare(Duration t1, Duration t2); // // Summary: // Determines whether a specified System.Windows.Duration is equal to this System.Windows.Duration. // // Parameters: // duration: // The System.Windows.Duration to check for equality. // // Returns: // true if duration is equal to this System.Windows.Duration; otherwise, false. extern public bool Equals(Duration duration); // // Summary: // Determines whether two System.Windows.Duration values are equal. // // Parameters: // t1: // First System.Windows.Duration to compare. // // t2: // Second System.Windows.Duration to compare. // // Returns: // true if t1 is equal to t2; otherwise, false. extern public static bool Equals(Duration t1, Duration t2); // // Summary: // Adds one System.Windows.Duration to this System.Windows.Duration. // // Parameters: // duration: // The System.Windows.Duration to add. // // Returns: // The summed System.Windows.Duration. extern public static Duration Plus(Duration duration); // // Summary: // Subtracts the specified System.Windows.Duration from this System.Windows.Duration. // // Parameters: // duration: // The System.Windows.Duration to subtract from this System.Windows.Duration. // // Returns: // The subtracted System.Windows.Duration. extern public Duration Subtract(Duration duration); } }
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { public class SayDialog : MonoBehaviour { // Currently active Say Dialog used to display Say text public static SayDialog activeSayDialog; // Most recent speaking character public static Character speakingCharacter; public float fadeDuration = 0.25f; public Button continueButton; public Canvas dialogCanvas; public Text nameText; public Text storyText; public Image characterImage; [Tooltip("Adjust width of story text when Character Image is displayed (to avoid overlapping)")] public bool fitTextWithImage = true; [Tooltip("Scale factor to apply to story text width when Character Image is displayed")] public float textWidthScale = 0.8f; protected float startStoryTextWidth; protected float startStoryTextInset; protected WriterAudio writerAudio; protected Writer writer; protected CanvasGroup canvasGroup; protected bool fadeWhenDone = true; protected float targetAlpha = 0f; protected float fadeCoolDownTimer = 0f; public static SayDialog GetSayDialog() { if (activeSayDialog == null) { // Use first Say Dialog found in the scene (if any) SayDialog sd = GameObject.FindObjectOfType<SayDialog>(); if (sd != null) { activeSayDialog = sd; } if (activeSayDialog == null) { // Auto spawn a say dialog object from the prefab GameObject prefab = Resources.Load<GameObject>("SayDialog"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.SetActive(false); go.name = "SayDialog"; activeSayDialog = go.GetComponent<SayDialog>(); } } } return activeSayDialog; } protected Writer GetWriter() { if (writer != null) { return writer; } writer = GetComponent<Writer>(); if (writer == null) { writer = gameObject.AddComponent<Writer>(); } return writer; } protected CanvasGroup GetCanvasGroup() { if (canvasGroup != null) { return canvasGroup; } canvasGroup = GetComponent<CanvasGroup>(); if (canvasGroup == null) { canvasGroup = gameObject.AddComponent<CanvasGroup>(); } return canvasGroup; } protected WriterAudio GetWriterAudio() { if (writerAudio != null) { return writerAudio; } writerAudio = GetComponent<WriterAudio>(); if (writerAudio == null) { writerAudio = gameObject.AddComponent<WriterAudio>(); } return writerAudio; } protected void Start() { // Dialog always starts invisible, will be faded in when writing starts GetCanvasGroup().alpha = 0f; // Add a raycaster if none already exists so we can handle dialog input GraphicRaycaster raycaster = GetComponent<GraphicRaycaster>(); if (raycaster == null) { gameObject.AddComponent<GraphicRaycaster>(); } } public virtual void Say(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, AudioClip audioClip, Action onComplete) { StartCoroutine(SayInternal(text, clearPrevious, waitForInput, fadeWhenDone, audioClip, onComplete)); } protected virtual IEnumerator SayInternal(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, AudioClip audioClip, Action onComplete) { Writer writer = GetWriter(); // Stop any existing Say Command and write this one instead // This will probably take a frame or two to complete while (writer.isWriting || writer.isWaitingForInput) { writer.Stop(); yield return null; } this.fadeWhenDone = fadeWhenDone; // Look for a character sound effect if no voice over clip is specified AudioClip clip = audioClip; if (speakingCharacter != null && clip == null) { clip = speakingCharacter.soundEffect; } writer.Write(text, clearPrevious, waitForInput, clip, onComplete); } protected virtual void LateUpdate() { UpdateAlpha(); if (continueButton != null) { continueButton.gameObject.SetActive( GetWriter().isWaitingForInput ); } } /** * Tell dialog to fade out if it's finished writing. */ public virtual void FadeOut() { fadeWhenDone = true; } /** * Stop a Say Dialog while its writing text. */ public virtual void Stop() { fadeWhenDone = true; GetWriter().Stop(); } protected virtual void UpdateAlpha() { if (GetWriter().isWriting) { targetAlpha = 1f; fadeCoolDownTimer = 0.1f; } else if (fadeWhenDone && fadeCoolDownTimer == 0f) { targetAlpha = 0f; } else { // Add a short delay before we start fading in case there's another Say command in the next frame or two. // This avoids a noticeable flicker between consecutive Say commands. fadeCoolDownTimer = Mathf.Max(0f, fadeCoolDownTimer - Time.deltaTime); } CanvasGroup canvasGroup = GetCanvasGroup(); float fadeDuration = GetSayDialog().fadeDuration; if (fadeDuration <= 0f) { canvasGroup.alpha = targetAlpha; } else { float delta = (1f / fadeDuration) * Time.deltaTime; float alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, delta); canvasGroup.alpha = alpha; if (alpha <= 0f) { // Deactivate dialog object once invisible gameObject.SetActive(false); } } } public virtual void SetCharacter(Character character, Flowchart flowchart = null) { if (character == null) { if (characterImage != null) { characterImage.gameObject.SetActive(false); } if (nameText != null) { nameText.text = ""; } speakingCharacter = null; } else { Character prevSpeakingCharacter = speakingCharacter; speakingCharacter = character; // Dim portraits of non-speaking characters foreach (Stage s in Stage.activeStages) { if (s.dimPortraits) { foreach (Character c in s.charactersOnStage) { if (prevSpeakingCharacter != speakingCharacter) { if (c != speakingCharacter) { Portrait.SetDimmed(c, s, true); } else { Portrait.SetDimmed(c, s, false); } } } } } string characterName = character.nameText; if (characterName == "") { // Use game object name as default characterName = character.name; } if (flowchart != null) { characterName = flowchart.SubstituteVariables(characterName); } SetCharacterName(characterName, character.nameColor); } } public virtual void SetCharacterImage(Sprite image) { if (characterImage == null) { return; } if (image != null) { characterImage.sprite = image; characterImage.gameObject.SetActive(true); } else { characterImage.gameObject.SetActive(false); if (startStoryTextWidth != 0) { storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, startStoryTextInset, startStoryTextWidth); } } // Adjust story text box to not overlap image rect if (fitTextWithImage && storyText != null && characterImage.gameObject.activeSelf) { if (startStoryTextWidth == 0) { startStoryTextWidth = storyText.rectTransform.rect.width; startStoryTextInset = storyText.rectTransform.offsetMin.x; } // Clamp story text to left or right depending on relative position of the character image if (storyText.rectTransform.position.x < characterImage.rectTransform.position.x) { storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, startStoryTextInset, startStoryTextWidth - characterImage.rectTransform.rect.width); } else { storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, startStoryTextInset, startStoryTextWidth - characterImage.rectTransform.rect.width); } } } public virtual void SetCharacterName(string name, Color color) { if (nameText != null) { nameText.text = name; nameText.color = color; } } public virtual void Clear() { ClearStoryText(); // Kill any active write coroutine StopAllCoroutines(); } protected virtual void ClearStoryText() { if (storyText != null) { storyText.text = ""; } } public static void StopPortraitTweens() { // Stop all tweening portraits foreach( Character c in Character.activeCharacters ) { if (c.state.portraitImage != null) { if (LeanTween.isTweening(c.state.portraitImage.gameObject)) { LeanTween.cancel(c.state.portraitImage.gameObject, true); Portrait.SetRectTransform(c.state.portraitImage.rectTransform, c.state.position); if (c.state.dimmed == true) { c.state.portraitImage.color = new Color(0.5f, 0.5f, 0.5f, 1f); } else { c.state.portraitImage.color = Color.white; } } } } } } }
using System; using System.Globalization; //for NumberFormatInfo using TestLibrary; /// <summary> /// UInt16.System.IConvertible.ToString(string, IFormatProvider) /// Converts the numeric value of this instance to its equivalent string representation /// using the specified format and culture-specific format information. /// </summary> public class UInt16ToString { public static int Main() { UInt16ToString testObj = new UInt16ToString(); TestLibrary.TestFramework.BeginTestCase("for method: UInt16.System.ToString(string, IFormatProvider)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal &= DoPosTest("PosTest1: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PostTest1", UInt16.MinValue, "X", "0", CurrentNFI); retVal &= DoPosTest("PosTest2: Value is UInt16 integer, format is hexadecimal \"X\".", "PostTest2", 8542, "X", "215E", CurrentNFI); retVal &= DoPosTest("PosTest3: Value is UInt16.MaxValue, format is hexadecimal \"X\".", "PostTest3", UInt16.MaxValue, "X", "FFFF", CurrentNFI); retVal &= DoPosTest("PosTest4: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PosTest4", UInt16.MinValue, "X", "0", CustomNFI); retVal &= DoPosTest("PosTest5: Value is UInt16 integer, format is general \"G\".", "PosTest5", 5641, "G", "5641", CustomNFI); retVal &= DoPosTest("PosTest6: Value is UInt16.MaxValue, format is general \"G\".", "PosTest6", UInt16.MaxValue, "G", "65535", CustomNFI); retVal &= DoPosTest("PosTest7: Value is UInt16 integer, format is currency \"C\".", "PosTest7", 8423, "C", "84.23,000USD", CustomNFI); retVal &= DoPosTest("PosTest8: Value is UInt16.MaxValue, format is currency \"C\".", "PosTes8", UInt16.MaxValue, "C", "6.55.35,000USD", CustomNFI); retVal &= DoPosTest("PosTest9: Value is UInt16.MinValue, format is currency \"C\".", "PosTes9", UInt16.MinValue, "C", "0,000USD", CustomNFI); retVal &= DoPosTest("PosTest10: Value is UInt16 integer, format is decimal \"D\".", "PosTest10", 2351, "D", "2351", CustomNFI); retVal &= DoPosTest("PosTest11: Value is UInt16.MaxValue integer, format is decimal \"D\".", "PosTest11", UInt16.MaxValue, "D", "65535", CustomNFI); retVal &= DoPosTest("PosTest12: Value is UInt16.MinValue integer, format is decimal \"D\".", "PosTest12", UInt16.MinValue, "D", "0", CustomNFI); retVal &= DoPosTest("PosTest13: Value is UInt16 integer, format is decimal \"E\".", "PosTest13", 2351, "E", TestLibrary.Utilities.IsWindows ? "2,351000E++003" : "2,351000E3", CustomNFI); retVal &= DoPosTest("PosTest14: Value is UInt16.MaxValue integer, format is decimal \"E\".", "PosTest14", UInt16.MaxValue, "E", TestLibrary.Utilities.IsWindows ? "6,553500E++004" : "6,553500E4", CustomNFI); retVal &= DoPosTest("PosTest15: Value is UInt16.MinValue integer, format is decimal \"E\".", "PosTest15", UInt16.MinValue, "E", TestLibrary.Utilities.IsWindows ? "0,000000E++000" : "0,000000E0", CustomNFI); retVal &= DoPosTest("PosTest16: Value is UInt16 integer, format is decimal \"F\".", "PosTest16", 2341, "F", "2341,000", CustomNFI); retVal &= DoPosTest("PosTest17: Value is UInt16 integer, format is decimal \"P\".", "PosTest17", 2341, "P", "234,100,0000~", CustomNFI); retVal &= DoPosTest("PosTest18: Value is UInt16 integer, format is decimal \"N\".", "PosTest18", 2341, "N", "23#41,000", CustomNFI); retVal &= DoPosTest("PosTest19: Value is UInt16 integer, format is decimal \"N\".", "PosTest19", 2341, null, "2341", CustomNFI); TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #endregion #region Helper method for tests public bool DoPosTest(string testDesc, string id, UInt16 uintA, string format, String expectedValue, NumberFormatInfo _NFI) { bool retVal = true; string errorDesc; string actualValue; TestLibrary.TestFramework.BeginScenario(testDesc); try { actualValue = uintA.ToString(format, _NFI); if (actualValue != expectedValue) { errorDesc = string.Format("The string representation of {0} is not the value {1} as expected: actual({2})", uintA, expectedValue, actualValue); errorDesc += "\nThe format info is \"" + ((format == null) ? "null" : format) + "\" speicifed"; TestLibrary.TestFramework.LogError(id + "_001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe UInt16 integer is " + uintA + ", format info is \"" + format + "\" speicifed."; TestLibrary.TestFramework.LogError(id + "_002", errorDesc); retVal = false; } return retVal; } #endregion #region Private Methods private NumberFormatInfo CurrentNFI = CultureInfo.CurrentCulture.NumberFormat; private NumberFormatInfo nfi = null; private NumberFormatInfo CustomNFI { get { if (null == nfi) { nfi = new CultureInfo(CultureInfo.CurrentCulture.Name).NumberFormat; //For "G" // NegativeSign, NumberDecimalSeparator, NumberDecimalDigits, PositiveSign nfi.NegativeSign = "@"; //Default: "-" nfi.NumberDecimalSeparator = ","; //Default: "." nfi.NumberDecimalDigits = 3; //Default: 2 nfi.PositiveSign = "++"; //Default: "+" //For "E" // PositiveSign, NegativeSign, and NumberDecimalSeparator. // If precision specifier is omitted, a default of six digits after the decimal point is used. //For "R" // NegativeSign, NumberDecimalSeparator and PositiveSign //For "X", The result string isn't affected by the formatting information of the current NumberFormatInfo //For "C" // CurrencyPositivePattern, CurrencySymbol, CurrencyDecimalDigits, CurrencyDecimalSeparator, CurrencyGroupSeparator, CurrencyGroupSizes, NegativeSign and CurrencyNegativePattern nfi.CurrencyDecimalDigits = 3; //Default: 2 nfi.CurrencyDecimalSeparator = ","; //Default: "," nfi.CurrencyGroupSeparator = "."; //Default: "." nfi.CurrencyGroupSizes = new int[] { 2 }; //Default: new int[]{3} nfi.CurrencyNegativePattern = 2; //Default: 0 nfi.CurrencyPositivePattern = 1; //Default: 0 nfi.CurrencySymbol = "USD"; //Default: "$" //For "D" // NegativeSign //For "E" // PositiveSign, NumberDecimalSeparator and NegativeSign. // If precision specifier is omitted, a default of six digits after the decimal point is used. nfi.PositiveSign = "++"; //Default: "+" nfi.NumberDecimalSeparator = ","; //Default: "." //For "F" // NumberDecimalDigits, and NumberDecimalSeparator and NegativeSign. nfi.NumberDecimalDigits = 3; //Default: 2 //For "N" // NumberGroupSizes, NumberGroupSeparator, NumberDecimalSeparator, NumberDecimalDigits, NumberNegativePattern and NegativeSign. nfi.NumberGroupSizes = new int[] { 2 }; //Default: 3 nfi.NumberGroupSeparator = "#"; //Default: "," //For "P" // PercentPositivePattern, PercentNegativePattern, NegativeSign, PercentSymbol, PercentDecimalDigits, PercentDecimalSeparator, PercentGroupSeparator and PercentGroupSizes nfi.PercentPositivePattern = 1; //Default: 0 nfi.PercentNegativePattern = 2; //Default: 0 nfi.PercentSymbol = "~"; //Default: "%" nfi.PercentDecimalDigits = 4; //Default: 2 nfi.PercentDecimalSeparator = ","; //Default: "." nfi.PercentGroupSizes[0] = 2; //Default: 3 nfi.PercentGroupSeparator = ","; } return nfi; } } #endregion #region Negative tests //FormatException public bool NegTest1() { const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: The format parameter is invalid -- \"R\". "; CultureInfo culture = CultureInfo.CurrentCulture; return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "39", "40", "R", culture); } public bool NegTest2() { const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: The format parameter is invalid -- \"r\". "; CultureInfo culture = CultureInfo.CurrentCulture; return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "41", "42", "r", culture); } public bool NegTest3() { const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: The format parameter is invalid -- \"z\". "; CultureInfo culture = CultureInfo.CurrentCulture; return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "43", "44", "z", culture); } #endregion #region Helper methods for negative tests public bool DoInvalidFormatTest(string testId, string testDesc, string errorNum1, string errorNum2, string format, CultureInfo culture) { bool retVal = true; string errorDesc; IFormatProvider provider; UInt16 uintA = (UInt16)(TestLibrary.Generator.GetInt32() % (UInt16.MaxValue + 1)); TestLibrary.TestFramework.BeginScenario(testDesc); try { provider = (IFormatProvider)culture.NumberFormat; uintA.ToString(format, provider); errorDesc = "FormatException is not thrown as expected."; errorDesc = string.Format("\nUInt16 value is {0}, format string is {1} and the culture is {3}.", uintA, format, culture.Name); TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc); retVal = false; } catch (FormatException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc = string.Format("\nUInt16 value is {0}, format string is {1} and the culture is {3}.", uintA, format, culture.Name); TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } #endregion }
using System; using System.Collections.Generic; using System.Reactive.Concurrency; using System.Threading; using System.Threading.Tasks; namespace BFF.DataVirtualizingCollection { /// <summary> /// Lets you configure the page loading behavior. /// Here you can turn the preloading on or off. Preloading means that neighboring pages from requested pages are loaded as well, assuming that they'll be requested soon. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IPageLoadingBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// No preloading. Pages are loaded only as soon as an item of the page is requested. /// </summary> IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonPreloading(); /// <summary> /// Pages are loaded as soon as an item of the page is requested or as soon as a neighboring page is loaded. /// Per default the initially configured background scheduler is taken for the preloads. /// </summary> /// <param name="preloadingPlaceholderFactory">Initially preloaded pages are filled with placeholders.</param> IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> Preloading( Func<int, int, TItem> preloadingPlaceholderFactory); /// <summary> /// Pages are loaded as soon as an item of the page is requested or as soon as a neighboring page is loaded. /// </summary> /// <param name="preloadingPlaceholderFactory">Initially preloaded pages are filled with placeholders.</param> /// <param name="preloadingBackgroundScheduler">A scheduler exclusively for preloading pages.</param> IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> Preloading( Func<int, int, TItem> preloadingPlaceholderFactory, IScheduler preloadingBackgroundScheduler); } /// <summary> /// Lets you configure the page holding behavior. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IPageHoldingBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// In this mode pages are loaded on demand. However, once loaded the pages are hold in memory until the data virtualizing collection is reset or disposed. /// </summary> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> Hoarding(); /// <summary> /// If the page limit is reached then the page which is least recently used will be chosen for removal. /// </summary> /// <param name="pageLimit">Has to be greater than zero (with preloading greater than two) in order to maintain at least one page in the page store (when preloading is active, then the neighbors of the most recently requested page are maintained as well).</param> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> LeastRecentlyUsed( int pageLimit); /// <summary> /// If the page limit is reached then the pages (amount: removal buffer plus one) which are least recently used will be chosen for removal. /// </summary> /// <param name="pageLimit">Has to be greater than zero (with preloading greater than two) in order to maintain at least one page in the page store (when preloading is active, then the neighbors of the most recently requested page are maintained as well).</param> /// <param name="removalCount">Has to be in between one and the page limit minus one (so at least one page remains). /// With active preloading the removal count cannot be greater than the page limit minus three.</param> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> LeastRecentlyUsed( int pageLimit, int removalCount); /// <summary> /// With this function you can provide a custom page-removal strategy. /// You'll get an observable which emits all element requests in form of a key to the page and the element's index inside of the page. /// You'll have to return an observable which emits page-removal requests. You can request to remove several pages at once. /// </summary> IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> CustomPageRemovalStrategy( Func<IObservable<(int PageKey, int PageIndex)>, IObservable<IReadOnlyList<int>>> pageReplacementStrategyFactory); } /// <summary> /// Lets you configure the fetcher (page and count) kind and lets you also provide appropriate fetchers as well. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IFetchersKindCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// You have to provide non-task-based (synchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">You have to provide a lambda function which gets the count of all elements in the backend.</param> [Obsolete("Please use the overload with CancellationToken parameters (which can be ignored if not required). This function will be removed in next major release.")] IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonTaskBasedFetchers( Func<int, int, TItem[]> pageFetcher, Func<int> countFetcher); /// <summary> /// You have to provide task-based (asynchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">You have to provide a lambda function which gets the count of all elements in the backend.</param> [Obsolete("Please use the overload with CancellationToken parameters (which can be ignored if not required). This function will be removed in next major release.")] IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> TaskBasedFetchers( Func<int, int, Task<TItem[]>> pageFetcher, Func<Task<int>> countFetcher); /// <summary> /// You have to provide non-task-based (synchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size, third parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">The parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which gets the count of all elements in the backend.</param> IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> NonTaskBasedFetchers( Func<int, int, CancellationToken, TItem[]> pageFetcher, Func<CancellationToken, int> countFetcher); /// <summary> /// You have to provide task-based (asynchronous) fetchers. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size, third parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">The parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which gets the count of all elements in the backend.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> TaskBasedFetchers( Func<int, int, CancellationToken, Task<TItem[]>> pageFetcher, Func<CancellationToken, Task<int>> countFetcher); /// <summary> /// You have to provide a enumerable-based (asynchronous) page fetcher and a task-based (asynchronous) count fetcher. /// The page fetcher has to get a page from the backend based on the provided offset and size. The count fetcher has to get the count of the items in the backend. /// </summary> /// <param name="pageFetcher">First parameter is the offset, second parameter is the size, third parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which given the parameters returns the expected page from the backend.</param> /// <param name="countFetcher">The parameter will signal cancellation when the result of the fetch won't be used. You have to provide a lambda function which gets the count of all elements in the backend.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> AsyncEnumerableBasedFetchers( Func<int, int, CancellationToken, IAsyncEnumerable<TItem>> pageFetcher, Func<CancellationToken, Task<int>> countFetcher); } /// <summary> /// Lets you configure the asynchronous index access options. /// Asynchronous meas the if the page still needs to be loaded a placeholder will be provided. As soon as the page is loaded a notification is emitted which states that the entry of the index arrived. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// Page request are triggered right after the generation of the page's placeholders. /// <para/> /// This is the default behavior. You won't need to call it explicitly. /// </summary> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ImmediatePageRequests(); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// <para/> /// Default throttling due time is set to 200 ms and default scheduler is the same as for the page requests. /// </summary> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// <para/> /// Default scheduler is the same as for the page requests. /// </summary> /// <param name="throttleDueTime">Time span which has to pass by without new page request until the collected page requests are triggered.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(TimeSpan throttleDueTime); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// <para/> /// Default throttling due time is set to 200 ms. /// </summary> /// <param name="pageRequestBackgroundScheduler">A scheduler exclusively for page request delaying.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(IScheduler pageRequestBackgroundScheduler); /// <summary> /// Instead of triggering the page requests right away, they are delayed in throttling (Rx) manner and then triggered in Last In First Out (LIFO)/ stack-based manner. /// </summary> /// <param name="throttleDueTime">Time span which has to pass by without new page request until the collected page requests are triggered.</param> /// <param name="pageRequestBackgroundScheduler">A scheduler exclusively for page request delaying.</param> IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> ThrottledLifoPageRequests(TimeSpan throttleDueTime, IScheduler pageRequestBackgroundScheduler); /// <summary> /// If item of requested index isn't loaded yet the collections will return a placeholder instead and emit a notification as soon as it arrives. /// Per default the initially configured background scheduler is taken for page and count fetches. /// </summary> /// <param name="placeholderFactory">You have to provide a factory lambda function which returns a placeholder. /// The first parameter is the page key (index of pages) and the second is the page index (index of items inside the page).</param> TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory); /// <summary> /// If item of requested index isn't loaded yet the collections will return a placeholder instead and emit a notification as soon as it arrives. /// Per default the initially configured background scheduler is taken for count fetches. /// </summary> /// <param name="placeholderFactory">You have to provide a factory lambda function which returns a placeholder. /// The first parameter is the page key (index of pages) and the second is the page index (index of items inside the page).</param> /// <param name="pageBackgroundScheduler">A scheduler exclusively for page fetches.</param> TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory, IScheduler pageBackgroundScheduler); /// <summary> /// If item of requested index isn't loaded yet the collections will return a placeholder instead and emit a notification as soon as it arrives. /// </summary> /// <param name="placeholderFactory">You have to provide a factory lambda function which returns a placeholder. /// The first parameter is the page key (index of pages) and the second is the page index (index of items inside the page).</param> /// <param name="pageBackgroundScheduler">A scheduler exclusively for page fetches.</param> /// <param name="countBackgroundScheduler">A scheduler exclusively for count fetches.</param> TVirtualizationKind AsyncIndexAccess( Func<int, int, TItem> placeholderFactory, IScheduler pageBackgroundScheduler, IScheduler countBackgroundScheduler); } /// <summary> /// Lets you configure whether the index access should be synchronous or asynchronous. /// Synchronous means that if the index access will wait actively until the entry is provided even if the page still has to be loaded. /// Asynchronous meas the if the page still needs to be loaded a placeholder will be provided. As soon as the page is loaded a notification is emitted which states that the entry of the index arrived. /// </summary> /// <typeparam name="TItem">Item type.</typeparam> /// <typeparam name="TVirtualizationKind">IDataVirtualizingCollection or ISlidingWindow.</typeparam> public interface IIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> : IAsyncOnlyIndexAccessBehaviorCollectionBuilder<TItem, TVirtualizationKind> { /// <summary> /// If item of requested index isn't loaded yet the collections will wait actively and return as soon as it arrives. /// Depending on the latency of the page fetcher it may result in freezes of the application. /// </summary> TVirtualizationKind SyncIndexAccess(); } }
using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Reflection; using System.Text; using System.Web; using System.Web.UI.WebControls; using Rainbow.Framework.Data; using Rainbow.Framework.Security; using Rainbow.Framework.Settings; using Rainbow.Framework.Web.UI.WebControls; using System.Collections.Generic; using Rainbow.Framework.Providers.RainbowRoleProvider; namespace Rainbow.Framework.Helpers { /// <summary> /// SearchHelper /// Original ideas from Jakob Hansen. /// Reflection and pluggable interface by Manu /// </summary> public class SearchHelper { /// <summary> /// Searches the portal. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="userID">The user ID.</param> /// <param name="searchModule">The search module.</param> /// <param name="searchString">The search string.</param> /// <param name="searchField">The search field.</param> /// <param name="sortField">The sort field.</param> /// <param name="sortDirection">The sort direction.</param> /// <param name="topicName">Name of the topic.</param> /// <param name="addExtraSQL">The add extra SQL.</param> /// <returns> /// A System.Data.SqlClient.SqlDataReader value... /// </returns> // TODO --> [Obsolete("Replace me")] public static SqlDataReader SearchPortal(int portalID, Guid userID, string searchModule, string searchString, string searchField, string sortField, string sortDirection, string topicName, string addExtraSQL) { StringBuilder select; select = new StringBuilder(string.Empty, 2048); searchString = searchString.Replace('?','_'); searchString = searchString.Replace(" AND "," +"); searchString = searchString.Replace(" NOT "," -"); searchString = searchString.Replace(" OR "," "); searchString = searchString.Replace(" NEAR "," "); if (addExtraSQL.Length != 0) { if (searchString == string.Empty) searchString = "AddExtraSQL:" + addExtraSQL; else searchString = "AddExtraSQL:" + addExtraSQL + " SearchString:" + searchString; } // TODO: This should be cached // move the code in a self cached property... StringBuilder modulesList = new StringBuilder(); if (searchModule == string.Empty) { // Search all using (SqlDataReader drModules = GetSearchableModules(portalID)) { try { while (drModules.Read()) { modulesList.Append(drModules["AssemblyName"].ToString()); modulesList.Append(";"); modulesList.Append(drModules["ClassName"].ToString()); modulesList.Append(";"); } } finally { drModules.Close(); //by Manu, fixed bug 807858 } } } else { modulesList.Append(searchModule); modulesList.Append(";"); } // Builds searchables modules list (Assembly, Class) string[] arrModulesList = modulesList.ToString().TrimEnd(';').Split(';'); // Cycle trhough modules and get search string ArrayList slqSelectQueries = new ArrayList(); int modulesCount = arrModulesList.GetUpperBound(0); for (int i = 0; i <= modulesCount; i = i + 2) { // Use reflection Assembly a; //http://sourceforge.net/tracker/index.php?func=detail&aid=899424&group_id=66837&atid=515929 string assemblyName = Path.WebPathCombine(Path.ApplicationRoot, "bin", arrModulesList[i]); assemblyName = HttpContext.Current.Server.MapPath(assemblyName); a = Assembly.LoadFrom(assemblyName); // ISearchable ISearchable p = (ISearchable) a.CreateInstance(arrModulesList[i+1]); if (p != null) { //Call a method with arguments object [] args = new object [] {portalID, userID, searchString, searchField}; string currentSearch = (string) p.GetType().InvokeMember("SearchSqlSelect", BindingFlags.Default | BindingFlags.InvokeMethod, null, p, args); if (currentSearch.Length != 0 && currentSearch != null) slqSelectQueries.Add(currentSearch); } } int queriesCount = slqSelectQueries.Count; for (int i = 0; i < queriesCount; i++) { select.Append(slqSelectQueries[i]); if (i < (queriesCount - 1)) //Avoid last select.Append("\r\n\r\nUNION\r\n\r\n"); } if (sortField.Length != 0) { if (sortDirection == string.Empty) { if (sortField == "CreatedDate") sortDirection = "DESC"; else sortDirection = "ASC"; } select.Append(" ORDER BY " + sortField + " " + sortDirection); } //Topic implementation if (topicName.Length != 0) { select.Replace("%TOPIC_PLACEHOLDER_JOIN%", "INNER JOIN rb_ModuleSettings modSet ON mod.ModuleID = modSet.ModuleID"); select.Replace("%TOPIC_PLACEHOLDER%", " AND (modSet.SettingName = 'TopicName' AND modSet.SettingValue='" + topicName + "')"); } else { select.Replace("%TOPIC_PLACEHOLDER_JOIN%", null); select.Replace("%TOPIC_PLACEHOLDER%", null); } string selectSQL = select.ToString(); //string connectionString = Portal.ConnectionString; string connectionString = Config.ConnectionString; SqlConnection sqlConnection = new SqlConnection(connectionString); SqlCommand sqlCommand = new SqlCommand(selectSQL, sqlConnection); try { sqlCommand.Connection.Open(); return sqlCommand.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception e) { ErrorHandler.Publish(LogLevel.Error, "Error in Search:SearchPortal()-> " + e.ToString() + " " + select.ToString(), e); throw new Exception("Error in Search selection."); } } /// <summary> /// Adds the modules that can be searched to the dropdown list. /// First entry is always the "All" /// </summary> /// <param name="portalID">The PortalID</param> /// <param name="ddList">The DropDown List</param> public static void AddToDropDownList(int portalID, ref DropDownList ddList) { using (SqlDataReader drModules = GetSearchableModules(portalID)) { ddList.Items.Add(new ListItem(General.GetString("ALL", "All", null), string.Empty)); //TODO JLH!! Should be read from context!! try { while (drModules.Read()) { ddList.Items.Add(new ListItem(drModules["FriendlyName"].ToString(), drModules["AssemblyName"].ToString() + ";" + drModules["ClassName"].ToString())); } } finally { drModules.Close(); //by Manu, fixed bug 807858 } } } /// <summary> /// The GetSearchableModules function returns a list of all Searchable modules /// </summary> /// <param name="portalID"></param> /// <returns></returns> // TODO --> [Obsolete("Replace me")] public static SqlDataReader GetSearchableModules(int portalID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSearchableModules", myConnection); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4); parameterPortalID.Value = portalID; myCommand.Parameters.Add(parameterPortalID); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // return the datareader return result; } /// <summary> /// Add most of the WHERE part to a search sql /// </summary> /// <param name="portalID">portalID</param> /// <param name="userID">userID</param> /// <param name="select">SQL string to add sql to</param> /// <param name="fieldName">Field to do IS NOT NULL test on</param> public static void AddSharedSQL(int portalID, int userID, ref StringBuilder select, string fieldName) { HttpContext context=HttpContext.Current; IList<RainbowRole> asRoles = PortalSecurity.GetRoles(); /* if (userID>-1) select.Append(", rb_Roles, rb_UserRoles"); select.Append(" WHERE itm." + fieldName + " IS NOT NULL"); select.Append(" AND itm.ModuleID = mod.ModuleID"); select.Append(" AND mod.ModuleDefID = modDef.ModuleDefID"); select.Append(" AND modDef.PortalID = " + portalID.ToString()); select.Append(" AND tab.PortalID = " + portalID.ToString()); select.Append(" AND tab.TabID = mod.TabID"); */ if (userID>-1) { //select.Append(" AND rb_UserRoles.UserID = " + userID.ToString()); //select.Append(" AND rb_UserRoles.RoleID = rb_Roles.RoleID"); //select.Append(" AND rb_Roles.PortalID = " + portalID.ToString()); select.Append(" AND ((mod.AuthorizedViewRoles LIKE '%All Users%') "); if (context.Request.IsAuthenticated) // - no tenia en cuenta el rol "Authenticated users" select.Append(" OR (mod.AuthorizedViewRoles LIKE '%Authenticated Users%')"); else select.Append(" OR (mod.AuthorizedViewRoles LIKE '%Unauthenticated Users%')"); foreach (RainbowRole sRole in asRoles) select.Append(" OR (mod.AuthorizedViewRoles LIKE '%" + sRole.Name + "%')"); select.Append(")"); select.Append(" AND ((tab.AuthorizedRoles LIKE '%All Users%')"); if (context.Request.IsAuthenticated) // - no tenia en cuenta el rol "Authenticated users" select.Append(" OR (tab.AuthorizedRoles LIKE '%Authenticated Users%')"); foreach (RainbowRole sRole in asRoles) select.Append(" OR (tab.AuthorizedRoles LIKE '%" + sRole.Name + "%')"); select.Append(")"); } else { select.Append(" AND (mod.AuthorizedViewRoles LIKE '%All Users%')"); select.Append(" AND (tab.AuthorizedRoles LIKE '%All Users%')"); } } // old search /* public static void AddSharedSQL(int portalID, int userID, ref StringBuilder select, string fieldName) { if (userID>-1) select.Append(", rb_Roles, rb_UserRoles"); select.Append(" WHERE itm." + fieldName + " IS NOT NULL"); select.Append(" AND itm.ModuleID = mod.ModuleID"); select.Append(" AND mod.ModuleDefID = modDef.ModuleDefID"); select.Append(" AND modDef.PortalID = " + portalID.ToString()); select.Append(" AND tab.PortalID = " + portalID.ToString()); select.Append(" AND tab.TabID = mod.TabID"); if (userID>-1) { select.Append(" AND rb_UserRoles.UserID = " + userID.ToString()); select.Append(" AND rb_UserRoles.RoleID = rb_Roles.RoleID"); select.Append(" AND rb_Roles.PortalID = " + portalID.ToString()); select.Append(" AND ((mod.AuthorizedViewRoles LIKE '%All Users%') OR (mod.AuthorizedViewRoles LIKE '%'+rb_Roles.RoleName+'%'))"); select.Append(" AND ((tab.AuthorizedRoles LIKE '%All Users%') OR (tab.AuthorizedRoles LIKE '%'+rb_Roles.RoleName+'%'))"); } else { select.Append(" AND (mod.AuthorizedViewRoles LIKE '%All Users%')"); select.Append(" AND (tab.AuthorizedRoles LIKE '%All Users%')"); } } */ /// <summary> /// Creates search sql to the WHERE clause /// </summary> /// <param name="arrFields">Array of fieldnames to search e.g. ArrayList("fld1", "fld2")</param> /// <param name="strSearchwords">Whatever words the user entered to perform the search with e.g. "smukke jakob". Note: Must be seperated by spaces!</param> /// <param name="useAnd">Controls wether all or only one word in the searchstring strSearchwords should result in a hit.</param> /// <returns> /// (fld1 LIKE '%smukke%' OR fld2 LIKE '%smukke%') AND (fld1 LIKE '%jakob%' OR fld2 LIKE '%jakob%') /// </returns> public static string CreateTestSQL(ArrayList arrFields, string strSearchwords, bool useAnd) { Int32 i = 0; Int32 j = 0; string [] arrWord; string strWord, strTmp, strNot; string strBoolOp; string vbCrLf = "\r\n"; if (useAnd) strBoolOp = "AND"; else strBoolOp = "OR"; strTmp = string.Empty; if (strSearchwords.IndexOf('"') > -1) MarkPhrase(ref strSearchwords); strSearchwords = strSearchwords.Replace(" +", " "); arrWord = strSearchwords.Split(' '); foreach (string strItem in arrWord) { strWord = strItem; strWord = strWord.Replace('=', ' '); // dephrase! if (strWord.StartsWith("-")) { strNot = "NOT"; strWord = strWord.Substring(1); } else strNot = string.Empty; if (strTmp == string.Empty) strTmp = strNot + "("; if (j>0) strTmp = strTmp + ")" + vbCrLf + " " + strBoolOp + " " + strNot + "("; j = j + 1; foreach (string strField in arrFields) { if (i>0) strTmp = strTmp + " OR "; strTmp = strTmp + strField + " LIKE N'%" + strWord + "%'"; i = i + 1; } i = 0; } return "(" + strTmp + "))"; } /// <summary> /// A phrase is marked with '"' as a stating and ending charater. /// If a phrase is discovered the '"' is replaced with '='. /// </summary> /// <param name="strWords">The staring of words that might contain a phrase</param> public static void MarkPhrase(ref string strWords) { int idxStartQuote = strWords.IndexOf('"'); int idxEndQuote = strWords.IndexOf('"', idxStartQuote+1); if (idxEndQuote == -1) return; string phrase; phrase = strWords.Substring(idxStartQuote+1, (idxEndQuote-idxStartQuote)-1); phrase = phrase.Replace(' ', '='); strWords = strWords.Substring(0, idxStartQuote) + phrase + strWords.Substring(idxEndQuote+1); } /// <summary> /// DeleteBeforeBody /// </summary> /// <param name="strHtml">strHtml</param> /// <returns></returns> public static string DeleteBeforeBody(string strHtml) { int idxBody = strHtml.ToLower().IndexOf("<body"); // Get rid of anything before the body tag if (idxBody != -1) strHtml = strHtml.Substring(idxBody); return strHtml; } /// <summary> /// Gets the topic list. /// </summary> /// <param name="portalID">The portal ID.</param> /// <returns>A string[] value...</returns> public static string[] GetTopicList(int portalID) { ArrayList al = new ArrayList(); al.Add(General.GetString("PORTALSEARCH_ALL", "All", null)); SqlDataReader dr = DBHelper.GetDataReader ("SELECT DISTINCT rb_ModuleSettings.SettingValue " + "FROM rb_ModuleSettings INNER JOIN rb_Modules ON rb_ModuleSettings.ModuleID = rb_Modules.ModuleID INNER JOIN rb_ModuleDefinitions ON rb_Modules.ModuleDefID = rb_ModuleDefinitions.ModuleDefID " + "WHERE (rb_ModuleDefinitions.PortalID = " + portalID.ToString() + ") AND (rb_ModuleSettings.SettingName = N'TopicName') AND (rb_ModuleSettings.SettingValue <> '') ORDER BY rb_ModuleSettings.SettingValue"); try { while(dr.Read()) { al.Add(dr["SettingValue"].ToString()); } } finally { dr.Close(); //by Manu fix close bug #2 found } return (string[]) al.ToArray(typeof(string)); } } }
using System.Collections.Generic; using System.Linq; using Content.Server.GameTicking; using Content.Server.Ghost.Components; using Content.Server.Mind; using Content.Server.Mind.Components; using Content.Server.Players; using Content.Server.Visible; using Content.Server.Warps; using Content.Shared.Actions; using Content.Shared.Examine; using Content.Shared.Follower; using Content.Shared.Ghost; using Content.Shared.MobState.Components; using Content.Shared.Movement.EntitySystems; using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Timing; namespace Content.Server.Ghost { [UsedImplicitly] public sealed class GhostSystem : SharedGhostSystem { [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly GameTicker _ticker = default!; [Dependency] private readonly MindSystem _mindSystem = default!; [Dependency] private readonly SharedActionsSystem _actions = default!; [Dependency] private readonly VisibilitySystem _visibilitySystem = default!; [Dependency] private readonly EntityLookupSystem _lookup = default!; [Dependency] private readonly FollowerSystem _followerSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<GhostComponent, ComponentStartup>(OnGhostStartup); SubscribeLocalEvent<GhostComponent, ComponentShutdown>(OnGhostShutdown); SubscribeLocalEvent<GhostComponent, ExaminedEvent>(OnGhostExamine); SubscribeLocalEvent<GhostComponent, MindRemovedMessage>(OnMindRemovedMessage); SubscribeLocalEvent<GhostComponent, MindUnvisitedMessage>(OnMindUnvisitedMessage); SubscribeLocalEvent<GhostOnMoveComponent, RelayMoveInputEvent>(OnRelayMoveInput); SubscribeNetworkEvent<GhostWarpsRequestEvent>(OnGhostWarpsRequest); SubscribeNetworkEvent<GhostReturnToBodyRequest>(OnGhostReturnToBodyRequest); SubscribeNetworkEvent<GhostWarpToLocationRequestEvent>(OnGhostWarpToLocationRequest); SubscribeNetworkEvent<GhostWarpToTargetRequestEvent>(OnGhostWarpToTargetRequest); SubscribeLocalEvent<GhostComponent, BooActionEvent>(OnActionPerform); } private void OnActionPerform(EntityUid uid, GhostComponent component, BooActionEvent args) { if (args.Handled) return; var ents = _lookup.GetEntitiesInRange(args.Performer, component.BooRadius); var booCounter = 0; foreach (var ent in ents) { var ghostBoo = new GhostBooEvent(); RaiseLocalEvent(ent, ghostBoo); if (ghostBoo.Handled) booCounter++; if (booCounter >= component.BooMaxTargets) break; } args.Handled = true; } private void OnRelayMoveInput(EntityUid uid, GhostOnMoveComponent component, RelayMoveInputEvent args) { // Let's not ghost if our mind is visiting... if (EntityManager.HasComponent<VisitingMindComponent>(uid)) return; if (!EntityManager.TryGetComponent<MindComponent>(uid, out var mind) || !mind.HasMind || mind.Mind!.IsVisitingEntity) return; if (component.MustBeDead && TryComp<MobStateComponent>(uid, out var state) && !state.IsDead()) return; _ticker.OnGhostAttempt(mind.Mind!, component.CanReturn); } private void OnGhostStartup(EntityUid uid, GhostComponent component, ComponentStartup args) { // Allow this entity to be seen by other ghosts. var visibility = EntityManager.EnsureComponent<VisibilityComponent>(component.Owner); _visibilitySystem.AddLayer(visibility, (int) VisibilityFlags.Ghost, false); _visibilitySystem.RemoveLayer(visibility, (int) VisibilityFlags.Normal, false); _visibilitySystem.RefreshVisibility(visibility); if (EntityManager.TryGetComponent(component.Owner, out EyeComponent? eye)) { eye.VisibilityMask |= (uint) VisibilityFlags.Ghost; } component.TimeOfDeath = _gameTiming.RealTime; _actions.AddAction(uid, component.Action, null); } private void OnGhostShutdown(EntityUid uid, GhostComponent component, ComponentShutdown args) { // Perf: If the entity is deleting itself, no reason to change these back. if (!Terminating(uid)) { // Entity can't be seen by ghosts anymore. if (EntityManager.TryGetComponent(component.Owner, out VisibilityComponent? visibility)) { _visibilitySystem.RemoveLayer(visibility, (int) VisibilityFlags.Ghost, false); _visibilitySystem.AddLayer(visibility, (int) VisibilityFlags.Normal, false); _visibilitySystem.RefreshVisibility(visibility); } // Entity can't see ghosts anymore. if (EntityManager.TryGetComponent(component.Owner, out EyeComponent? eye)) { eye.VisibilityMask &= ~(uint) VisibilityFlags.Ghost; } _actions.RemoveAction(uid, component.Action); } } private void OnGhostExamine(EntityUid uid, GhostComponent component, ExaminedEvent args) { var timeSinceDeath = _gameTiming.RealTime.Subtract(component.TimeOfDeath); var deathTimeInfo = timeSinceDeath.Minutes > 0 ? Loc.GetString("comp-ghost-examine-time-minutes", ("minutes", timeSinceDeath.Minutes)) : Loc.GetString("comp-ghost-examine-time-seconds", ("seconds", timeSinceDeath.Seconds)); args.PushMarkup(deathTimeInfo); } private void OnMindRemovedMessage(EntityUid uid, GhostComponent component, MindRemovedMessage args) { DeleteEntity(uid); } private void OnMindUnvisitedMessage(EntityUid uid, GhostComponent component, MindUnvisitedMessage args) { DeleteEntity(uid); } private void OnGhostWarpsRequest(GhostWarpsRequestEvent msg, EntitySessionEventArgs args) { if (args.SenderSession.AttachedEntity is not {Valid: true} entity || !EntityManager.HasComponent<GhostComponent>(entity)) { Logger.Warning($"User {args.SenderSession.Name} sent a {nameof(GhostWarpsRequestEvent)} without being a ghost."); return; } var response = new GhostWarpsResponseEvent(GetLocationNames().ToList(), GetPlayerWarps(entity)); RaiseNetworkEvent(response, args.SenderSession.ConnectedClient); } private void OnGhostReturnToBodyRequest(GhostReturnToBodyRequest msg, EntitySessionEventArgs args) { if (args.SenderSession.AttachedEntity is not {Valid: true} attached || !EntityManager.TryGetComponent(attached, out GhostComponent? ghost) || !ghost.CanReturnToBody || !EntityManager.TryGetComponent(attached, out ActorComponent? actor)) { Logger.Warning($"User {args.SenderSession.Name} sent an invalid {nameof(GhostReturnToBodyRequest)}"); return; } actor.PlayerSession.ContentData()!.Mind?.UnVisit(); } private void OnGhostWarpToLocationRequest(GhostWarpToLocationRequestEvent msg, EntitySessionEventArgs args) { if (args.SenderSession.AttachedEntity is not {Valid: true} attached || !EntityManager.TryGetComponent(attached, out GhostComponent? ghost)) { Logger.Warning($"User {args.SenderSession.Name} tried to warp to {msg.Name} without being a ghost."); return; } if (FindLocation(msg.Name) is { } warp) { EntityManager.GetComponent<TransformComponent>(ghost.Owner).Coordinates = EntityManager.GetComponent<TransformComponent>(warp.Owner).Coordinates; return; } Logger.Warning($"User {args.SenderSession.Name} tried to warp to an invalid warp: {msg.Name}"); } private void OnGhostWarpToTargetRequest(GhostWarpToTargetRequestEvent msg, EntitySessionEventArgs args) { if (args.SenderSession.AttachedEntity is not {Valid: true} attached || !EntityManager.TryGetComponent(attached, out GhostComponent? ghost)) { Logger.Warning($"User {args.SenderSession.Name} tried to warp to {msg.Target} without being a ghost."); return; } if (!EntityManager.EntityExists(msg.Target)) { Logger.Warning($"User {args.SenderSession.Name} tried to warp to an invalid entity id: {msg.Target}"); return; } _followerSystem.StartFollowingEntity(ghost.Owner, msg.Target); } private void DeleteEntity(EntityUid uid) { if (Deleted(uid) || Terminating(uid)) return; if (EntityManager.TryGetComponent<MindComponent?>(uid, out var mind)) _mindSystem.SetGhostOnShutdown(uid, false, mind); EntityManager.DeleteEntity(uid); } private IEnumerable<string> GetLocationNames() { foreach (var warp in EntityManager.EntityQuery<WarpPointComponent>(true)) { if (warp.Location != null) { yield return warp.Location; } } } private WarpPointComponent? FindLocation(string name) { foreach (var warp in EntityManager.EntityQuery<WarpPointComponent>(true)) { if (warp.Location == name) { return warp; } } return null; } private Dictionary<EntityUid, string> GetPlayerWarps(EntityUid except) { var players = new Dictionary<EntityUid, string>(); foreach (var player in _playerManager.Sessions) { if (player.AttachedEntity is {Valid: true} attached) { players.Add(attached, EntityManager.GetComponent<MetaDataComponent>(attached).EntityName); } } players.Remove(except); return players; } } }
using UnityEditor.Experimental.GraphView; using UnityEngine.UIElements; using UnityEngine; using UnityEditor.Experimental.VFX; using System.Collections.Generic; using System.Linq; using System; using System.Collections.ObjectModel; using System.Reflection; using UnityObject = UnityEngine.Object; namespace UnityEditor.VFX.UI { class VFXContextController : VFXNodeController { public new VFXContext model { get { return base.model as VFXContext; } } private List<VFXBlockController> m_BlockControllers = new List<VFXBlockController>(); public ReadOnlyCollection<VFXBlockController> blockControllers { get { return m_BlockControllers.AsReadOnly(); } } protected List<VFXFlowAnchorController> m_FlowInputAnchors = new List<VFXFlowAnchorController>(); public ReadOnlyCollection<VFXFlowAnchorController> flowInputAnchors { get { return m_FlowInputAnchors.AsReadOnly(); } } protected List<VFXFlowAnchorController> m_FlowOutputAnchors = new List<VFXFlowAnchorController>(); public ReadOnlyCollection<VFXFlowAnchorController> flowOutputAnchors { get { return m_FlowOutputAnchors.AsReadOnly(); } } public char letter { get { return model.letter; } set { model.letter = value; } } public override void OnDisable() { if (viewController != null) { UnregisterAnchors(); } if (!object.ReferenceEquals(m_Data, null)) { viewController.UnRegisterNotification(m_Data, DataChanged); m_Data = null; } base.OnDisable(); } private void UnregisterAnchors() { foreach (var anchor in flowInputAnchors) viewController.UnregisterFlowAnchorController(anchor); foreach (var anchor in flowOutputAnchors) viewController.UnregisterFlowAnchorController(anchor); } protected void DataChanged() { NotifyChange(AnyThing); } protected override VFXDataAnchorController AddDataAnchor(VFXSlot slot, bool input, bool hidden) { if (input) { VFXContextDataInputAnchorController anchorController = new VFXContextDataInputAnchorController(slot, this, hidden); return anchorController; } else { VFXContextDataOutputAnchorController anchorController = new VFXContextDataOutputAnchorController(slot, this, hidden); return anchorController; } } VFXData m_Data = null; protected override void ModelChanged(UnityEngine.Object obj) { SyncControllers(); // make sure we listen to the right data if (!object.ReferenceEquals(m_Data, null) && model.GetData() != m_Data) { viewController.UnRegisterNotification(m_Data, DataChanged); m_Data = null; } if (m_Data == null && model.GetData() != null) { m_Data = model.GetData(); viewController.RegisterNotification(m_Data, DataChanged); } viewController.FlowEdgesMightHaveChanged(); base.ModelChanged(obj); } public VFXContextController(VFXModel model, VFXViewController viewController) : base(model, viewController) { UnregisterAnchors(); if (this.model.inputType != VFXDataType.kNone) { for (int slot = 0; slot < this.model.inputFlowSlot.Length; ++slot) { var inAnchor = new VFXFlowInputAnchorController(); inAnchor.Init(this, slot); m_FlowInputAnchors.Add(inAnchor); viewController.RegisterFlowAnchorController(inAnchor); } } if (this.model.outputType != VFXDataType.kNone) { for (int slot = 0; slot < this.model.outputFlowSlot.Length; ++slot) { var outAnchor = new VFXFlowOutputAnchorController(); outAnchor.Init(this, slot); m_FlowOutputAnchors.Add(outAnchor); viewController.RegisterFlowAnchorController(outAnchor); } } SyncControllers(); } public void AddBlock(int index, VFXBlock block) { model.AddChild(block, index); } public void ReorderBlock(int index, VFXBlock block) { if (block.GetParent() == base.model && model.GetIndex(block) < index) { --index; } if (index < 0 || index >= base.model.GetNbChildren()) index = -1; model.AddChild(block, index); } public void RemoveBlock(VFXBlock block) { model.RemoveChild(block); VFXModel.UnlinkModel(block); } public int FindBlockIndexOf(VFXBlockController controller) { return m_BlockControllers.IndexOf(controller); } private void SyncControllers() { var m_NewControllers = new List<VFXBlockController>(); foreach (var block in model.children) { var newController = m_BlockControllers.Find(p => p.model == block); if (newController == null) // If the controller does not exist for this model, create it { newController = new VFXBlockController(block, this); newController.ForceUpdate(); } m_NewControllers.Add(newController); } foreach (var deletedController in m_BlockControllers.Except(m_NewControllers)) { deletedController.OnDisable(); } m_BlockControllers = m_NewControllers; } static VFXBlock DuplicateBlock(VFXBlock block) { var dependencies = new HashSet<ScriptableObject>(); dependencies.Add(block); block.CollectDependencies(dependencies); var duplicated = VFXMemorySerializer.DuplicateObjects(dependencies.ToArray()); VFXBlock result = duplicated.OfType<VFXBlock>().First(); foreach (var slot in result.inputSlots) { slot.UnlinkAll(true, false); } foreach (var slot in result.outputSlots) { slot.UnlinkAll(true, false); } return result; } internal void BlocksDropped(int blockIndex, IEnumerable<VFXBlockController> draggedBlocks, bool copy) { //Sort draggedBlock in the order we want them to appear and not the selected order ( blocks in the same context should appear in the same order as they where relative to each other). draggedBlocks = draggedBlocks.OrderBy(t => t.index).GroupBy(t => t.contextController).SelectMany<IGrouping<VFXContextController, VFXBlockController>, VFXBlockController>(t => t.Select(u => u)); foreach (VFXBlockController draggedBlock in draggedBlocks) { if (copy) { this.AddBlock(blockIndex++, DuplicateBlock(draggedBlock.model)); } else { this.ReorderBlock(blockIndex++, draggedBlock.model); } } } public override IEnumerable<Controller> allChildren { get { return m_BlockControllers.Cast<Controller>(); } } public static bool IsTypeExpandable(System.Type type) { return !type.IsPrimitive && !typeof(UnityObject).IsAssignableFrom(type) && type != typeof(AnimationCurve) && !type.IsEnum && type != typeof(Gradient); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using MICore; using Microsoft.MIDebugEngine.Natvis; namespace Microsoft.MIDebugEngine { // And implementation of IDebugCodeContext2 and IDebugMemoryContext2. // IDebugMemoryContext2 represents a position in the address space of the machine running the program being debugged. // IDebugCodeContext2 represents the starting position of a code instruction. // For most run-time architectures today, a code context can be thought of as an address in a program's execution stream. internal class AD7MemoryAddress : IDebugCodeContext2 { private readonly AD7Engine _engine; private readonly ulong _address; /*OPTIONAL*/ private string _functionName; private IDebugDocumentContext2 _documentContext; public AD7MemoryAddress(AD7Engine engine, ulong address, /*OPTIONAL*/ string functionName) { _engine = engine; _address = address; _functionName = functionName; } internal ulong Address { get { return _address; } } internal AD7Engine Engine { get { return _engine; } } public void SetDocumentContext(IDebugDocumentContext2 docContext) { _documentContext = docContext; } #region IDebugMemoryContext2 Members // Adds a specified value to the current context's address to create a new context. public int Add(ulong dwCount, out IDebugMemoryContext2 newAddress) { newAddress = new AD7MemoryAddress(_engine, (uint)dwCount + _address, null); return Constants.S_OK; } // Compares the memory context to each context in the given array in the manner indicated by compare flags, // returning an index of the first context that matches. public int Compare(enum_CONTEXT_COMPARE contextCompare, IDebugMemoryContext2[] compareToItems, uint compareToLength, out uint foundIndex) { foundIndex = uint.MaxValue; try { for (uint c = 0; c < compareToLength; c++) { AD7MemoryAddress compareTo = compareToItems[c] as AD7MemoryAddress; if (compareTo == null) { continue; } if (!AD7Engine.ReferenceEquals(_engine, compareTo._engine)) { continue; } bool result; switch (contextCompare) { case enum_CONTEXT_COMPARE.CONTEXT_EQUAL: result = (_address == compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN: result = (_address < compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN: result = (_address > compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL: result = (_address <= compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL: result = (_address >= compareTo._address); break; // The debug engine doesn't understand scopes case enum_CONTEXT_COMPARE.CONTEXT_SAME_SCOPE: result = (_address == compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION: if (_address == compareTo._address) { result = true; break; } string funcThis = Engine.GetAddressDescription(_address); if (string.IsNullOrEmpty(funcThis)) { result = false; break; } string funcCompareTo = Engine.GetAddressDescription(compareTo._address); result = (funcThis == funcCompareTo); break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_MODULE: result = (_address == compareTo._address); if (result == false) { DebuggedModule module = _engine.DebuggedProcess.ResolveAddress(_address); if (module != null) { result = module.AddressInModule(compareTo._address); } } break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_PROCESS: result = true; break; default: // A new comparison was invented that we don't support return Constants.E_NOTIMPL; } if (result) { foundIndex = c; return Constants.S_OK; } } return Constants.S_FALSE; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Gets information that describes this context. public int GetInfo(enum_CONTEXT_INFO_FIELDS dwFields, CONTEXT_INFO[] pinfo) { try { pinfo[0].dwFields = 0; if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS) != 0) { pinfo[0].bstrAddress = EngineUtils.AsAddr(_address, _engine.DebuggedProcess.Is64BitArch); pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS; } // Fields not supported by the sample if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSOFFSET) != 0) { } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE) != 0) { pinfo[0].bstrAddressAbsolute = EngineUtils.AsAddr(_address, _engine.DebuggedProcess.Is64BitArch); pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE; } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL) != 0) { DebuggedModule module = _engine.DebuggedProcess.ResolveAddress(_address); if (module != null) { pinfo[0].bstrModuleUrl = module.Name; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL; } } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION) != 0) { if (string.IsNullOrEmpty(_functionName)) { _functionName = Engine.GetAddressDescription(_address); } if (!(string.IsNullOrEmpty(_functionName))) { pinfo[0].bstrFunction = _functionName; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION; } } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_FUNCTIONOFFSET) != 0) { } return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Gets the user-displayable name for this context // This is not supported by the sample engine. public int GetName(out string pbstrName) { throw new NotImplementedException(); } // Subtracts a specified value from the current context's address to create a new context. public int Subtract(ulong dwCount, out IDebugMemoryContext2 ppMemCxt) { ppMemCxt = new AD7MemoryAddress(_engine, _address - (uint)dwCount, null); return Constants.S_OK; } #endregion #region IDebugCodeContext2 Members // Gets the document context for this code-context. If no document context is available, return S_FALSE. public int GetDocumentContext(out IDebugDocumentContext2 ppSrcCxt) { int hr = Constants.S_OK; if (_documentContext == null) hr = Constants.S_FALSE; ppSrcCxt = _documentContext; return hr; } // Gets the language information for this code context. public int GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage) { if (_documentContext != null) { return _documentContext.GetLanguageInfo(ref pbstrLanguage, ref pguidLanguage); } else { return Constants.S_FALSE; } } #endregion } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Web.UI.WebControls; using Hotcakes.Commerce.Contacts; using Hotcakes.Commerce.Dnn; using Hotcakes.Commerce.Membership; using Hotcakes.Commerce.Utilities; using Hotcakes.Common.Dnn; using Hotcakes.Modules.Core.Admin.AppCode; namespace Hotcakes.Modules.Core.Admin.People { partial class Affiliates : BaseAdminPage { #region Fields protected AffiliateReportTotals Totals = new AffiliateReportTotals(); #endregion #region Properties protected int AffiliatesCount { get { return ViewState["AffiliatesCount"].ConvertTo(0); } set { ViewState["AffiliatesCount"] = value; } } #endregion #region Event Handlers protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); PageTitle = Localization.GetString("Affiliates"); CurrentTab = AdminTabType.Reports; ValidateCurrentUserHasPermission(SystemPermissions.ReportsView); } protected override void OnInit(EventArgs e) { base.OnInit(e); gvAffiliates.RowDeleting += gvAffiliates_RowDeleting; lnkAddPayment.Click += lnkAddPayment_Click; ucPaymentDialog.AddPaymentAction = payment => { AddPayments(new List<AffiliatePayment> {payment}); }; ucPaymentDialog.AddMultiplePaymentsAction = payments => { AddPayments(payments); }; lnkExportToExcel.Click += lnkExportToExcel_Click; lnkApprove.Click += lnkApprove_Click; rblFilterMode.SelectedIndexChanged += (s, a) => ucPager.ResetPageNumber(); btnFind.Click += (s, a) => ucPager.ResetPageNumber(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!IsPostBack) { lnkApprove.OnClientClick = WebUtils.JsConfirmMessage(Localization.GetJsEncodedString("ApproveConfirm")); } } private void gvAffiliates_RowDeleting(object sender, GridViewDeleteEventArgs e) { var id = (long) e.Keys[0]; HccApp.ContactServices.Affiliates.Delete(id); } private void lnkAddPayment_Click(object sender, EventArgs e) { ucPaymentDialog.ShowDialogForSelection(GetSelectedIDs()); } private void lnkExportToExcel_Click(object sender, EventArgs e) { var criteria = GetCriteria(); var total = 0; var reportData = HccApp.ContactServices.Affiliates.FindAllWithFilter(criteria, 1, int.MaxValue, ref total); var affiliatesExport = new AffiliatesExport(); affiliatesExport.ExportToExcel(Response, "Hotcakes_Affiliates.xlsx", reportData); } private void lnkApprove_Click(object sender, EventArgs e) { var ids = GetSelectedIDs(); foreach (var affiliateId in ids) { var aff = HccApp.ContactServices.Affiliates.Find(affiliateId); if (!aff.Approved) { aff.Approved = true; var ui = DnnUserController.Instance.GetUser(DnnGlobal.Instance.GetPortalId(), aff.UserId); var culture = ui.Profile["UsedCulture"] as string; if (string.IsNullOrEmpty(culture)) { culture = "en-US"; } HccApp.ContactServices.Affiliates.Update(aff); HccApp.ContactServices.AffiliateWasApproved(aff, culture); } } } protected override void OnPreRender(EventArgs e) { var onlyNonApproved = rblFilterMode.SelectedValue == "OnlyNonApproved"; var onlyOwed = rblFilterMode.SelectedValue == "OnlyOwed"; if (onlyOwed || onlyNonApproved) { txtSearchText.Enabled = false; ddlSearchBy.Enabled = false; ucDateRangePicker.RangeType = DateRangeType.AllDates; ucDateRangePicker.Enabled = false; btnFind.Visible = false; } else { txtSearchText.Enabled = true; ddlSearchBy.Enabled = true; ucDateRangePicker.Enabled = true; btnFind.Visible = true; } lnkApprove.Visible = onlyNonApproved; BindAffiliates(); base.OnPreRender(e); } protected void gvAffiliates_OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[1].Text = Localization.GetString("Company"); e.Row.Cells[2].Text = Localization.GetString("Affiliate"); e.Row.Cells[3].Text = Localization.GetString("ID"); e.Row.Cells[4].Text = Localization.GetString("Sales"); e.Row.Cells[5].Text = Localization.GetString("Orders"); e.Row.Cells[6].Text = Localization.GetString("Commission"); e.Row.Cells[7].Text = Localization.GetString("Owed"); e.Row.Cells[8].Text = Localization.GetString("Signups"); } } protected void Delete_OnPreRender(object sender, EventArgs e) { var link = (LinkButton) sender; link.Text = Localization.GetString("Delete"); link.OnClientClick = WebUtils.JsConfirmMessage(Localization.GetJsEncodedString("ConfirmDelete")); } #endregion #region Implementation private List<long> GetSelectedIDs() { var ids = new List<long>(); foreach (GridViewRow row in gvAffiliates.Rows) { var chbItem = row.FindControl("chbItem") as CheckBox; if (chbItem.Checked) { ids.Add((long) gvAffiliates.DataKeys[row.DataItemIndex].Value); } } return ids; } private void AddPayments(List<AffiliatePayment> payments) { var paymentWasAdded = false; foreach (var payment in payments) { if (payment.PaymentAmount > 0) { if (HccApp.ContactServices.AffiliatePayments.Create(payment)) { paymentWasAdded = true; } } } if (paymentWasAdded) { ucMessageBox.ShowOk(Localization.GetString("NewPaymentsAdded")); } } private void BindAffiliates() { var repository = HccApp.ContactServices.Affiliates; var rowCount = 0; var criteria = GetCriteria(); Totals = repository.GetTotalsByFilter(criteria); gvAffiliates.DataSource = repository.FindAllWithFilter(criteria, ucPager.PageNumber, ucPager.PageSize, ref rowCount); gvAffiliates.DataBind(); ucPager.SetRowCount(rowCount); AffiliatesCount = rowCount; } private AffiliateReportCriteria GetCriteria() { var utcStart = ucDateRangePicker.GetStartDateUtc(HccApp); var utcEnd = ucDateRangePicker.GetEndDateUtc(HccApp); var onlyNonApproved = rblFilterMode.SelectedValue == "OnlyNonApproved"; var onlyOwed = rblFilterMode.SelectedValue == "OnlyOwed"; AffiliateReportCriteria criteria; if (onlyNonApproved) { criteria = new AffiliateReportCriteria { ShowOnlyNonApproved = true, SortBy = (AffiliateReportCriteria.SortingType) ddlSortBy.SelectedValue.ConvertTo<int>() }; } else if (onlyOwed) { criteria = new AffiliateReportCriteria { ShowCommissionOwed = true, SortBy = (AffiliateReportCriteria.SortingType) ddlSortBy.SelectedValue.ConvertTo<int>() }; } else { criteria = new AffiliateReportCriteria { StartDateUtc = utcStart, EndDateUtc = utcEnd, SortBy = (AffiliateReportCriteria.SortingType) ddlSortBy.SelectedValue.ConvertTo<int>(), SearchBy = (AffiliateReportCriteria.SearchType) ddlSearchBy.SelectedValue.ConvertTo<int>(), SearchText = txtSearchText.Text, ShowCommissionOwed = false, ShowOnlyNonApproved = false }; } return criteria; } #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.Reflection.Internal; using Xunit; namespace System.Reflection.Metadata.Tests { // // Test reading/decoding of compressed integers as described in the ECMA 335 CLI specification. // See Section II.3.2 - Blobs and Signatures. // public class CompressedIntegerTests { [Fact] public void DecompressUnsignedIntegersFromSpecExamples() { // These examples are straight from the CLI spec. // Test that we read them correctly straight from their explicit encoded values. Assert.Equal(0x03, ReadCompressedUnsignedInteger(0x03)); Assert.Equal(0x7f, ReadCompressedUnsignedInteger(0x7f)); Assert.Equal(0x80, ReadCompressedUnsignedInteger(0x80, 0x80)); Assert.Equal(0x2E57, ReadCompressedUnsignedInteger(0xAE, 0x57)); Assert.Equal(0x3FFF, ReadCompressedUnsignedInteger(0xBF, 0xFF)); Assert.Equal(0x4000, ReadCompressedUnsignedInteger(0xC0, 0x00, 0x40, 0x00)); Assert.Equal(0x1FFFFFFF, ReadCompressedUnsignedInteger(0xDF, 0xFF, 0xFF, 0xFF)); } [Fact] public void CompressUnsignedIntegersFromSpecExamples() { // These examples are straight from the CLI spec. // Test that our compression routine (written below for test purposes) encodes them the same way. Assert.Equal(CompressUnsignedInteger(0x03), new byte[] { 0x03 }); Assert.Equal(CompressUnsignedInteger(0x7F), new byte[] { 0x7f }); Assert.Equal(CompressUnsignedInteger(0x80), new byte[] { 0x80, 0x80 }); Assert.Equal(CompressUnsignedInteger(0x2E57), new byte[] { 0xAE, 0x57 }); Assert.Equal(CompressUnsignedInteger(0x3FFF), new byte[] { 0xBF, 0xFF }); Assert.Equal(CompressUnsignedInteger(0x4000), new byte[] { 0xC0, 0x00, 0x40, 0x00 }); Assert.Equal(CompressUnsignedInteger(0x1FFFFFFF), new byte[] { 0xDF, 0xFF, 0xFF, 0xFF }); } [Fact] public void DecompressInvalidUnsignedIntegers() { // Too few bytes Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(new byte[0])); Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0x80)); Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0xC0, 0xFF)); // No compressed integer can lead with 3 bits set. Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0xFF, 0xFF, 0xFF, 0xFF)); Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0xE0, 0x00, 0x00, 0x00)); } [Fact] public void DecompressSignedIntegersFromSpecExamples() { // These examples are straight from the CLI spec. // Test that we read them correctly straight from their explicit encoded values. Assert.Equal(3, ReadCompressedSignedInteger(0x06)); Assert.Equal(-3, ReadCompressedSignedInteger(0x7B)); Assert.Equal(64, ReadCompressedSignedInteger(0x80, 0x80)); Assert.Equal(-64, ReadCompressedSignedInteger(0x01)); Assert.Equal(8192, ReadCompressedSignedInteger(0xC0, 0x00, 0x40, 0x00)); Assert.Equal(-8192, ReadCompressedSignedInteger(0x80, 0x01)); Assert.Equal(268435455, ReadCompressedSignedInteger(0xDF, 0xFF, 0xFF, 0xFE)); Assert.Equal(-268435456, ReadCompressedSignedInteger(0xC0, 0x00, 0x00, 0x01)); } [Fact] public void CheckCompressedUnsignedIntegers() { // Test that we can round trip unsigned integers near the edge conditions // Around 0 CheckCompressedUnsignedInteger(0, 1); CheckCompressedUnsignedInteger(-1, -1); CheckCompressedUnsignedInteger(1, 1); // Near 1 byte limit CheckCompressedUnsignedInteger((1 << 7), 2); CheckCompressedUnsignedInteger((1 << 7) - 1, 1); CheckCompressedUnsignedInteger((1 << 7) + 1, 2); // Near 2 byte limit CheckCompressedUnsignedInteger((1 << 14), 4); CheckCompressedUnsignedInteger((1 << 14) - 1, 2); CheckCompressedUnsignedInteger((1 << 14) + 1, 4); // Near 4 byte limit CheckCompressedUnsignedInteger((1 << 29), -1); CheckCompressedUnsignedInteger((1 << 29) - 1, 4); CheckCompressedUnsignedInteger((1 << 29) + 1, -1); } [Fact] public void CompressSignedIntegersFromSpecExamples() { // These examples are straight from the CLI spec. // Test that our compression routine (written below for test purposes) encodes them the same way. Assert.Equal(CompressSignedInteger(3), new byte[] { 0x06 }); Assert.Equal(CompressSignedInteger(-3), new byte[] { 0x7b }); Assert.Equal(CompressSignedInteger(64), new byte[] { 0x80, 0x80 }); Assert.Equal(CompressSignedInteger(-64), new byte[] { 0x01 }); Assert.Equal(CompressSignedInteger(8192), new byte[] { 0xC0, 0x00, 0x40, 0x00 }); Assert.Equal(CompressSignedInteger(-8192), new byte[] { 0x80, 0x01 }); Assert.Equal(CompressSignedInteger(268435455), new byte[] { 0xDF, 0xFF, 0xFF, 0xFE }); Assert.Equal(CompressSignedInteger(-268435456), new byte[] { 0xC0, 0x00, 0x00, 0x01 }); } [Fact] public unsafe void DecompressInvalidSignedIntegers() { // Too few bytes Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(new byte[0])); Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0x80)); Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0xC0, 0xFF)); // No compressed integer can lead with 3 bits set. Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0xFF, 0xFF, 0xFF, 0xFF)); Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0xE0, 0x00, 0x00, 0x00)); } [Fact] public void CheckCompressedSignedIntegers() { // Test that we can round trip signed integers near the edge conditions. // around 0 CheckCompressedSignedInteger(-1, 1); CheckCompressedSignedInteger(1, 1); // around 1 byte limit CheckCompressedSignedInteger(-(1 << 6), 1); CheckCompressedSignedInteger(-(1 << 6) - 1, 2); CheckCompressedSignedInteger(-(1 << 6) + 1, 1); CheckCompressedSignedInteger((1 << 6), 2); CheckCompressedSignedInteger((1 << 6) - 1, 1); CheckCompressedSignedInteger((1 << 6) + 1, 2); // around 2 byte limit CheckCompressedSignedInteger(-(1 << 13), 2); CheckCompressedSignedInteger(-(1 << 13) - 1, 4); CheckCompressedSignedInteger(-(1 << 13) + 1, 2); CheckCompressedSignedInteger((1 << 13), 4); CheckCompressedSignedInteger((1 << 13) - 1, 2); CheckCompressedSignedInteger((1 << 13) + 1, 4); // around 4 byte limit CheckCompressedSignedInteger(-(1 << 28), 4); CheckCompressedSignedInteger(-(1 << 28) - 1, -1); CheckCompressedSignedInteger(-(1 << 28) + 1, 4); CheckCompressedSignedInteger((1 << 28), -1); CheckCompressedSignedInteger((1 << 28) - 1, 4); CheckCompressedSignedInteger((1 << 28) + 1, -1); } private void CheckCompressedSignedInteger(int valueToRoundTrip, int numberOfBytesExpected) { CheckCompressedInteger(valueToRoundTrip, numberOfBytesExpected, CompressSignedInteger, ReadCompressedSignedInteger); } private void CheckCompressedUnsignedInteger(int valueToRoundTrip, int numberOfBytesExpected) { CheckCompressedInteger(valueToRoundTrip, numberOfBytesExpected, CompressUnsignedInteger, ReadCompressedUnsignedInteger); } private void CheckCompressedInteger(int valueToRoundTrip, int numberOfBytesExpected, Func<int, byte[]> compress, Func<byte[], int> read) { byte[] bytes = compress(valueToRoundTrip); if (bytes == null) { Assert.Equal(-1, numberOfBytesExpected); } else { Assert.Equal(numberOfBytesExpected, bytes.Length); Assert.Equal(valueToRoundTrip, read(bytes)); } } // NOTE: The compression routines below can be optimized, but please don't do that. // The whole idea is to follow the verbal descriptions of the algorithms in // the spec as closely as possible. private byte[] CompressUnsignedInteger(int value) { if (value < 0) { return null; // too small } if (value < (1 << 7)) { return EncodeInteger(value, 1); } if (value < (1 << 14)) { return EncodeInteger(value, 2); } if (value < (1 << 29)) { return EncodeInteger(value, 4); } return null; // too big } private byte[] CompressSignedInteger(int value) { if (value >= -(1 << 6) && value < (1 << 6)) { return EncodeInteger(Rotate(value, 0x7f), 1); } if (value >= -(1 << 13) && value < (1 << 13)) { return EncodeInteger(Rotate(value, 0x3fff), 2); } if (value >= -(1 << 28) && value < (1 << 28)) { return EncodeInteger(Rotate(value, 0x1fffffff), 4); } return null; // out of compressible range. } private int Rotate(int value, int mask) { int signBit = value >= 0 ? 0 : 1; value <<= 1; value |= signBit; value &= mask; return value; } private byte[] EncodeInteger(int value, int byteCount) { Assert.True(value >= 0); switch (byteCount) { case 1: Assert.True(value < (1 << 7)); return new byte[] { // 1 byte encoding: bit 7 clear, // 7-bit value in bits 0-6 (byte)value }; case 2: Assert.True(value < (1 << 14)); return new byte[] { // 2 byte encoding: bit 15 set, bit 14 clear, // 14-bit value stored big-endian in bits 0-13 (byte)(0x80 | ((value >> 8) & 0x3f)), (byte)( ((value >> 0) & 0xff)), }; case 4: Assert.True(value < (1 << 29)); return new byte[] { // 4 byte encoding: bit 31 set, bit 30 set, bit 29 clear, // 29-bit value stored big-endian in bits 0-28 (byte)(0xC0 | ((value >> 24) & 0x1f)), (byte)( ((value >> 16) & 0xff)), (byte)( ((value >> 8) & 0xff)), (byte)( ((value >> 0) & 0xff)), }; default: throw new ArgumentOutOfRangeException(); } } private int ReadCompressedUnsignedInteger(params byte[] bytes) { return ReadCompressedInteger( bytes, delegate (ref BlobReader reader, out int value) { return reader.TryReadCompressedInteger(out value); }, delegate (ref BlobReader reader) { return reader.ReadCompressedInteger(); }); } private int ReadCompressedSignedInteger(params byte[] bytes) { return ReadCompressedInteger( bytes, delegate (ref BlobReader reader, out int value) { return reader.TryReadCompressedSignedInteger(out value); }, delegate (ref BlobReader reader) { return reader.ReadCompressedSignedInteger(); }); } private delegate bool TryReadFunc(ref BlobReader reader, out int value); private delegate int ReadFunc(ref BlobReader reader); private unsafe int ReadCompressedInteger(byte[] bytes, TryReadFunc tryRead, ReadFunc read) { fixed (byte* ptr = bytes) { var reader = new BlobReader(new MemoryBlock(ptr, bytes.Length)); int value; bool valid = tryRead(ref reader, out value); if (valid) { Assert.Equal(bytes.Length, reader.Offset); reader.Reset(); Assert.Equal(value, read(ref reader)); Assert.Equal(bytes.Length, reader.Offset); } else { Assert.Equal(0, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger()); Assert.Equal(value, BlobReader.InvalidCompressedInteger); Assert.Equal(0, reader.Offset); } return value; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using ValveResourceFormat.Blocks; using ValveResourceFormat.Blocks.ResourceEditInfoStructs; using ValveResourceFormat.ResourceTypes; namespace ValveResourceFormat { /// <summary> /// Represents a Valve resource. /// </summary> public class Resource : IDisposable { public const ushort KnownHeaderVersion = 12; private FileStream FileStream; /// <summary> /// Gets the binary reader. USE AT YOUR OWN RISK! /// It is exposed publicly to ease of reading the same file. /// </summary> /// <value>The binary reader.</value> public BinaryReader Reader { get; private set; } /// <summary> /// Gets or sets the file name this resource was parsed from. /// </summary> public string FileName { get; set; } /// <summary> /// Gets the resource size. /// </summary> public uint FileSize { get; private set; } /// <summary> /// Gets the version of this resource, should be 12. /// </summary> public ushort HeaderVersion { get; private set; } /// <summary> /// Gets the file type version. /// </summary> public ushort Version { get; private set; } /// <summary> /// Gets the list of blocks this resource contains. /// </summary> public List<Block> Blocks { get; } /// <summary> /// Gets or sets the type of the resource. /// </summary> /// <value>The type of the resource.</value> public ResourceType ResourceType { get; set; } /// <summary> /// Gets the ResourceExtRefList block. /// </summary> public ResourceExtRefList ExternalReferences { get { return (ResourceExtRefList)GetBlockByType(BlockType.RERL); } } /// <summary> /// Gets the ResourceEditInfo block. /// </summary> public ResourceEditInfo EditInfo { get; private set; } /// <summary> /// Gets the ResourceIntrospectionManifest block. /// </summary> public ResourceIntrospectionManifest IntrospectionManifest { get { return (ResourceIntrospectionManifest)GetBlockByType(BlockType.NTRO); } } /// <summary> /// Gets the Vertex and Index Buffer block. /// </summary> public VBIB VBIB { get { return (VBIB)GetBlockByType(BlockType.VBIB); } } /// <summary> /// Gets the generic DATA block. /// </summary> public ResourceData DataBlock { get { return (ResourceData)GetBlockByType(BlockType.DATA); } } /// <summary> /// Initializes a new instance of the <see cref="Resource"/> class. /// </summary> public Resource() { ResourceType = ResourceType.Unknown; Blocks = new List<Block>(); } /// <summary> /// Releases binary reader. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (FileStream != null) { FileStream.Dispose(); FileStream = null; } if (Reader != null) { Reader.Dispose(); Reader = null; } } } /// <summary> /// Opens and reads the given filename. /// The file is held open until the object is disposed. /// </summary> /// <param name="filename">The file to open and read.</param> public void Read(string filename) { FileName = filename; FileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Read(FileStream); } /// <summary> /// Reads the given <see cref="Stream"/>. /// </summary> /// <param name="input">The input <see cref="Stream"/> to read from.</param> public void Read(Stream input) { Reader = new BinaryReader(input); FileSize = Reader.ReadUInt32(); if (FileSize == 0x55AA1234) { throw new InvalidDataException("Use ValvePak library to parse VPK files.\nSee https://github.com/SteamDatabase/ValvePak"); } if (FileSize == CompiledShader.MAGIC) { throw new InvalidDataException("Use CompiledShader() class to parse compiled shader files."); } // TODO: Some real files seem to have different file size if (FileSize != Reader.BaseStream.Length) { //throw new Exception(string.Format("File size does not match size specified in file. {0} != {1}", FileSize, Reader.BaseStream.Length)); } HeaderVersion = Reader.ReadUInt16(); if (HeaderVersion != KnownHeaderVersion) { throw new InvalidDataException(string.Format("Bad header version. ({0} != expected {1})", HeaderVersion, KnownHeaderVersion)); } if (FileName != null) { ResourceType = DetermineResourceTypeByFileExtension(); } Version = Reader.ReadUInt16(); var blockOffset = Reader.ReadUInt32(); var blockCount = Reader.ReadUInt32(); Reader.BaseStream.Position += blockOffset - 8; // 8 is 2 uint32s we just read for (var i = 0; i < blockCount; i++) { var blockType = Encoding.UTF8.GetString(Reader.ReadBytes(4)); var position = Reader.BaseStream.Position; var offset = (uint)position + Reader.ReadUInt32(); var size = Reader.ReadUInt32(); Block block = null; // Peek data to detect VKV3 // Valve has deprecated NTRO as reported by resourceinfo.exe // TODO: Find a better way without checking against resource type if (size >= 4 && blockType == nameof(BlockType.DATA) && !IsHandledResourceType(ResourceType)) { Reader.BaseStream.Position = offset; var magic = Reader.ReadUInt32(); if (magic == BinaryKV3.MAGIC || magic == BinaryKV3.MAGIC2 || magic == BinaryKV3.MAGIC3) { block = new BinaryKV3(); } else if (magic == BinaryKV1.MAGIC) { block = new BinaryKV1(); } Reader.BaseStream.Position = position; } if (block == null) { block = ConstructFromType(blockType); } block.Offset = offset; block.Size = size; Blocks.Add(block); switch (block.Type) { case BlockType.REDI: case BlockType.RED2: block.Read(Reader, this); EditInfo = (ResourceEditInfo)block; // Try to determine resource type by looking at first compiler indentifier if (ResourceType == ResourceType.Unknown && EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies)) { var specialDeps = (SpecialDependencies)EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]; if (specialDeps.List.Count > 0) { ResourceType = DetermineResourceTypeByCompilerIdentifier(specialDeps.List[0]); } } break; case BlockType.NTRO: block.Read(Reader, this); if (ResourceType == ResourceType.Unknown && IntrospectionManifest.ReferencedStructs.Count > 0) { switch (IntrospectionManifest.ReferencedStructs[0].Name) { case "VSoundEventScript_t": ResourceType = ResourceType.SoundEventScript; break; case "CWorldVisibility": ResourceType = ResourceType.WorldVisibility; break; } } break; } Reader.BaseStream.Position = position + 8; } foreach (var block in Blocks) { if (block.Type is not BlockType.REDI and not BlockType.RED2 and not BlockType.NTRO) { block.Read(Reader, this); } } } public Block GetBlockByIndex(int index) { return Blocks[index]; } public Block GetBlockByType(BlockType type) { return Blocks.Find(b => b.Type == type); } public bool ContainsBlockType(BlockType type) { return Blocks.Exists(b => b.Type == type); } private Block ConstructFromType(string input) { return input switch { nameof(BlockType.DATA) => ConstructResourceType(), nameof(BlockType.REDI) => new ResourceEditInfo(), nameof(BlockType.RED2) => new ResourceEditInfo2(), nameof(BlockType.RERL) => new ResourceExtRefList(), nameof(BlockType.NTRO) => new ResourceIntrospectionManifest(), nameof(BlockType.VBIB) => new VBIB(), nameof(BlockType.VXVS) => new VXVS(), nameof(BlockType.SNAP) => new SNAP(), nameof(BlockType.MBUF) => new MBUF(), nameof(BlockType.CTRL) => new BinaryKV3(BlockType.CTRL), nameof(BlockType.MDAT) => new BinaryKV3(BlockType.MDAT), nameof(BlockType.INSG) => new BinaryKV3(BlockType.INSG), nameof(BlockType.SrMa) => new BinaryKV3(BlockType.SrMa), // SourceMap nameof(BlockType.LaCo) => new BinaryKV3(BlockType.LaCo), // vxml ast nameof(BlockType.MRPH) => new KeyValuesOrNTRO(BlockType.MRPH, "MorphSetData_t"), nameof(BlockType.ANIM) => new KeyValuesOrNTRO(BlockType.ANIM, "AnimationResourceData_t"), nameof(BlockType.ASEQ) => new KeyValuesOrNTRO(BlockType.ASEQ, "SequenceGroupResourceData_t"), nameof(BlockType.AGRP) => new KeyValuesOrNTRO(BlockType.AGRP, "AnimationGroupResourceData_t"), nameof(BlockType.PHYS) => new PhysAggregateData(BlockType.PHYS), _ => throw new ArgumentException($"Unrecognized block type '{input}'"), }; } private ResourceData ConstructResourceType() { switch (ResourceType) { case ResourceType.Panorama: case ResourceType.PanoramaScript: case ResourceType.PanoramaDynamicImages: case ResourceType.PanoramaVectorGraphic: return new Panorama(); case ResourceType.PanoramaStyle: return new PanoramaStyle(); case ResourceType.PanoramaLayout: return new PanoramaLayout(); case ResourceType.Sound: return new Sound(); case ResourceType.Texture: return new Texture(); case ResourceType.Model: return new Model(); case ResourceType.World: return new World(); case ResourceType.WorldNode: return new WorldNode(); case ResourceType.EntityLump: return new EntityLump(); case ResourceType.Material: return new Material(); case ResourceType.SoundEventScript: return new SoundEventScript(); case ResourceType.SoundStackScript: return new SoundStackScript(); case ResourceType.Particle: return new ParticleSystem(); case ResourceType.ResourceManifest: return new ResourceManifest(); case ResourceType.SboxData: case ResourceType.ArtifactItem: return new Plaintext(); case ResourceType.PhysicsCollisionMesh: return new PhysAggregateData(); case ResourceType.Mesh: if (Version == 0) { break; } return new BinaryKV3(); } if (ContainsBlockType(BlockType.NTRO)) { return new NTRO(); } return new ResourceData(); } private ResourceType DetermineResourceTypeByFileExtension() { var extension = Path.GetExtension(FileName) ?? string.Empty; extension = extension.EndsWith("_c", StringComparison.Ordinal) ? extension[1..^2] : extension[1..]; foreach (ResourceType typeValue in Enum.GetValues(typeof(ResourceType))) { if (typeValue == ResourceType.Unknown) { continue; } var type = typeof(ResourceType).GetMember(typeValue.ToString())[0]; var typeExt = (ExtensionAttribute)type.GetCustomAttributes(typeof(ExtensionAttribute), false)[0]; if (typeExt.Extension == extension) { return typeValue; } } return ResourceType.Unknown; } private static bool IsHandledResourceType(ResourceType type) { return type == ResourceType.Model || type == ResourceType.World || type == ResourceType.WorldNode || type == ResourceType.Particle || type == ResourceType.Material || type == ResourceType.EntityLump || type == ResourceType.PhysicsCollisionMesh; } private static ResourceType DetermineResourceTypeByCompilerIdentifier(SpecialDependencies.SpecialDependency input) { var identifier = input.CompilerIdentifier; if (identifier.StartsWith("Compile", StringComparison.Ordinal)) { identifier = identifier.Remove(0, "Compile".Length); } // Special mappings and otherwise different identifiers switch (identifier) { case "Psf": return ResourceType.ParticleSnapshot; case "AnimGroup": return ResourceType.AnimationGroup; case "VPhysXData": return ResourceType.PhysicsCollisionMesh; case "Font": return ResourceType.BitmapFont; case "RenderMesh": return ResourceType.Mesh; case "Panorama": switch (input.String) { case "Panorama Style Compiler Version": return ResourceType.PanoramaStyle; case "Panorama Script Compiler Version": return ResourceType.PanoramaScript; case "Panorama Layout Compiler Version": return ResourceType.PanoramaLayout; case "Panorama Dynamic Images Compiler Version": return ResourceType.PanoramaDynamicImages; } return ResourceType.Panorama; case "VectorGraphic": return ResourceType.PanoramaVectorGraphic; case "DotaItem": return ResourceType.ArtifactItem; case "SBData": return ResourceType.SboxData; } if (Enum.TryParse(identifier, false, out ResourceType resourceType)) { return resourceType; } return ResourceType.Unknown; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function initializeForestEditor() { echo(" % - Initializing Forest Editor"); exec( "./forestEditor.cs" ); exec( "./forestEditorGui.gui" ); exec( "./forestEditToolbar.ed.gui" ); exec( "./forestEditorGui.cs" ); exec( "./tools.cs" ); ForestEditorGui.setVisible( false ); ForestEditorPalleteWindow.setVisible( false ); ForestEditorPropertiesWindow.setVisible( false ); ForestEditToolbar.setVisible( false ); EditorGui.add( ForestEditorGui ); EditorGui.add( ForestEditorPalleteWindow ); EditorGui.add( ForestEditorPropertiesWindow ); EditorGui.add( ForestEditToolbar ); new ScriptObject( ForestEditorPlugin ) { superClass = "EditorPlugin"; editorGui = ForestEditorGui; }; new SimSet(ForestTools) { new ForestBrushTool() { internalName = "BrushTool"; toolTip = "Paint Tool"; buttonImage = "tools/forest/images/brushTool"; }; new ForestSelectionTool() { internalName = "SelectionTool"; toolTip = "Selection Tool"; buttonImage = "tools/forest/images/selectionTool"; }; }; %map = new ActionMap(); %map.bindCmd( keyboard, "1", "ForestEditorSelectModeBtn.performClick();", "" ); // Select %map.bindCmd( keyboard, "2", "ForestEditorMoveModeBtn.performClick();", "" ); // Move %map.bindCmd( keyboard, "3", "ForestEditorRotateModeBtn.performClick();", "" ); // Rotate %map.bindCmd( keyboard, "4", "ForestEditorScaleModeBtn.performClick();", "" ); // Scale %map.bindCmd( keyboard, "5", "ForestEditorPaintModeBtn.performClick();", "" ); // Paint %map.bindCmd( keyboard, "6", "ForestEditorEraseModeBtn.performClick();", "" ); // Erase %map.bindCmd( keyboard, "7", "ForestEditorEraseSelectedModeBtn.performClick();", "" ); // EraseSelected //%map.bindCmd( keyboard, "backspace", "ForestEditorGui.onDeleteKey();", "" ); //%map.bindCmd( keyboard, "delete", "ForestEditorGui.onDeleteKey();", "" ); ForestEditorPlugin.map = %map; } function destroyForestEditor() { } // NOTE: debugging helper. function reinitForest() { exec( "./main.cs" ); exec( "./forestEditorGui.cs" ); exec( "./tools.cs" ); } function ForestEditorPlugin::onWorldEditorStartup( %this ) { new PersistenceManager( ForestDataManager ); %brushPath = "art/forest/brushes.cs"; if ( !isFile( %brushPath ) ) createPath( %brushPath ); // This creates the ForestBrushGroup, all brushes, and elements. exec( %brushpath ); if ( !isObject( ForestBrushGroup ) ) { new SimGroup( ForestBrushGroup ); %this.showError = true; } ForestEditBrushTree.open( ForestBrushGroup ); if ( !isObject( ForestItemDataSet ) ) new SimSet( ForestItemDataSet ); ForestEditMeshTree.open( ForestItemDataSet ); // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu( "Forest Editor", "", ForestEditorPlugin ); // Add ourselves to the tools menu. %tooltip = "Forest Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "ForestEditorPlugin", "ForestEditorPalette", expandFilename("tools/forestEditor/images/forest-editor-btn"), %tooltip ); //connect editor windows GuiWindowCtrl::attach( ForestEditorPropertiesWindow, ForestEditorPalleteWindow ); ForestEditTabBook.selectPage(0); } function ForestEditorPlugin::onWorldEditorShutdown( %this ) { if ( isObject( ForestBrushGroup ) ) ForestBrushGroup.delete(); if ( isObject( ForestDataManager ) ) ForestDataManager.delete(); } function ForestEditorPlugin::onActivated( %this ) { EditorGui.bringToFront( ForestEditorGui ); ForestEditorGui.setVisible( true ); ForestEditorPalleteWindow.setVisible( true ); ForestEditorPropertiesWindow.setVisible( true ); ForestEditorGui.makeFirstResponder( true ); //ForestEditToolbar.setVisible( true ); //Get our existing forest object in our current mission if we have one %forestObject = parseMissionGroupForIds("Forest", ""); if(isObject(%forestObject)) { ForestEditorGui.setActiveForest(%forestObject.getName()); } %this.map.push(); Parent::onActivated(%this); ForestEditBrushTree.open( ForestBrushGroup ); ForestEditMeshTree.open( ForestItemDataSet ); // Open the Brush tab. ForestEditTabBook.selectPage(0); // Sync the pallete button state // And toolbar. %tool = ForestEditorGui.getActiveTool(); if ( isObject( %tool ) ) %tool.onActivated(); if ( !isObject( %tool ) ) { ForestEditorPaintModeBtn.performClick(); if ( ForestEditBrushTree.getItemCount() > 0 ) { ForestEditBrushTree.selectItem( 0, true ); } } else if ( %tool == ForestTools->SelectionTool ) { %mode = GlobalGizmoProfile.mode; switch$ (%mode) { case "None": ForestEditorSelectModeBtn.performClick(); case "Move": ForestEditorMoveModeBtn.performClick(); case "Rotate": ForestEditorRotateModeBtn.performClick(); case "Scale": ForestEditorScaleModeBtn.performClick(); } } else if ( %tool == ForestTools->BrushTool ) { %mode = ForestTools->BrushTool.mode; switch$ (%mode) { case "Paint": ForestEditorPaintModeBtn.performClick(); case "Erase": ForestEditorEraseModeBtn.performClick(); case "EraseSelected": ForestEditorEraseSelectedModeBtn.performClick(); } } if ( %this.showError ) MessageBoxOK( "Error", "Your art/forest folder does not contain a valid brushes.cs. Brushes you create will not be saved!" ); } function ForestEditorPlugin::onDeactivated( %this ) { ForestEditorGui.setVisible( false ); ForestEditorPalleteWindow.setVisible( false ); ForestEditorPropertiesWindow.setVisible( false ); %tool = ForestEditorGui.getActiveTool(); if ( isObject( %tool ) ) %tool.onDeactivated(); // Also take this opportunity to save. ForestDataManager.saveDirty(); %this.map.pop(); Parent::onDeactivated(%this); } function ForestEditorPlugin::isDirty( %this ) { %dirty = %this.dirty || ForestEditorGui.isDirty(); return %dirty; } function ForestEditorPlugin::clearDirty( %this ) { %this.dirty = false; } function ForestEditorPlugin::onSaveMission( %this, %missionFile ) { ForestDataManager.saveDirty(); //First, find out if we have an existing forest object %forestObject = parseMissionGroupForIds("Forest", ""); if ( isObject( %forestObject ) ) { //We do. Next, see if we have a file already by polling the datafield. if(%forestObject.dataFile !$= "") { //If we do, just save to the provided file. %forestObject.saveDataFile(%forestObject.dataFile); } else { //We don't, so we'll save in the same place as the mission file and give it the missionpath\missionName.forest //naming convention. %path = filePath(%missionFile); %missionName = fileBase(%missionFile); %forestObject.saveDataFile(%path @ "/" @ %missionName @ ".forest"); } } ForestBrushGroup.save( "art/forest/brushes.cs" ); } function ForestEditorPlugin::onEditorSleep( %this ) { } function ForestEditorPlugin::onEditMenuSelect( %this, %editMenu ) { %hasSelection = false; %selTool = ForestTools->SelectionTool; if ( ForestEditorGui.getActiveTool() == %selTool ) if ( %selTool.getSelectionCount() > 0 ) %hasSelection = true; %editMenu.enableItem( 3, %hasSelection ); // Cut %editMenu.enableItem( 4, %hasSelection ); // Copy %editMenu.enableItem( 5, %hasSelection ); // Paste %editMenu.enableItem( 6, %hasSelection ); // Delete %editMenu.enableItem( 8, %hasSelection ); // Deselect } function ForestEditorPlugin::handleDelete( %this ) { ForestTools->SelectionTool.deleteSelection(); } function ForestEditorPlugin::handleDeselect( %this ) { ForestTools->SelectionTool.clearSelection(); } function ForestEditorPlugin::handleCut( %this ) { ForestTools->SelectionTool.cutSelection(); } function ForestEditorPlugin::handleCopy( %this ) { ForestTools->SelectionTool.copySelection(); } function ForestEditorPlugin::handlePaste( %this ) { ForestTools->SelectionTool.pasteSelection(); }
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #endregion #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using System.Collections.Generic; using System.Collections.ObjectModel; using AdvanceMath; using AdvanceMath.Geometry2D; using Physics2DDotNet.Shapes; namespace Physics2DDotNet.PhysicsLogics { /// <summary> /// Simulates a simple explosion. /// </summary> public sealed class ExplosionLogic : PhysicsLogic { sealed class Wrapper { public Body body; public IExplosionAffectable affectable; } Scalar dragCoefficient; Scalar radius; Scalar time; Scalar pressurePulseSpeed; Body explosionBody; List<Wrapper> items; /// <summary> /// Creates a new instance of the ExplosionLogic /// </summary> /// <param name="location">ground zero</param> /// <param name="velocity">the velocity of the explosion (this would be from the missile or bomb that spawns it).</param> /// <param name="pressurePulseSpeed">the speed at which the explosion expands</param> /// <param name="dragCoefficient">the drag Coefficient</param> /// <param name="mass">the mass of the expanding cloud</param> /// <param name="lifetime"></param> public ExplosionLogic( Vector2D location, Vector2D velocity, Scalar pressurePulseSpeed, Scalar dragCoefficient, Scalar mass, Lifespan lifetime) : base(lifetime) { this.dragCoefficient = dragCoefficient; this.pressurePulseSpeed = pressurePulseSpeed; this.explosionBody = new Body( new PhysicsState(new ALVector2D(0, location), new ALVector2D(0, velocity)), new CircleShape(1, 3), mass, new Coefficients(1, 1), lifetime); this.explosionBody.IgnoresCollisionResponse = true; this.explosionBody.Collided += OnCollided; this.items = new List<Wrapper>(); } public Body ExplosionBody { get { return explosionBody; } } void OnCollided(object sender, CollisionEventArgs e) { if (e.Other.IgnoresPhysicsLogics|| Scalar.IsPositiveInfinity(e.Other.Mass.Mass)) { return; } IExplosionAffectable affectable = e.Other.Shape as IExplosionAffectable; if (affectable != null) { Wrapper wrapper = new Wrapper(); wrapper.body = e.Other; wrapper.affectable = affectable; items.Add(wrapper); } } public override ReadOnlyCollection<Body> LogicBodies { get { return new ReadOnlyCollection<Body>(new Body[] { explosionBody }); } } protected internal override void UpdateTime(TimeStep step) { time += step.Dt; radius = 1 + time * pressurePulseSpeed; explosionBody.Transformation = Matrix2x3.FromScale(new Vector2D(radius, radius)); base.UpdateTime(step); } protected internal override void RunLogic(TimeStep step) { Scalar area = MathHelper.Pi * radius * radius; Scalar density = explosionBody.Mass.Mass / area; BoundingCircle circle = new BoundingCircle(explosionBody.State.Position.Linear, radius); Matrix2x3 temp; ALVector2D.ToMatrix2x3(ref explosionBody.State.Position, out temp); Matrices matrices = new Matrices(); matrices.SetToWorld(ref temp); Vector2D relativeVelocity = Vector2D.Zero; Vector2D velocityDirection = Vector2D.Zero; Vector2D dragDirection = Vector2D.Zero; for (int index = 0; index < items.Count; ++index) { Wrapper wrapper = items[index]; Body body = wrapper.body; Matrix2x3 matrix; Matrix2x3.Multiply(ref matrices.ToBody, ref body.Matrices.ToWorld, out matrix); ContainmentType containmentType; BoundingRectangle rect = body.Rectangle; circle.Contains(ref rect, out containmentType); if (containmentType == ContainmentType.Intersects) { return; GetTangentCallback callback = delegate(Vector2D centroid) { centroid = body.Matrices.ToWorld * centroid; Vector2D p1 = centroid - explosionBody.State.Position.Linear; Vector2D p2 = centroid - body.State.Position.Linear; PhysicsHelper.GetRelativeVelocity( ref explosionBody.State.Velocity, ref body.State.Velocity, ref p1, ref p2, out relativeVelocity); relativeVelocity = p1.Normalized * this.pressurePulseSpeed; relativeVelocity = -relativeVelocity; velocityDirection = relativeVelocity.Normalized; dragDirection = matrices.ToBodyNormal * velocityDirection.LeftHandNormal; return dragDirection; }; DragInfo dragInfo = wrapper.affectable.GetExplosionInfo(matrix, radius, callback); if (dragInfo == null) { continue; } if (velocityDirection == Vector2D.Zero) { continue; } if (dragInfo.DragArea < .01f) { continue; } Scalar speedSq = relativeVelocity.MagnitudeSq; Scalar dragForceMag = -.5f * density * speedSq * dragInfo.DragArea * dragCoefficient; Scalar maxDrag = -MathHelper.Sqrt(speedSq) * body.Mass.Mass * step.DtInv; if (dragForceMag < maxDrag) { dragForceMag = maxDrag; } Vector2D dragForce = dragForceMag * velocityDirection; wrapper.body.ApplyForce(dragForce, (body.Matrices.ToBody * matrices.ToWorld) * dragInfo.DragCenter); } else if (containmentType == ContainmentType.Contains) { Vector2D centroid = body.Matrices.ToWorld * wrapper.affectable.Centroid; Vector2D p1 = centroid - explosionBody.State.Position.Linear; Vector2D p2 = centroid - body.State.Position.Linear; PhysicsHelper.GetRelativeVelocity( ref explosionBody.State.Velocity, ref body.State.Velocity, ref p1, ref p2, out relativeVelocity); relativeVelocity = p1.Normalized * this.pressurePulseSpeed; relativeVelocity = -relativeVelocity; velocityDirection = relativeVelocity.Normalized; dragDirection = matrices.ToBodyNormal * velocityDirection.LeftHandNormal; DragInfo dragInfo = wrapper.affectable.GetFluidInfo(dragDirection); if (dragInfo.DragArea < .01f) { continue; } Scalar speedSq = relativeVelocity.MagnitudeSq; Scalar dragForceMag = -.5f * density * speedSq * dragInfo.DragArea * dragCoefficient; Scalar maxDrag = -MathHelper.Sqrt(speedSq) * body.Mass.Mass * step.DtInv; if (dragForceMag < maxDrag) { dragForceMag = maxDrag; } Vector2D dragForce = dragForceMag * velocityDirection; wrapper.body.ApplyForce(dragForce, body.Matrices.ToWorldNormal * dragInfo.DragCenter); wrapper.body.ApplyTorque( -body.Mass.MomentOfInertia * (body.Coefficients.DynamicFriction + density + dragCoefficient) * body.State.Velocity.Angular); } } } } }
#region File Description //----------------------------------------------------------------------------- // Quest.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework.Content; #endregion namespace RolePlayingGameData { /// <summary> /// A quest that the party can embark on, with goals and rewards. /// </summary> public class Quest : ContentObject { #region Quest Stage /// <summary> /// The possible stages of a quest. /// </summary> public enum QuestStage { NotStarted, InProgress, RequirementsMet, Completed }; /// <summary> /// The current stage of this quest. /// </summary> private QuestStage stage = QuestStage.NotStarted; /// <summary> /// The current stage of this quest. /// </summary> [ContentSerializerIgnore] public QuestStage Stage { get { return stage; } set { stage = value; } } #endregion #region Description /// <summary> /// The name of the quest. /// </summary> private string name; /// <summary> /// The name of the quest. /// </summary> public string Name { get { return name; } set { name = value; } } /// <summary> /// A description of the quest. /// </summary> private string description; /// <summary> /// A description of the quest. /// </summary> public string Description { get { return description; } set { description = value; } } /// <summary> /// A message describing the objective of the quest, /// presented when the player receives the quest. /// </summary> private string objectiveMessage; /// <summary> /// A message describing the objective of the quest, /// presented when the player receives the quest. /// </summary> public string ObjectiveMessage { get { return objectiveMessage; } set { objectiveMessage = value; } } /// <summary> /// A message announcing the completion of the quest, /// presented when the player reaches the goals of the quest. /// </summary> private string completionMessage; public string CompletionMessage { get { return completionMessage; } set { completionMessage = value; } } #endregion #region Requirements /// <summary> /// The gear that the player must have to finish the quest. /// </summary> private List<QuestRequirement<Gear>> gearRequirements = new List<QuestRequirement<Gear>>(); /// <summary> /// The gear that the player must have to finish the quest. /// </summary> public List<QuestRequirement<Gear>> GearRequirements { get { return gearRequirements; } set { gearRequirements = value; } } /// <summary> /// The monsters that must be killed to finish the quest. /// </summary> private List<QuestRequirement<Monster>> monsterRequirements = new List<QuestRequirement<Monster>>(); /// <summary> /// The monsters that must be killed to finish the quest. /// </summary> public List<QuestRequirement<Monster>> MonsterRequirements { get { return monsterRequirements; } set { monsterRequirements = value; } } /// <summary> /// Returns true if all requirements for this quest have been met. /// </summary> public bool AreRequirementsMet { get { foreach (QuestRequirement<Gear> gearRequirement in gearRequirements) { if (gearRequirement.CompletedCount < gearRequirement.Count) { return false; } } foreach (QuestRequirement<Monster> monsterRequirement in monsterRequirements) { if (monsterRequirement.CompletedCount < monsterRequirement.Count) { return false; } } return true; } } #endregion #region Quest Content /// <summary> /// The fixed combat encounters added to the world when this quest is active. /// </summary> private List<WorldEntry<FixedCombat>> fixedCombatEntries = new List<WorldEntry<FixedCombat>>(); /// <summary> /// The fixed combat encounters added to the world when this quest is active. /// </summary> public List<WorldEntry<FixedCombat>> FixedCombatEntries { get { return fixedCombatEntries; } set { fixedCombatEntries = value; } } /// <summary> /// The chests added to thew orld when this quest is active. /// </summary> private List<WorldEntry<Chest>> chestEntries = new List<WorldEntry<Chest>>(); /// <summary> /// The chests added to thew orld when this quest is active. /// </summary> public List<WorldEntry<Chest>> ChestEntries { get { return chestEntries; } set { chestEntries = value; } } #endregion #region Destination /// <summary> /// The map with the destination Npc, if any. /// </summary> private string destinationMapContentName; /// <summary> /// The map with the destination Npc, if any. /// </summary> [ContentSerializer(Optional = true)] public string DestinationMapContentName { get { return destinationMapContentName; } set { destinationMapContentName = value; } } /// <summary> /// The Npc that the party must visit to finish the quest, if any. /// </summary> private string destinationNpcContentName; /// <summary> /// The Npc that the party must visit to finish the quest, if any. /// </summary> [ContentSerializer(Optional = true)] public string DestinationNpcContentName { get { return destinationNpcContentName; } set { destinationNpcContentName = value; } } /// <summary> /// The message shown when the party is eligible to complete the quest, if any. /// </summary> private string destinationObjectiveMessage; /// <summary> /// The message shown when the party is eligible to complete the quest, if any. /// </summary> [ContentSerializer(Optional = true)] public string DestinationObjectiveMessage { get { return destinationObjectiveMessage; } set { destinationObjectiveMessage = value; } } #endregion #region Reward /// <summary> /// The number of experience points given to each party member as a reward. /// </summary> private int experienceReward; /// <summary> /// The number of experience points given to each party member as a reward. /// </summary> [ContentSerializer(Optional = true)] public int ExperienceReward { get { return experienceReward; } set { experienceReward = value; } } /// <summary> /// The amount of gold given to the party as a reward. /// </summary> private int goldReward; /// <summary> /// The amount of gold given to the party as a reward. /// </summary> [ContentSerializer(Optional = true)] public int GoldReward { get { return goldReward; } set { goldReward = value; } } /// <summary> /// The content names of the gear given to the party as a reward. /// </summary> private List<string> gearRewardContentNames = new List<string>(); /// <summary> /// The content names of the gear given to the party as a reward. /// </summary> [ContentSerializer(Optional = true)] public List<string> GearRewardContentNames { get { return gearRewardContentNames; } set { gearRewardContentNames = value; } } /// <summary> /// The gear given to the party as a reward. /// </summary> private List<Gear> gearRewards = new List<Gear>(); /// <summary> /// The gear given to the party as a reward. /// </summary> [ContentSerializerIgnore] public List<Gear> GearRewards { get { return gearRewards; } set { gearRewards = value; } } #endregion #region Content Type Reader /// <summary> /// Reads a Quest object from the content pipeline. /// </summary> public class QuestReader : ContentTypeReader<Quest> { /// <summary> /// Reads a Quest object from the content pipeline. /// </summary> protected override Quest Read(ContentReader input, Quest existingInstance) { Quest quest = existingInstance; if (quest == null) { quest = new Quest(); } quest.AssetName = input.AssetName; quest.Name = input.ReadString(); quest.Description = input.ReadString(); quest.ObjectiveMessage = input.ReadString(); quest.CompletionMessage = input.ReadString(); quest.GearRequirements.AddRange( input.ReadObject<List<QuestRequirement<Gear>>>()); quest.MonsterRequirements.AddRange( input.ReadObject<List<QuestRequirement<Monster>>>()); // load the fixed combat entries Random random = new Random(); quest.FixedCombatEntries.AddRange( input.ReadObject<List<WorldEntry<FixedCombat>>>()); foreach (WorldEntry<FixedCombat> fixedCombatEntry in quest.FixedCombatEntries) { fixedCombatEntry.Content = input.ContentManager.Load<FixedCombat>( System.IO.Path.Combine(@"Maps\FixedCombats", fixedCombatEntry.ContentName)); // clone the map sprite in the entry, as there may be many entries // per FixedCombat fixedCombatEntry.MapSprite = fixedCombatEntry.Content.Entries[0].Content.MapSprite.Clone() as AnimatingSprite; // play the idle animation fixedCombatEntry.MapSprite.PlayAnimation("Idle", fixedCombatEntry.Direction); // advance in a random amount so the animations aren't synchronized fixedCombatEntry.MapSprite.UpdateAnimation( 4f * (float)random.NextDouble()); } quest.ChestEntries.AddRange( input.ReadObject<List<WorldEntry<Chest>>>()); foreach (WorldEntry<Chest> chestEntry in quest.ChestEntries) { chestEntry.Content = input.ContentManager.Load<Chest>( System.IO.Path.Combine(@"Maps\Chests", chestEntry.ContentName)).Clone() as Chest; } quest.DestinationMapContentName = input.ReadString(); quest.DestinationNpcContentName = input.ReadString(); quest.DestinationObjectiveMessage = input.ReadString(); quest.experienceReward = input.ReadInt32(); quest.goldReward = input.ReadInt32(); quest.GearRewardContentNames.AddRange( input.ReadObject<List<string>>()); foreach (string contentName in quest.GearRewardContentNames) { quest.GearRewards.Add(input.ContentManager.Load<Gear>( Path.Combine("Gear", contentName))); } return quest; } } #endregion #region ICloneable Members public object Clone() { Quest quest = new Quest(); quest.AssetName = AssetName; foreach (WorldEntry<Chest> chestEntry in chestEntries) { WorldEntry<Chest> worldEntry = new WorldEntry<Chest>(); worldEntry.Content = chestEntry.Content.Clone() as Chest; worldEntry.ContentName = chestEntry.ContentName; worldEntry.Count = chestEntry.Count; worldEntry.Direction = chestEntry.Direction; worldEntry.MapContentName = chestEntry.MapContentName; worldEntry.MapPosition = chestEntry.MapPosition; quest.chestEntries.Add(worldEntry); } quest.completionMessage = completionMessage; quest.description = description; quest.destinationMapContentName = destinationMapContentName; quest.destinationNpcContentName = destinationNpcContentName; quest.destinationObjectiveMessage = destinationObjectiveMessage; quest.experienceReward = experienceReward; quest.fixedCombatEntries.AddRange(fixedCombatEntries); quest.gearRequirements.AddRange(gearRequirements); quest.gearRewardContentNames.AddRange(gearRewardContentNames); quest.gearRewards.AddRange(gearRewards); quest.goldReward = goldReward; quest.monsterRequirements.AddRange(monsterRequirements); quest.name = name; quest.objectiveMessage = objectiveMessage; quest.stage = stage; return quest; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Xunit; using Validation; using System.Diagnostics; namespace System.Collections.Immutable.Tests { public abstract class ImmutableListTestBase : SimpleElementImmutablesTestBase { internal abstract IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list); [Fact] public void CopyToEmptyTest() { var array = new int[0]; this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array, 0); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(0, array, 0, 0); ((ICollection)this.GetListQuery(ImmutableList<int>.Empty)).CopyTo(array, 0); } [Fact] public void CopyToTest() { var listQuery = this.GetListQuery(ImmutableList.Create(1, 2)); var list = (IEnumerable<int>)listQuery; var array = new int[2]; listQuery.CopyTo(array); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(array, 0); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(0, array, 0, listQuery.Count); Assert.Equal(list, array); array = new int[1]; // shorter than source length listQuery.CopyTo(0, array, 0, array.Length); Assert.Equal(list.Take(array.Length), array); array = new int[3]; listQuery.CopyTo(1, array, 2, 1); Assert.Equal(new[] { 0, 0, 2 }, array); array = new int[2]; ((ICollection)listQuery).CopyTo(array, 0); Assert.Equal(list, array); } [Fact] public void ForEachTest() { this.GetListQuery(ImmutableList<int>.Empty).ForEach(n => { throw new ShouldNotBeInvokedException(); }); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 3)); var hitTest = new bool[list.Max() + 1]; this.GetListQuery(list).ForEach(i => { Assert.False(hitTest[i]); hitTest[i] = true; }); for (int i = 0; i < hitTest.Length; i++) { Assert.Equal(list.Contains(i), hitTest[i]); Assert.Equal(((IList)list).Contains(i), hitTest[i]); } } [Fact] public void ExistsTest() { Assert.False(this.GetListQuery(ImmutableList<int>.Empty).Exists(n => true)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 5)); Assert.True(this.GetListQuery(list).Exists(n => n == 3)); Assert.False(this.GetListQuery(list).Exists(n => n == 8)); } [Fact] public void FindAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).FindAll(n => true).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); var actual = this.GetListQuery(list).FindAll(n => n % 2 == 1); var expected = list.ToList().FindAll(n => n % 2 == 1); Assert.Equal<int>(expected, actual.ToList()); } [Fact] public void FindTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).Find(n => true)); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(3, this.GetListQuery(list).Find(n => (n % 2) == 1)); } [Fact] public void FindLastTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).FindLast(n => { throw new ShouldNotBeInvokedException(); })); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(5, this.GetListQuery(list).FindLast(n => (n % 2) == 1)); } [Fact] public void FindIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == 0) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void FindLastIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindLastIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindLastIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindLastIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == list.Count - 1) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void ConvertAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).ConvertAll<float>(n => n).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); Func<int, double> converter = n => 2.0 * n; var expected = list.ToList().Select(converter).ToList(); var actual = this.GetListQuery(list).ConvertAll(converter); Assert.Equal<double>(expected.ToList(), actual.ToList()); } [Fact] public void GetRangeTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).GetRange(0, 0).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); var bclList = list.ToList(); for (int index = 0; index < list.Count; index++) { for (int count = 0; count < list.Count - index; count++) { var expected = bclList.GetRange(index, count); var actual = this.GetListQuery(list).GetRange(index, count); Assert.Equal<int>(expected.ToList(), actual.ToList()); } } } [Fact] public void TrueForAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).TrueForAll(n => false)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.TrueForAllTestHelper(list, n => n % 2 == 0); this.TrueForAllTestHelper(list, n => n % 2 == 1); this.TrueForAllTestHelper(list, n => true); } [Fact] public void RemoveAllTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.RemoveAllTestHelper(list, n => false); this.RemoveAllTestHelper(list, n => true); this.RemoveAllTestHelper(list, n => n < 7); this.RemoveAllTestHelper(list, n => n > 7); this.RemoveAllTestHelper(list, n => n == 7); } [Fact] public void ReverseTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count - i; j++) { this.ReverseTestHelper(list, i, j); } } } [Fact] public void SortTest() { var scenarios = new[] { ImmutableList<int>.Empty, ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50)), ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50).Reverse()), }; foreach (var scenario in scenarios) { var expected = scenario.ToList(); expected.Sort(); var actual = this.SortTestHelper(scenario); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); Comparison<int> comparison = (x, y) => x > y ? 1 : (x < y ? -1 : 0); expected.Sort(comparison); actual = this.SortTestHelper(scenario, comparison); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); IComparer<int> comparer = Comparer<int>.Default; expected.Sort(comparer); actual = this.SortTestHelper(scenario, comparer); Assert.Equal<int>(expected, actual); for (int i = 0; i < scenario.Count; i++) { for (int j = 0; j < scenario.Count - i; j++) { expected = scenario.ToList(); comparer = Comparer<int>.Default; expected.Sort(i, j, comparer); actual = this.SortTestHelper(scenario, i, j, comparer); Assert.Equal<int>(expected, actual); } } } } [Fact] public void BinarySearch() { var basis = new List<int>(Enumerable.Range(1, 50).Select(n => n * 2)); var query = this.GetListQuery(basis.ToImmutableList()); for (int value = basis.First() - 1; value <= basis.Last() + 1; value++) { int expected = basis.BinarySearch(value); int actual = query.BinarySearch(value); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); for (int index = 0; index < basis.Count - 1; index++) { for (int count = 0; count <= basis.Count - index; count++) { expected = basis.BinarySearch(index, count, value, null); actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void BinarySearchPartialSortedList() { var reverseSorted = ImmutableArray.CreateRange(Enumerable.Range(1, 150).Select(n => n * 2).Reverse()); this.BinarySearchPartialSortedListHelper(reverseSorted, 0, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 50, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 100, 50); } private void BinarySearchPartialSortedListHelper(ImmutableArray<int> inputData, int sortedIndex, int sortedLength) { Requires.Range(sortedIndex >= 0, "sortedIndex"); Requires.Range(sortedLength > 0, "sortedLength"); inputData = inputData.Sort(sortedIndex, sortedLength, Comparer<int>.Default); int min = inputData[sortedIndex]; int max = inputData[sortedIndex + sortedLength - 1]; var basis = new List<int>(inputData); var query = this.GetListQuery(inputData.ToImmutableList()); for (int value = min - 1; value <= max + 1; value++) { for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list. { for (int count = 0; count <= sortedLength - index; count++) { int expected = basis.BinarySearch(index, count, value, null); int actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void SyncRoot() { var collection = (ICollection)this.GetEnumerableOf<int>(); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Fact] public void GetEnumeratorTest() { var enumerable = this.GetEnumerableOf(1); Assert.Equal(new[] { 1 }, enumerable.ToList()); // exercises the enumerator IEnumerable enumerableNonGeneric = enumerable; Assert.Equal(new[] { 1 }, enumerableNonGeneric.Cast<int>().ToList()); // exercises the enumerator } protected abstract void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test); protected abstract void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer); private void TrueForAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var bclList = list.ToList(); var expected = bclList.TrueForAll(test); var actual = this.GetListQuery(list).TrueForAll(test); Assert.Equal(expected, actual); } } }
using System; using System.Data; using Signum.Utilities; using Signum.Engine.Maps; using System.IO; using System.Data.Common; using System.Linq.Expressions; using Signum.Entities; using Signum.Utilities.Reflection; using System.Reflection; using System.Threading.Tasks; using System.Threading; using System.Data.SqlClient; using System.Collections.Generic; namespace Signum.Engine { public abstract class Connector { static readonly Variable<Connector> currentConnector = Statics.ThreadVariable<Connector>("connection"); public SqlBuilder SqlBuilder; public static IDisposable Override(Connector connector) { Connector oldConnection = currentConnector.Value; currentConnector.Value = connector; return new Disposable(() => currentConnector.Value = oldConnection); } public static Connector Current { get { return currentConnector.Value ?? Default; } } public static Connector Default { get; set; } = null!; static readonly Variable<int?> scopeTimeout = Statics.ThreadVariable<int?>("scopeTimeout"); public static int? ScopeTimeout { get { return scopeTimeout.Value; } } public static IDisposable CommandTimeoutScope(int? timeoutSeconds) { var old = scopeTimeout.Value; scopeTimeout.Value = timeoutSeconds; return new Disposable(() => scopeTimeout.Value = old); } public Connector(Schema schema) { this.Schema = schema; this.IsolationLevel = IsolationLevel.Unspecified; this.SqlBuilder = new SqlBuilder(this); } public Schema Schema { get; private set; } static readonly Variable<TextWriter?> logger = Statics.ThreadVariable<TextWriter?>("connectionlogger"); public static TextWriter? CurrentLogger { get { return logger.Value; } set { logger.Value = value; } } protected static void Log(SqlPreCommandSimple pcs) { var log = logger.Value; if (log != null) { log.WriteLine(pcs.Sql); if (pcs.Parameters != null) log.WriteLine(pcs.Parameters .ToString(p => "{0} {1}: {2}".FormatWith( p.ParameterName, Connector.Current.GetSqlDbType(p), p.Value?.Let(v => v.ToString())), "\r\n")); log.WriteLine(); } } public abstract string GetSqlDbType(DbParameter p); protected internal abstract object? ExecuteScalar(SqlPreCommandSimple preCommand, CommandType commandType); protected internal abstract int ExecuteNonQuery(SqlPreCommandSimple preCommand, CommandType commandType); protected internal abstract DataTable ExecuteDataTable(SqlPreCommandSimple preCommand, CommandType commandType); protected internal abstract DbDataReaderWithCommand UnsafeExecuteDataReader(SqlPreCommandSimple preCommand, CommandType commandType); protected internal abstract Task<DbDataReaderWithCommand> UnsafeExecuteDataReaderAsync(SqlPreCommandSimple preCommand, CommandType commandType, CancellationToken token); protected internal abstract void BulkCopy(DataTable dt, List<IColumn> columns, ObjectName destinationTable, SqlBulkCopyOptions options, int? timeout); public abstract Connector ForDatabase(Maps.DatabaseName? database); public abstract string DatabaseName(); public abstract string DataSourceName(); public abstract int MaxNameLength { get; } public abstract void SaveTransactionPoint(DbTransaction transaction, string savePointName); public abstract void RollbackTransactionPoint(DbTransaction Transaction, string savePointName); public abstract DbParameter CloneParameter(DbParameter p); public abstract DbConnection CreateConnection(); public IsolationLevel IsolationLevel { get; set; } public abstract ParameterBuilder ParameterBuilder { get; protected set; } public abstract void CleanDatabase(DatabaseName? database); public abstract bool AllowsMultipleQueries { get; } public abstract bool SupportsScalarSubquery { get; } public abstract bool SupportsScalarSubqueryInAggregates { get; } public static string? TryExtractDatabaseNameWithPostfix(ref string connectionString, string catalogPostfix) { string toFind = "+" + catalogPostfix; string? result = connectionString.TryBefore(toFind).TryAfterLast("="); if (result == null) return null; connectionString = connectionString.Replace(toFind, ""); // Remove toFind return result + catalogPostfix; } public static string ExtractCatalogPostfix(ref string connectionString, string catalogPostfix) { string toFind = "+" + catalogPostfix; int index = connectionString.IndexOf(toFind); if (index == -1) throw new InvalidOperationException("CatalogPostfix '{0}' not found in the connection string".FormatWith(toFind)); connectionString = connectionString.Substring(0, index) + connectionString.Substring(index + toFind.Length); // Remove toFind return catalogPostfix; } public abstract bool AllowsSetSnapshotIsolation { get; } public abstract bool AllowsIndexWithWhere(string where); public abstract bool AllowsConvertToDate { get; } public abstract bool AllowsConvertToTime { get; } public abstract bool SupportsSqlDependency { get; } public abstract bool SupportsFormat { get; } public abstract bool SupportsTemporalTables { get; } public abstract bool RequiresRetry { get; } } public abstract class ParameterBuilder { public static string GetParameterName(string name) { return "@" + name; } public DbParameter CreateReferenceParameter(string parameterName, PrimaryKey? id, IColumn column) { return CreateParameter(parameterName, column.DbType, null, column.Nullable.ToBool(), id == null ? null : id.Value.Object); } public DbParameter CreateParameter(string parameterName, object? value, Type type) { var pair = Schema.Current.Settings.GetSqlDbTypePair(type.UnNullify()); return CreateParameter(parameterName, pair.DbType, pair.UserDefinedTypeName, type == null || type.IsByRef || type.IsNullable(), value); } public abstract DbParameter CreateParameter(string parameterName, AbstractDbType dbType, string? udtTypeName, bool nullable, object? value); public abstract MemberInitExpression ParameterFactory(Expression parameterName, AbstractDbType dbType, string? udtTypeName, bool nullable, Expression value); protected static MethodInfo miAsserDateTime = ReflectionTools.GetMethodInfo(() => AssertDateTime(null)); protected static DateTime? AssertDateTime(DateTime? dateTime) { if (dateTime.HasValue) { if (Schema.Current.TimeZoneMode == TimeZoneMode.Utc && dateTime.Value.Kind != DateTimeKind.Utc) throw new InvalidOperationException("Attempt to use a non-Utc date in the database"); //Problematic with Time machine //if (Schema.Current.TimeZoneMode != TimeZoneMode.Utc && dateTime.Value.Kind == DateTimeKind.Utc) // throw new InvalidOperationException("Attempt to use a Utc date in the database"); } return dateTime; } } public class DbDataReaderWithCommand : IDisposable { public DbDataReaderWithCommand(DbCommand command, DbDataReader reader) { Command = command; Reader = reader; } public DbCommand Command { get; private set; } public DbDataReader Reader { get; private set; } public void Dispose() { Reader.Dispose(); } } }
// 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.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Cache FileCodeModel instances for a given project (we are using WeakReference for now, /// so that we can more or less match the semantics of the former native implementation, which /// offered reference equality until all instances were collected by the GC) /// </summary> internal sealed partial class CodeModelProjectCache { private readonly CodeModelState _state; private readonly AbstractProject _project; private readonly Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>(StringComparer.OrdinalIgnoreCase); private readonly object _cacheGate = new object(); private EnvDTE.CodeModel _rootCodeModel; private bool _zombied; internal CodeModelProjectCache(AbstractProject project, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace) { _project = project; _state = new CodeModelState(serviceProvider, languageServices, workspace); } private bool IsZombied { get { return _zombied; } } /// <summary> /// Look for an existing instance of FileCodeModel in our cache. /// Return null if there is no active FCM for "fileName". /// </summary> private CacheEntry? GetCacheEntry(string fileName) { lock (_cacheGate) { CacheEntry cacheEntry; if (_cache.TryGetValue(fileName, out cacheEntry)) { return cacheEntry; } } return null; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // This ultimately ends up calling GetOrCreateFileCodeModel(fileName, parent) with the correct "parent" object // through the project system. var provider = (IProjectCodeModelProvider)_project; var newFileCodeModel = (EnvDTE80.FileCodeModel2)provider.ProjectCodeModel.CreateFileCodeModelThroughProject(filePath); return new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(newFileCodeModel); } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? GetComHandleForFileCodeModel(string filePath) { var cacheEntry = GetCacheEntry(filePath); return cacheEntry != null ? cacheEntry.Value.ComHandle : null; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // Check that we know about this file! var hostDocument = _project.GetCurrentDocumentFromPath(filePath); if (hostDocument == null) { // Matches behavior of native (C#) implementation throw Exceptions.ThrowENotImpl(); } // Create object (outside of lock) var newFileCodeModel = FileCodeModel.Create(_state, parent, hostDocument.Id, new TextManagerAdapter()); var newCacheEntry = new CacheEntry(newFileCodeModel); // Second try (object might have been added by another thread at this point!) lock (_cacheGate) { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } // Note: Using the indexer here (instead of "Add") is relevant since the old // WeakReference entry is likely still in the cache (with a Null target, of course) _cache[filePath] = newCacheEntry; return newFileCodeModel; } } public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent) { if (this.IsZombied) { Debug.Fail("Cannot access root code model after code model was shutdown!"); throw Exceptions.ThrowEUnexpected(); } if (_rootCodeModel == null) { _rootCodeModel = RootCodeModel.Create(_state, parent, _project.Id); } return _rootCodeModel; } public IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetFileCodeModelInstances() { var result = new List<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>>(); lock (_cacheGate) { foreach (var cacheEntry in _cache.Values) { var comHandle = cacheEntry.ComHandle; if (comHandle != null) { result.Add(comHandle.Value); } } } return result; } public void OnProjectClosed() { var instances = GetFileCodeModelInstances(); lock (_cacheGate) { _cache.Clear(); } foreach (var instance in instances) { instance.Object.Shutdown(); } _zombied = false; } public void OnSourceFileRemoved(string fileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandle = null; lock (_cacheGate) { CacheEntry cacheEntry; if (_cache.TryGetValue(fileName, out cacheEntry)) { comHandle = cacheEntry.ComHandle; _cache.Remove(fileName); } } if (comHandle != null) { comHandle.Value.Object.Shutdown(); } } public void OnSourceFileRenaming(string oldFileName, string newFileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandle = null; lock (_cacheGate) { CacheEntry cacheEntry; if (_cache.TryGetValue(oldFileName, out cacheEntry)) { comHandle = cacheEntry.ComHandle; _cache.Remove(oldFileName); if (comHandle != null) { _cache.Add(newFileName, cacheEntry); } } } if (comHandle != null) { comHandle.Value.Object.OnRename(newFileName); } } } }
namespace java.util.jar { [global::MonoJavaBridge.JavaClass()] public partial class Attributes : java.lang.Object, Map, java.lang.Cloneable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Attributes(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class Name : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Name(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.jar.Attributes.Name.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.util.jar.Attributes.Name._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.jar.Attributes.Name.staticClass, "toString", "()Ljava/lang/String;", ref global::java.util.jar.Attributes.Name._m1) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m2; public override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.jar.Attributes.Name.staticClass, "hashCode", "()I", ref global::java.util.jar.Attributes.Name._m2); } private static global::MonoJavaBridge.MethodId _m3; public Name(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.jar.Attributes.Name._m3.native == global::System.IntPtr.Zero) global::java.util.jar.Attributes.Name._m3 = @__env.GetMethodIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "<init>", "(Ljava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.jar.Attributes.Name.staticClass, global::java.util.jar.Attributes.Name._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _MANIFEST_VERSION6837; public static global::java.util.jar.Attributes.Name MANIFEST_VERSION { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _MANIFEST_VERSION6837)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _SIGNATURE_VERSION6838; public static global::java.util.jar.Attributes.Name SIGNATURE_VERSION { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _SIGNATURE_VERSION6838)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _CONTENT_TYPE6839; public static global::java.util.jar.Attributes.Name CONTENT_TYPE { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _CONTENT_TYPE6839)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _CLASS_PATH6840; public static global::java.util.jar.Attributes.Name CLASS_PATH { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _CLASS_PATH6840)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _MAIN_CLASS6841; public static global::java.util.jar.Attributes.Name MAIN_CLASS { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _MAIN_CLASS6841)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _SEALED6842; public static global::java.util.jar.Attributes.Name SEALED { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _SEALED6842)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _EXTENSION_LIST6843; public static global::java.util.jar.Attributes.Name EXTENSION_LIST { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _EXTENSION_LIST6843)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _EXTENSION_NAME6844; public static global::java.util.jar.Attributes.Name EXTENSION_NAME { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _EXTENSION_NAME6844)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _EXTENSION_INSTALLATION6845; public static global::java.util.jar.Attributes.Name EXTENSION_INSTALLATION { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _EXTENSION_INSTALLATION6845)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _IMPLEMENTATION_TITLE6846; public static global::java.util.jar.Attributes.Name IMPLEMENTATION_TITLE { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _IMPLEMENTATION_TITLE6846)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _IMPLEMENTATION_VERSION6847; public static global::java.util.jar.Attributes.Name IMPLEMENTATION_VERSION { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _IMPLEMENTATION_VERSION6847)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _IMPLEMENTATION_VENDOR6848; public static global::java.util.jar.Attributes.Name IMPLEMENTATION_VENDOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _IMPLEMENTATION_VENDOR6848)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _IMPLEMENTATION_VENDOR_ID6849; public static global::java.util.jar.Attributes.Name IMPLEMENTATION_VENDOR_ID { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _IMPLEMENTATION_VENDOR_ID6849)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _IMPLEMENTATION_URL6850; public static global::java.util.jar.Attributes.Name IMPLEMENTATION_URL { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _IMPLEMENTATION_URL6850)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _SPECIFICATION_TITLE6851; public static global::java.util.jar.Attributes.Name SPECIFICATION_TITLE { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _SPECIFICATION_TITLE6851)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _SPECIFICATION_VERSION6852; public static global::java.util.jar.Attributes.Name SPECIFICATION_VERSION { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _SPECIFICATION_VERSION6852)) as java.util.jar.Attributes.Name; } } internal static global::MonoJavaBridge.FieldId _SPECIFICATION_VENDOR6853; public static global::java.util.jar.Attributes.Name SPECIFICATION_VENDOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.util.jar.Attributes.Name.staticClass, _SPECIFICATION_VENDOR6853)) as java.util.jar.Attributes.Name; } } static Name() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.jar.Attributes.Name.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/jar/Attributes$Name")); global::java.util.jar.Attributes.Name._MANIFEST_VERSION6837 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "MANIFEST_VERSION", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._SIGNATURE_VERSION6838 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "SIGNATURE_VERSION", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._CONTENT_TYPE6839 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "CONTENT_TYPE", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._CLASS_PATH6840 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "CLASS_PATH", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._MAIN_CLASS6841 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "MAIN_CLASS", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._SEALED6842 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "SEALED", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._EXTENSION_LIST6843 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "EXTENSION_LIST", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._EXTENSION_NAME6844 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "EXTENSION_NAME", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._EXTENSION_INSTALLATION6845 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "EXTENSION_INSTALLATION", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._IMPLEMENTATION_TITLE6846 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "IMPLEMENTATION_TITLE", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._IMPLEMENTATION_VERSION6847 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "IMPLEMENTATION_VERSION", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._IMPLEMENTATION_VENDOR6848 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "IMPLEMENTATION_VENDOR", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._IMPLEMENTATION_VENDOR_ID6849 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "IMPLEMENTATION_VENDOR_ID", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._IMPLEMENTATION_URL6850 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "IMPLEMENTATION_URL", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._SPECIFICATION_TITLE6851 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "SPECIFICATION_TITLE", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._SPECIFICATION_VERSION6852 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "SPECIFICATION_VERSION", "Ljava/util/jar/Attributes$Name;"); global::java.util.jar.Attributes.Name._SPECIFICATION_VENDOR6853 = @__env.GetStaticFieldIDNoThrow(global::java.util.jar.Attributes.Name.staticClass, "SPECIFICATION_VENDOR", "Ljava/util/jar/Attributes$Name;"); } } private static global::MonoJavaBridge.MethodId _m0; public virtual global::java.lang.Object get(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.jar.Attributes.staticClass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.util.jar.Attributes._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m1; public virtual global::java.lang.Object put(java.lang.Object arg0, java.lang.Object arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.jar.Attributes.staticClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.util.jar.Attributes._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m2; public override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.jar.Attributes.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.util.jar.Attributes._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.util.Collection values() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Collection>(this, global::java.util.jar.Attributes.staticClass, "values", "()Ljava/util/Collection;", ref global::java.util.jar.Attributes._m3) as java.util.Collection; } private static global::MonoJavaBridge.MethodId _m4; public override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.jar.Attributes.staticClass, "hashCode", "()I", ref global::java.util.jar.Attributes._m4); } private static global::MonoJavaBridge.MethodId _m5; public virtual global::java.lang.Object clone() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.jar.Attributes.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.util.jar.Attributes._m5) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m6; public virtual void clear() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.jar.Attributes.staticClass, "clear", "()V", ref global::java.util.jar.Attributes._m6); } private static global::MonoJavaBridge.MethodId _m7; public virtual bool isEmpty() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.jar.Attributes.staticClass, "isEmpty", "()Z", ref global::java.util.jar.Attributes._m7); } private static global::MonoJavaBridge.MethodId _m8; public virtual global::java.lang.String getValue(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.jar.Attributes.staticClass, "getValue", "(Ljava/lang/String;)Ljava/lang/String;", ref global::java.util.jar.Attributes._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m9; public virtual global::java.lang.String getValue(java.util.jar.Attributes.Name arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.jar.Attributes.staticClass, "getValue", "(Ljava/util/jar/Attributes$Name;)Ljava/lang/String;", ref global::java.util.jar.Attributes._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m10; public virtual int size() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.jar.Attributes.staticClass, "size", "()I", ref global::java.util.jar.Attributes._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.util.Set entrySet() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::java.util.jar.Attributes.staticClass, "entrySet", "()Ljava/util/Set;", ref global::java.util.jar.Attributes._m11) as java.util.Set; } private static global::MonoJavaBridge.MethodId _m12; public virtual void putAll(java.util.Map arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.jar.Attributes.staticClass, "putAll", "(Ljava/util/Map;)V", ref global::java.util.jar.Attributes._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m13; public virtual global::java.lang.Object remove(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.jar.Attributes.staticClass, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.util.jar.Attributes._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m14; public virtual global::java.util.Set keySet() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::java.util.jar.Attributes.staticClass, "keySet", "()Ljava/util/Set;", ref global::java.util.jar.Attributes._m14) as java.util.Set; } private static global::MonoJavaBridge.MethodId _m15; public virtual bool containsValue(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.jar.Attributes.staticClass, "containsValue", "(Ljava/lang/Object;)Z", ref global::java.util.jar.Attributes._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual bool containsKey(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.jar.Attributes.staticClass, "containsKey", "(Ljava/lang/Object;)Z", ref global::java.util.jar.Attributes._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public virtual global::java.lang.String putValue(java.lang.String arg0, java.lang.String arg1) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.jar.Attributes.staticClass, "putValue", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", ref global::java.util.jar.Attributes._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m18; public Attributes(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.jar.Attributes._m18.native == global::System.IntPtr.Zero) global::java.util.jar.Attributes._m18 = @__env.GetMethodIDNoThrow(global::java.util.jar.Attributes.staticClass, "<init>", "(I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.jar.Attributes.staticClass, global::java.util.jar.Attributes._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m19; public Attributes(java.util.jar.Attributes arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.jar.Attributes._m19.native == global::System.IntPtr.Zero) global::java.util.jar.Attributes._m19 = @__env.GetMethodIDNoThrow(global::java.util.jar.Attributes.staticClass, "<init>", "(Ljava/util/jar/Attributes;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.jar.Attributes.staticClass, global::java.util.jar.Attributes._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m20; public Attributes() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.jar.Attributes._m20.native == global::System.IntPtr.Zero) global::java.util.jar.Attributes._m20 = @__env.GetMethodIDNoThrow(global::java.util.jar.Attributes.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.jar.Attributes.staticClass, global::java.util.jar.Attributes._m20); Init(@__env, handle); } static Attributes() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.jar.Attributes.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/jar/Attributes")); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dataflow.V1Beta3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedJobsV1Beta3ClientSnippets { /// <summary>Snippet for CreateJob</summary> public void CreateJobRequestObject() { // Snippet: CreateJob(CreateJobRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) CreateJobRequest request = new CreateJobRequest { ProjectId = "", Job = new Job(), View = JobView.Unknown, ReplaceJobId = "", Location = "", }; // Make the request Job response = jobsV1Beta3Client.CreateJob(request); // End snippet } /// <summary>Snippet for CreateJobAsync</summary> public async Task CreateJobRequestObjectAsync() { // Snippet: CreateJobAsync(CreateJobRequest, CallSettings) // Additional: CreateJobAsync(CreateJobRequest, CancellationToken) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) CreateJobRequest request = new CreateJobRequest { ProjectId = "", Job = new Job(), View = JobView.Unknown, ReplaceJobId = "", Location = "", }; // Make the request Job response = await jobsV1Beta3Client.CreateJobAsync(request); // End snippet } /// <summary>Snippet for GetJob</summary> public void GetJobRequestObject() { // Snippet: GetJob(GetJobRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) GetJobRequest request = new GetJobRequest { ProjectId = "", JobId = "", View = JobView.Unknown, Location = "", }; // Make the request Job response = jobsV1Beta3Client.GetJob(request); // End snippet } /// <summary>Snippet for GetJobAsync</summary> public async Task GetJobRequestObjectAsync() { // Snippet: GetJobAsync(GetJobRequest, CallSettings) // Additional: GetJobAsync(GetJobRequest, CancellationToken) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) GetJobRequest request = new GetJobRequest { ProjectId = "", JobId = "", View = JobView.Unknown, Location = "", }; // Make the request Job response = await jobsV1Beta3Client.GetJobAsync(request); // End snippet } /// <summary>Snippet for UpdateJob</summary> public void UpdateJobRequestObject() { // Snippet: UpdateJob(UpdateJobRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) UpdateJobRequest request = new UpdateJobRequest { ProjectId = "", JobId = "", Job = new Job(), Location = "", }; // Make the request Job response = jobsV1Beta3Client.UpdateJob(request); // End snippet } /// <summary>Snippet for UpdateJobAsync</summary> public async Task UpdateJobRequestObjectAsync() { // Snippet: UpdateJobAsync(UpdateJobRequest, CallSettings) // Additional: UpdateJobAsync(UpdateJobRequest, CancellationToken) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) UpdateJobRequest request = new UpdateJobRequest { ProjectId = "", JobId = "", Job = new Job(), Location = "", }; // Make the request Job response = await jobsV1Beta3Client.UpdateJobAsync(request); // End snippet } /// <summary>Snippet for ListJobs</summary> public void ListJobsRequestObject() { // Snippet: ListJobs(ListJobsRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) ListJobsRequest request = new ListJobsRequest { ProjectId = "", Filter = ListJobsRequest.Types.Filter.Unknown, Location = "", }; // Make the request PagedEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.ListJobs(request); // Iterate over all response items, lazily performing RPCs as required foreach (Job item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListJobsAsync</summary> public async Task ListJobsRequestObjectAsync() { // Snippet: ListJobsAsync(ListJobsRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) ListJobsRequest request = new ListJobsRequest { ProjectId = "", Filter = ListJobsRequest.Types.Filter.Unknown, Location = "", }; // Make the request PagedAsyncEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.ListJobsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Job item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListJobs</summary> public void AggregatedListJobsRequestObject() { // Snippet: AggregatedListJobs(ListJobsRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) ListJobsRequest request = new ListJobsRequest { ProjectId = "", Filter = ListJobsRequest.Types.Filter.Unknown, Location = "", }; // Make the request PagedEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.AggregatedListJobs(request); // Iterate over all response items, lazily performing RPCs as required foreach (Job item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListJobsAsync</summary> public async Task AggregatedListJobsRequestObjectAsync() { // Snippet: AggregatedListJobsAsync(ListJobsRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) ListJobsRequest request = new ListJobsRequest { ProjectId = "", Filter = ListJobsRequest.Types.Filter.Unknown, Location = "", }; // Make the request PagedAsyncEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.AggregatedListJobsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Job item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Job item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Job> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Job item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for CheckActiveJobs</summary> public void CheckActiveJobsRequestObject() { // Snippet: CheckActiveJobs(CheckActiveJobsRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "", }; // Make the request CheckActiveJobsResponse response = jobsV1Beta3Client.CheckActiveJobs(request); // End snippet } /// <summary>Snippet for CheckActiveJobsAsync</summary> public async Task CheckActiveJobsRequestObjectAsync() { // Snippet: CheckActiveJobsAsync(CheckActiveJobsRequest, CallSettings) // Additional: CheckActiveJobsAsync(CheckActiveJobsRequest, CancellationToken) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "", }; // Make the request CheckActiveJobsResponse response = await jobsV1Beta3Client.CheckActiveJobsAsync(request); // End snippet } /// <summary>Snippet for SnapshotJob</summary> public void SnapshotJobRequestObject() { // Snippet: SnapshotJob(SnapshotJobRequest, CallSettings) // Create client JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create(); // Initialize request argument(s) SnapshotJobRequest request = new SnapshotJobRequest { ProjectId = "", JobId = "", Ttl = new Duration(), Location = "", SnapshotSources = false, Description = "", }; // Make the request Snapshot response = jobsV1Beta3Client.SnapshotJob(request); // End snippet } /// <summary>Snippet for SnapshotJobAsync</summary> public async Task SnapshotJobRequestObjectAsync() { // Snippet: SnapshotJobAsync(SnapshotJobRequest, CallSettings) // Additional: SnapshotJobAsync(SnapshotJobRequest, CancellationToken) // Create client JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync(); // Initialize request argument(s) SnapshotJobRequest request = new SnapshotJobRequest { ProjectId = "", JobId = "", Ttl = new Duration(), Location = "", SnapshotSources = false, Description = "", }; // Make the request Snapshot response = await jobsV1Beta3Client.SnapshotJobAsync(request); // End snippet } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Runtime.InteropServices; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Dtyp; using Microsoft.Protocols.TestTools.StackSdk.Messages.Marshaling; namespace Microsoft.Protocols.TestTools.StackSdk.ActiveDirectory { /// <summary> /// Enum for CLAIMS_SET compression /// </summary> public enum CLAIMS_COMPRESSION_FORMAT { COMPRESSION_FORMAT_NONE = 0x0, COMPRESSION_FORMAT_DEFAULT = 0x1, COMPRESSION_FORMAT_LZNT1 = 0x2, COMPRESSION_FORMAT_XPRESS = 0x3, COMPRESSION_FORMAT_XPRESS_HUFF = 0x4, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIMS_SET_METADATA { /// ULONG->unsigned int public uint ulClaimsSetSize; /// BYTE* [Size("ulClaimsSetSize")] public byte[] ClaimsSet; /// CLAIMS_COMPRESSION_FORMAT->_CLAIMS_FORMAT public CLAIMS_COMPRESSION_FORMAT usCompressionFormat; /// ULONG->unsigned int public uint ulUncompressedClaimsSetSize; /// USHORT->unsigned short public ushort usReservedType; /// ULONG->unsigned int public uint ulReservedFieldSize; /// BYTE* [Size("ulReservedFieldSize")] public byte[] ReservedField; } public enum CLAIMS_SOURCE_TYPE { /// CLAIMS_SOURCE_TYPE_AD -> 1 CLAIMS_SOURCE_TYPE_AD = 1, /// CLAIMS_SOURCE_TYPE_CERTIFICATE -> (CLAIMS_SOURCE_TYPE_AD+1) CLAIMS_SOURCE_TYPE_CERTIFICATE = (CLAIMS_SOURCE_TYPE.CLAIMS_SOURCE_TYPE_AD + 1), } public enum CLAIM_TYPE { /// CLAIM_TYPE_INT64 -> 1 CLAIM_TYPE_INT64 = 1, /// CLAIM_TYPE_UINT64 -> 2 CLAIM_TYPE_UINT64 = 2, /// CLAIM_TYPE_STRING -> 3 CLAIM_TYPE_STRING = 3, /// CLAIM_TYPE_BOOLEAN -> 6 CLAIM_TYPE_BOOLEAN = 6, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_TYPE_VALUE_INT64 { /// ULONG->unsigned int public uint ValueCount; /// LONG64* [Size("ValueCount")] [MarshalAs(UnmanagedType.ByValArray)] public Int64[] Int64Values; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_TYPE_VALUE_UINT64 { /// ULONG->unsigned int public uint ValueCount; /// ULONG64* [Size("ValueCount")] [MarshalAs(UnmanagedType.ByValArray)] public UInt64[] Uint64Values; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_TYPE_VALUE_LPWSTR { /// ULONG->unsigned int public uint ValueCount; /// LPWSTR* [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string[] StringValues; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_TYPE_VALUE_BOOL { /// ULONG->unsigned int public uint ValueCount; /// ULONG64* [MarshalAs(UnmanagedType.ByValArray)] public bool[] BooleanValues; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_TYPE_VALUE_BAD { public uint ValueCount; } [Union("Type")] [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_ENTRY_VALUE_UNION { /// Anonymous_b3e6089d_89ef_41e8_ab86_81e2f84c5ca8 CLAIM_TYPE_VALUE_BAD [Case("0")] // [System.Runtime.InteropServices.FieldOffsetAttribute(0)] public CLAIM_TYPE_VALUE_BAD Struct0; // /// Anonymous_b3e6089d_89ef_41e8_ab86_81e2f84c5ca8 [Case("1")] // [System.Runtime.InteropServices.FieldOffsetAttribute(0)] public CLAIM_TYPE_VALUE_INT64 Struct1; // /// Anonymous_d0149cae_14f4_4ea8_9d10_859e2367335b [Case("2")] // [System.Runtime.InteropServices.FieldOffsetAttribute(0)] public CLAIM_TYPE_VALUE_UINT64 Struct2; // /// Anonymous_81c16a4e_9b96_4b57_a7ed_fd2d06e6699e [Case("3")] // [System.Runtime.InteropServices.FieldOffsetAttribute(0)] public CLAIM_TYPE_VALUE_LPWSTR Struct3; // /// Anonymous_62b8cf30_3f61_49d3_b707_3808779f1319 [Case("6")] // [System.Runtime.InteropServices.FieldOffsetAttribute(0)] public CLAIM_TYPE_VALUE_BOOL Struct4; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIM_ENTRY { /// CLAIM_ID->wchar_t* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string Id; public CLAIM_TYPE Type; /// CLAIM_ENTRY_VALUE_UNION [Switch("Type")] public CLAIM_ENTRY_VALUE_UNION Values; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIMS_ARRAY { /// CLAIMS_SOURCE_TYPE->_CLAIMS_SOURCE_TYPE public short usClaimsSourceType; /// ULONG->unsigned int public uint ulClaimsCount; /// PCLAIM_ENTRY->_CLAIM_ENTRY* [Size("ulClaimsCount")] public CLAIM_ENTRY[] ClaimEntries; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct CLAIMS_SET { /// ULONG->unsigned int public uint ulClaimsArrayCount; /// PCLAIMS_ARRAY->_CLAIMS_ARRAY* [Size("ulClaimsArrayCount")] public CLAIMS_ARRAY[] ClaimsArrays; /// USHORT->unsigned short public ushort usReservedType; /// ULONG->unsigned int public uint ulReservedFieldSize; /// BYTE* [Size("ulReservedFieldSize")] public byte[] ReservedField; } }
// 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 Xunit; namespace System.IO.Tests { public class Directory_Delete_str : FileSystemTest { #region Utilities public virtual void Delete(string path) { Directory.Delete(path); } #endregion #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName)); } Assert.True(testDir.Exists); } [Fact] public void ShouldThrowIOExceptionForDirectoryWithFiles() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] public void DirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [OuterLoop] public void DeleteRoot() { Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory()))); } [Fact] public void PositiveTest() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] public void ShouldThrowDirectoryNotFoundExceptionForNonexistentDirectory() { Assert.Throws<DirectoryNotFoundException>(() => Delete(GetTestFilePath())); } [Fact] public void ShouldThrowIOExceptionDeletingCurrentDirectory() { Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory())); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void DeletingSymLinkDoesntDeleteTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); Directory.CreateDirectory(path); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true)); // Both the symlink and the target exist Assert.True(Directory.Exists(path), "path should exist"); Assert.True(Directory.Exists(linkPath), "linkPath should exist"); // Delete the symlink Directory.Delete(linkPath); // Target should still exist Assert.True(Directory.Exists(path), "path should still exist"); Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist"); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExtendedDirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsLongPathExtendedDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteExtendedReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixShouldBeAbleToDeleteHiddenDirectory() { string testDir = "." + GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, testDir)); Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden)); Delete(Path.Combine(TestDirectory, testDir)); Assert.False(Directory.Exists(testDir)); } #endregion } public class Directory_Delete_str_bool : Directory_Delete_str { #region Utilities public override void Delete(string path) { Directory.Delete(path, false); } public virtual void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } #endregion [Fact] public void RecursiveDelete() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); testDir.CreateSubdirectory(GetTestFileName()); Delete(testDir.FullName, true); Assert.False(testDir.Exists); } [Fact] public void RecursiveDeleteWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName + Path.DirectorySeparatorChar, true); Assert.False(testDir.Exists); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition { /// <summary> /// The exception that is thrown when one or more errors occur during composition. /// </summary> [DebuggerTypeProxy(typeof(CompositionExceptionDebuggerProxy))] [DebuggerDisplay("{Message}")] public class CompositionException : Exception { private readonly ReadOnlyCollection<CompositionError> _errors; /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class. /// </summary> public CompositionException() : this((string)null, (Exception)null, (IEnumerable<CompositionError>)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class /// with the specified error message. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionException"/>; or <see langword="null"/> to set /// the <see cref="Exception.Message"/> property to its default value. /// </param> public CompositionException(string message) : this(message, (Exception)null, (IEnumerable<CompositionError>)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class /// with the specified error message and exception that is the cause of the /// exception. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionException"/>; or <see langword="null"/> to set /// the <see cref="Exception.Message"/> property to its default value. /// </param> /// <param name="innerException"> /// The <see cref="Exception"/> that is the underlying cause of the /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>. /// </param> public CompositionException(string message, Exception innerException) : this(message, innerException, (IEnumerable<CompositionError>)null) { } internal CompositionException(CompositionError error) : this(new CompositionError[] { error }) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionException"/> class /// with the specified errors. /// </summary> /// <param name="errors"> /// An <see cref="IEnumerable{T}"/> of <see cref="CompositionError"/> objects /// representing the errors that are the cause of the /// <see cref="CompositionException"/>; or <see langword="null"/> to set the /// <see cref="Errors"/> property to an empty <see cref="IEnumerable{T}"/>. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="errors"/> contains an element that is <see langword="null"/>. /// </exception> public CompositionException(IEnumerable<CompositionError> errors) : this((string)null, (Exception)null, errors) { } internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors) : base(message, innerException) { Requires.NullOrNotNullElements(errors, nameof(errors)); _errors = new ReadOnlyCollection<CompositionError>(errors == null ? Array.Empty<CompositionError>() : errors.ToArray<CompositionError>()); } /// <summary> /// Gets the errors that are the cause of the exception. /// </summary> /// <value> /// An <see cref="IEnumerable{T}"/> of <see cref="CompositionError"/> objects /// representing the errors that are the cause of the /// <see cref="CompositionException"/>. /// </value> public ReadOnlyCollection<CompositionError> Errors { get { return _errors; } } /// <summary> /// Gets a message that describes the exception. /// </summary> /// <value> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionException"/>. /// </value> public override string Message { get { if (Errors.Count == 0) { // If there are no errors, then we simply return base.Message, // which will either use the default Exception message, or if // one was specified; the user supplied message. return base.Message; } return BuildDefaultMessage(); } } public ReadOnlyCollection<Exception> RootCauses { get { var errors = new List<Exception>(); // In here return a collection of all of the exceptions in the Errors collection foreach (var error in Errors) { if (error.Exception != null) { var ce = error.Exception as CompositionException; if (ce != null) { if (ce.RootCauses.Count > 0) { errors.AddRange(ce.RootCauses); continue; } } errors.Add(error.Exception); } } return errors.ToReadOnlyCollection<Exception>(); } } private string BuildDefaultMessage() { IEnumerable<IEnumerable<CompositionError>> paths = CalculatePaths(this); StringBuilder writer = new StringBuilder(); WriteHeader(writer, Errors.Count, paths.Count()); WritePaths(writer, paths); return writer.ToString(); } private static void WriteHeader(StringBuilder writer, int errorsCount, int pathCount) { if (errorsCount > 1 && pathCount > 1) { // The composition produced multiple composition errors, with {0} root causes. The root causes are provided below. writer.AppendFormat( CultureInfo.CurrentCulture, SR.CompositionException_MultipleErrorsWithMultiplePaths, pathCount); } else if (errorsCount == 1 && pathCount > 1) { // The composition produced a single composition error, with {0} root causes. The root causes are provided below. writer.AppendFormat( CultureInfo.CurrentCulture, SR.CompositionException_SingleErrorWithMultiplePaths, pathCount); } else { if (errorsCount != 1 || pathCount != 1) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } // The composition produced a single composition error. The root cause is provided below. writer.AppendFormat( CultureInfo.CurrentCulture, SR.CompositionException_SingleErrorWithSinglePath, pathCount); } writer.Append(' '); writer.AppendLine(SR.CompositionException_ReviewErrorProperty); } private static void WritePaths(StringBuilder writer, IEnumerable<IEnumerable<CompositionError>> paths) { int ordinal = 0; foreach (IEnumerable<CompositionError> path in paths) { ordinal++; WritePath(writer, path, ordinal); } } private static void WritePath(StringBuilder writer, IEnumerable<CompositionError> path, int ordinal) { writer.AppendLine(); writer.Append(ordinal.ToString(CultureInfo.CurrentCulture)); writer.Append(SR.CompositionException_PathsCountSeparator); writer.Append(' '); WriteError(writer, path.First()); foreach (CompositionError error in path.Skip(1)) { writer.AppendLine(); writer.Append(SR.CompositionException_ErrorPrefix); writer.Append(' '); WriteError(writer, error); } } private static void WriteError(StringBuilder writer, CompositionError error) { writer.AppendLine(error.Description); if (error.Element != null) { WriteElementGraph(writer, error.Element); } } private static void WriteElementGraph(StringBuilder writer, ICompositionElement element) { // Writes the composition element and its origins in the format: // Element: Export --> Part --> PartDefinition --> Catalog writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_ElementPrefix, element.DisplayName); while ((element = element.Origin) != null) { writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_OriginFormat, SR.CompositionException_OriginSeparator, element.DisplayName); } writer.AppendLine(); } private static IEnumerable<IEnumerable<CompositionError>> CalculatePaths(CompositionException exception) { List<IEnumerable<CompositionError>> paths = new List<IEnumerable<CompositionError>>(); VisitContext context = new VisitContext(); context.Path = new Stack<CompositionError>(); context.LeafVisitor = path => { // Take a snapshot of the path paths.Add(path.Copy()); }; VisitCompositionException(exception, context); return paths; } private static void VisitCompositionException(CompositionException exception, VisitContext context) { foreach (CompositionError error in exception.Errors) { VisitError(error, context); } if (exception.InnerException != null) { VisitException(exception.InnerException, context); } } private static void VisitError(CompositionError error, VisitContext context) { context.Path.Push(error); if (error.Exception == null) { // This error is a root cause, so write // out the stack from this point context.LeafVisitor(context.Path); } else { VisitException(error.Exception, context); } context.Path.Pop(); } private static void VisitException(Exception exception, VisitContext context) { CompositionException composition = exception as CompositionException; if (composition != null) { VisitCompositionException(composition, context); } else { VisitError(new CompositionError(exception.Message, exception.InnerException), context); } } private struct VisitContext { public Stack<CompositionError> Path; public Action<Stack<CompositionError>> LeafVisitor; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Security; using System.Diagnostics; namespace System.Runtime.InteropServices.WindowsRuntime { // // ICustomProperty implementation - basically a wrapper of PropertyInfo // // MCG emits references to this internal type into generated interop code, so we apply the [DependencyReductionRoot] // attribute to it so that it survives initial tree shaking. [System.Runtime.CompilerServices.DependencyReductionRootAttribute] internal sealed class CustomPropertyImpl : global::Windows.UI.Xaml.Data.ICustomProperty { /// <summary> /// The PropertyInfo for reflection /// It might be null if m_supportIndexerWithoutMetadata is true /// </summary> private PropertyInfo m_property; /// <summary> /// True if the property is a collection indexer that may not have metadata /// Typically a IList/IDictionary /// This is attempted as a fallback if metadata is not available or accessor is gone /// </summary> private bool m_supportIndexerWithoutMetadata; /// <summary> /// Type that contains an indexer that doesn't have metadata /// </summary> private Type m_indexerContainingType; // // Constructor // public CustomPropertyImpl(PropertyInfo propertyInfo, bool supportIndexerWithoutMetadata, Type indexerContainingType = null) { m_property = propertyInfo; m_supportIndexerWithoutMetadata = supportIndexerWithoutMetadata; m_indexerContainingType = indexerContainingType; } // // ICustomProperty interface implementation // public string Name { get { if (m_property != null) { return m_property.Name; } Debug.Assert(m_supportIndexerWithoutMetadata); return "Item"; } } public bool CanRead { get { return m_supportIndexerWithoutMetadata || (m_property.GetMethod != null && m_property.GetMethod.IsPublic); } } public bool CanWrite { get { return m_supportIndexerWithoutMetadata || (m_property.SetMethod != null && m_property.SetMethod.IsPublic); } } /// <summary> /// Verify caller has access to the getter/setter property /// Return true if we can use reflection to access the property. False otherwise. /// </summary> private bool CheckAccess(bool getValue) { // // If no property, there is nothing to check against // We'll use IList/IDictionary to access them // if (m_property == null) { Debug.Assert(m_supportIndexerWithoutMetadata); return false; } MethodInfo accessor = getValue ? m_property.GetMethod : m_property.SetMethod; if (accessor == null) { if (m_supportIndexerWithoutMetadata) { return false; } else { throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd); } } if (!accessor.IsPublic) { if (m_supportIndexerWithoutMetadata) { return false; } else { Exception ex = new MemberAccessException( String.Format( CultureInfo.CurrentCulture, SR.Arg_MethodAccessException_WithMethodName, accessor.ToString(), accessor.DeclaringType.FullName) ); // We need to make sure it has the same HR that we were returning in desktop InteropExtensions.SetExceptionErrorCode(ex, __HResults.COR_E_METHODACCESS); throw ex; } } return true; } internal static void LogDataBindingError(string propertyName, Exception ex) { string message = SR.Format(SR.CustomPropertyProvider_DataBindingError, propertyName, ex.Message); // Don't call Debug.WriteLine, since it only does anything in DEBUG builds. Instead, we call OutputDebugString directly. ExternalInterop.OutputDebugString(message); } public object GetValue(object target) { // This means you are calling GetValue on a index property if (m_supportIndexerWithoutMetadata) { throw new TargetParameterCountException(); } CheckAccess(getValue: true); try { return m_property.GetValue(UnwrapTarget(target)); } catch (MemberAccessException ex) { LogDataBindingError(Name, ex); throw; } } public void SetValue(object target, object value) { // This means you are calling SetValue on a index property if (m_supportIndexerWithoutMetadata) { throw new TargetParameterCountException(); } CheckAccess(getValue: false); try { m_property.SetValue(UnwrapTarget(target), value); } catch (MemberAccessException ex) { LogDataBindingError(Name, ex); throw; } } public Type Type { get { if (m_property != null) { return m_property.PropertyType; } // // Calculate the property type from IList/IDictionary // Debug.Assert(m_supportIndexerWithoutMetadata); // The following calls look like reflection, but don't require metadata, // so they work on all types. Type indexType = null; TypeInfo containingTypeInfo = m_indexerContainingType.GetTypeInfo(); foreach (Type itf in containingTypeInfo.ImplementedInterfaces) { if (!itf.IsConstructedGenericType) { continue; } Type genericItf = itf.GetGenericTypeDefinition(); if (genericItf.Equals(typeof(IList<>))) { Type listArg = itf.GenericTypeArguments[0]; if (indexType != null && !indexType.Equals(listArg)) { throw new MissingMetadataException(); } indexType = listArg; } else if (genericItf.Equals(typeof(IDictionary<,>))) { Type dictionaryArg = itf.GenericTypeArguments[1]; if (indexType != null && !indexType.Equals(dictionaryArg)) { throw new MissingMetadataException(); } indexType = dictionaryArg; } } if (indexType == null) { throw new MissingMetadataException(); } return indexType; } } // Unlike normal .Net, Jupiter properties can have at most one indexer parameter. A null // indexValue here means that the property has an indexer argument and its value is null. public object GetIndexedValue(object target, object index) { bool supportPropertyAccess = CheckAccess(getValue: true); object unwrappedTarget = UnwrapTarget(target); // // If we can use reflection, go with reflection // If it fails, we would simply throw and not fallback to IList/IDictionary // if (m_property != null && supportPropertyAccess) { try { return m_property.GetValue(unwrappedTarget, new object[] { index }); } catch (MemberAccessException ex) { LogDataBindingError(Name, ex); throw; } } // // If reflection is not supported, fallback to IList/IDictionary indexer // If fallback is not possible, we would've failed earlier // Debug.Assert(m_supportIndexerWithoutMetadata); IDictionary dictionary = unwrappedTarget as IDictionary; if (dictionary != null) { return dictionary[index]; } IList list = (IList) unwrappedTarget; return list[Convert.ToInt32(index)]; } // Unlike normal .Net, Jupiter properties can have at most one indexer parameter. A null // indexValue here means that the property has an indexer argument and its value is null. public void SetIndexedValue(object target, object value, object index) { bool supportPropertyAccess = CheckAccess(getValue: false); object unwrappedTarget = UnwrapTarget(target); // // If we can use reflection, go with reflection // If it fails, we would simply throw and not fallback to IList/IDictionary // if (m_property != null && supportPropertyAccess) { try { m_property.SetValue(unwrappedTarget, value, new object[] { index }); return; } catch (MemberAccessException ex) { LogDataBindingError(Name, ex); throw; } } // // If reflection is not supported, fallback to IList/IDictionary indexer // If fallback is not possible, we would've failed earlier // Debug.Assert(m_supportIndexerWithoutMetadata); IDictionary dictionary = unwrappedTarget as IDictionary; if (dictionary != null) { dictionary[index] = value; return; } IList list = (IList) unwrappedTarget; list[Convert.ToInt32(index)] = value; } public static object UnwrapTarget(object target) { // // If target is a managed wrapper, we should unwrap it and use its target for data binding // For example, you don't want to data bind against a KeyValuePairImpl<K, V> - you want the real // KeyValuePair<K, V> // object newTarget = McgComHelpers.UnboxManagedWrapperIfBoxed(target); if (newTarget != target) return newTarget; if (target is __ComObject) { object winrtUnboxed = McgMarshal.UnboxIfBoxed(target); if (winrtUnboxed != null) return winrtUnboxed; } return target; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using BTDB.KVDBLayer; using Xunit; namespace BTDBTest { public class InMemoryInMemoryKeyValueDBTest { [Fact] public void CreateEmptyDatabase() { using (new InMemoryKeyValueDB()) { } } [Fact] public void EmptyTransaction() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.Commit(); } [Fact] public void EmptyWritingTransaction() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartWritingTransaction().Result; tr.Commit(); } [Fact] public void FirstTransaction() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); Assert.True(tr.CreateOrUpdateKeyValue(_key1, ReadOnlySpan<byte>.Empty)); tr.Commit(); } [Fact] public void CanGetSizeOfPair() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.CreateOrUpdateKeyValue(_key1, new byte[1]); var s = tr.GetStorageSizeOfCurrentKey(); Assert.Equal(_key1.Length, (int)s.Key); Assert.Equal(1u, s.Value); } [Fact] public void FirstTransactionIsNumber1() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); Assert.Equal(0, tr.GetTransactionNumber()); Assert.True(tr.CreateOrUpdateKeyValue(_key1, new byte[0])); Assert.Equal(1, tr.GetTransactionNumber()); tr.Commit(); } [Fact] public void ReadOnlyTransactionThrowsOnWriteAccess() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartReadOnlyTransaction(); Assert.Throws<BTDBTransactionRetryException>(() => tr.CreateKey(new byte[1])); } [Fact] public void MoreComplexTransaction() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); Assert.True(tr.CreateOrUpdateKeyValue(_key1, ReadOnlySpan<byte>.Empty)); Assert.False(tr.CreateOrUpdateKeyValue(_key1, ReadOnlySpan<byte>.Empty)); Assert.Equal(FindResult.Previous, tr.Find(_key2, 0)); Assert.True(tr.CreateOrUpdateKeyValue(_key2, ReadOnlySpan<byte>.Empty)); Assert.Equal(FindResult.Exact, tr.Find(_key1, 0)); Assert.Equal(FindResult.Exact, tr.Find(_key2, 0)); Assert.Equal(FindResult.Previous, tr.Find(_key3, 0)); Assert.Equal(FindResult.Next, tr.Find(ReadOnlySpan<byte>.Empty, 0)); tr.Commit(); } [Fact] public void CommitWorks() { using (IKeyValueDB db = new InMemoryKeyValueDB()) { using (var tr1 = db.StartTransaction()) { tr1.CreateKey(_key1); using (var tr2 = db.StartTransaction()) { Assert.Equal(0, tr2.GetTransactionNumber()); Assert.False(tr2.FindExactKey(_key1)); } tr1.Commit(); } using (var tr3 = db.StartTransaction()) { Assert.Equal(1, tr3.GetTransactionNumber()); Assert.True(tr3.FindExactKey(_key1)); } } } [Fact] public void CommitWithUlongWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { Assert.Equal(0ul, tr1.GetCommitUlong()); tr1.SetCommitUlong(42); tr1.Commit(); } using (var tr2 = db.StartTransaction()) { Assert.Equal(42ul, tr2.GetCommitUlong()); } } [Fact] public void RollbackWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { tr1.CreateKey(_key1); // Rollback because of missing commit } using (var tr2 = db.StartTransaction()) { Assert.Equal(0, tr2.GetTransactionNumber()); Assert.False(tr2.FindExactKey(_key1)); } } [Fact] public void OnlyOneWritingTransactionPossible() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr1 = db.StartTransaction(); tr1.CreateKey(_key1); using var tr2 = db.StartTransaction(); Assert.False(tr2.FindExactKey(_key1)); Assert.Throws<BTDBTransactionRetryException>(() => tr2.CreateKey(_key2)); } [Fact] public void OnlyOneWritingTransactionPossible2() { using IKeyValueDB db = new InMemoryKeyValueDB(); var tr1 = db.StartTransaction(); tr1.CreateKey(_key1); using var tr2 = db.StartTransaction(); tr1.Commit(); tr1.Dispose(); Assert.False(tr2.FindExactKey(_key1)); Assert.Throws<BTDBTransactionRetryException>(() => tr2.CreateKey(_key2)); } [Fact] public void TwoEmptyWriteTransactionsWithNestedWaiting() { using IKeyValueDB db = new InMemoryKeyValueDB(); Task<IKeyValueDBTransaction> trOuter; using (var tr = db.StartWritingTransaction().Result) { trOuter = db.StartWritingTransaction().AsTask(); tr.Commit(); } using (var tr = trOuter.Result) { tr.Commit(); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(5000)] [InlineData(1200000)] public void BiggerKey(int keyLength) { var key = new byte[keyLength]; for (var i = 0; i < keyLength; i++) key[i] = (byte)i; using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { tr1.CreateKey(key); tr1.Commit(); } using (var tr2 = db.StartTransaction()) { Assert.True(tr2.FindExactKey(key)); Assert.Equal(key, tr2.GetKey().ToArray()); } } [Fact] public void TwoTransactions() { using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { tr1.CreateKey(_key1); tr1.Commit(); } using (var tr2 = db.StartTransaction()) { tr2.CreateKey(_key2); Assert.True(tr2.FindExactKey(_key1)); Assert.True(tr2.FindExactKey(_key2)); Assert.False(tr2.FindExactKey(_key3)); tr2.Commit(); } using (var tr3 = db.StartTransaction()) { Assert.True(tr3.FindExactKey(_key1)); Assert.True(tr3.FindExactKey(_key2)); Assert.False(tr3.FindExactKey(_key3)); } } [Theory] [InlineData(1000)] public void MultipleTransactions(int transactionCount) { using IKeyValueDB db = new InMemoryKeyValueDB(); var key = new byte[2 + transactionCount * 10]; for (var i = 0; i < transactionCount; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); using var tr1 = db.StartTransaction(); tr1.CreateOrUpdateKeyValue(key.AsSpan(0, 2 + i * 10), ReadOnlySpan<byte>.Empty); if (i % 100 == 0 || i == transactionCount - 1) { for (var j = 0; j < i; j++) { key[0] = (byte)(j / 256); key[1] = (byte)(j % 256); Assert.Equal(FindResult.Exact, tr1.Find(key.AsSpan(0, 2 + j * 10), 0)); } } tr1.Commit(); } } [Theory] [InlineData(1000)] public void MultipleTransactions2(int transactionCount) { using IKeyValueDB db = new InMemoryKeyValueDB(); var key = new byte[2 + transactionCount * 10]; for (var i = 0; i < transactionCount; i++) { key[0] = (byte)((transactionCount - i) / 256); key[1] = (byte)((transactionCount - i) % 256); using var tr1 = db.StartTransaction(); tr1.CreateOrUpdateKeyValue(key.AsSpan(0, 2 + i * 10), ReadOnlySpan<byte>.Empty); if (i % 100 == 0 || i == transactionCount - 1) { for (var j = 0; j < i; j++) { key[0] = (byte)((transactionCount - j) / 256); key[1] = (byte)((transactionCount - j) % 256); Assert.Equal(FindResult.Exact, tr1.Find(key.AsSpan(0, 2 + j * 10), 0)); } } tr1.Commit(); } } [Fact] public void SimpleFindPreviousKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { tr1.CreateKey(_key1); tr1.CreateKey(_key2); tr1.CreateKey(_key3); tr1.Commit(); } using (var tr2 = db.StartTransaction()) { Assert.True(tr2.FindExactKey(_key3)); Assert.True(tr2.FindPreviousKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(_key1, tr2.GetKey().ToArray()); Assert.False(tr2.FindPreviousKey(ReadOnlySpan<byte>.Empty)); } } [Fact] public void FindKeyWithPreferPreviousKeyWorks() { const int keyCount = 10000; using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr = db.StartTransaction()) { var key = new byte[100]; for (var i = 0; i < keyCount; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); tr.CreateKey(key); } tr.Commit(); } using (var tr = db.StartTransaction()) { var key = new byte[101]; for (var i = 0; i < keyCount; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); var findKeyResult = tr.Find(key, 0); Assert.Equal(FindResult.Previous, findKeyResult); Assert.Equal(i, tr.GetKeyIndex()); } } using (var tr = db.StartTransaction()) { var key = new byte[99]; for (var i = 0; i < keyCount; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); var findKeyResult = tr.Find(key, 0); if (i == 0) { Assert.Equal(FindResult.Next, findKeyResult); Assert.Equal(i, tr.GetKeyIndex()); } else { Assert.Equal(FindResult.Previous, findKeyResult); Assert.Equal(i - 1, tr.GetKeyIndex()); } } } } [Fact] public void SimpleFindNextKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { tr1.CreateKey(_key1); tr1.CreateKey(_key2); tr1.CreateKey(_key3); tr1.Commit(); } using (var tr2 = db.StartTransaction()) { Assert.True(tr2.FindExactKey(_key3)); Assert.True(tr2.FindNextKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(_key2, tr2.GetKey().ToArray()); Assert.False(tr2.FindNextKey(ReadOnlySpan<byte>.Empty)); } } [Fact] public void AdvancedFindPreviousAndNextKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); var key = new byte[2]; const int keysCreated = 10000; using (var tr = db.StartTransaction()) { for (var i = 0; i < keysCreated; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); tr.CreateKey(key); } tr.Commit(); } using (var tr = db.StartTransaction()) { Assert.Equal(-1, tr.GetKeyIndex()); tr.FindExactKey(key); Assert.Equal(keysCreated - 1, tr.GetKeyIndex()); for (var i = 1; i < keysCreated; i++) { Assert.True(tr.FindPreviousKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(keysCreated - 1 - i, tr.GetKeyIndex()); } Assert.False(tr.FindPreviousKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(-1, tr.GetKeyIndex()); for (var i = 0; i < keysCreated; i++) { Assert.True(tr.FindNextKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(i, tr.GetKeyIndex()); } Assert.False(tr.FindNextKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(-1, tr.GetKeyIndex()); } } [Fact] public void SetKeyIndexWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); var key = new byte[2]; const int keysCreated = 10000; using (var tr = db.StartTransaction()) { for (var i = 0; i < keysCreated; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); tr.CreateKey(key); } tr.Commit(); } using (var tr = db.StartTransaction()) { Assert.False(tr.SetKeyIndex(keysCreated)); for (var i = 0; i < keysCreated; i += 5) { Assert.True(tr.SetKeyIndex(i)); key = tr.GetKey().ToArray(); Assert.Equal((byte)(i / 256), key[0]); Assert.Equal((byte)(i % 256), key[1]); Assert.Equal(i, tr.GetKeyIndex()); } } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] [InlineData(7)] [InlineData(8)] [InlineData(256)] [InlineData(5000)] [InlineData(10000000)] public void CreateOrUpdateKeyValueWorks(int length) { var valbuf = new byte[length]; new Random(0).NextBytes(valbuf); using IKeyValueDB db = new InMemoryKeyValueDB(); using (var tr1 = db.StartTransaction()) { Assert.True(tr1.CreateOrUpdateKeyValue(_key1, valbuf)); Assert.False(tr1.CreateOrUpdateKeyValue(_key1, valbuf)); Assert.True(tr1.CreateOrUpdateKeyValue(_key2, valbuf)); tr1.Commit(); } using (var tr2 = db.StartTransaction()) { Assert.True(tr2.FindExactKey(_key1)); var valbuf2 = tr2.GetValue(); for (var i = 0; i < length; i++) { if (valbuf[i] != valbuf2[i]) Assert.Equal(valbuf[i], valbuf2[i]); } Assert.True(tr2.FindExactKey(_key2)); valbuf2 = tr2.GetValue(); for (var i = 0; i < length; i++) { if (valbuf[i] != valbuf2[i]) Assert.Equal(valbuf[i], valbuf2[i]); } } } [Fact] public void FindFirstKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); Assert.False(tr.FindFirstKey(ReadOnlySpan<byte>.Empty)); tr.CreateKey(_key1); tr.CreateKey(_key2); tr.CreateKey(_key3); Assert.True(tr.FindFirstKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(_key1, tr.GetKey().ToArray()); tr.Commit(); } [Fact] public void FindLastKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); Assert.False(tr.FindLastKey(ReadOnlySpan<byte>.Empty)); tr.CreateKey(_key1); tr.CreateKey(_key2); tr.CreateKey(_key3); Assert.True(tr.FindLastKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(_key2, tr.GetKey().ToArray()); tr.Commit(); } [Fact] public void SimplePrefixWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.CreateKey(_key1); tr.CreateKey(_key2); tr.CreateKey(_key3); Assert.Equal(3, tr.GetKeyValueCount()); Assert.Equal(2, tr.GetKeyValueCount(_key1)); tr.FindFirstKey(_key1.AsSpan(0, 3)); Assert.Equal(_key1, tr.GetKey().ToArray()); tr.FindLastKey(_key1.AsSpan(0, 3)); Assert.Equal(_key3, tr.GetKey().ToArray()); tr.Commit(); } [Fact] public void PrefixWithFindNextKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.CreateKey(_key1); tr.CreateKey(_key2); Assert.True(tr.FindFirstKey(_key2.AsSpan(0, 1))); Assert.True(tr.FindNextKey(_key2.AsSpan(0, 1))); Assert.False(tr.FindNextKey(_key2.AsSpan(0, 1))); tr.Commit(); } [Fact] public void PrefixWithFindPrevKeyWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.CreateKey(_key1); tr.CreateKey(_key2); Assert.True(tr.FindFirstKey(_key2.AsSpan(0, 1))); Assert.False(tr.FindPreviousKey(_key2.AsSpan(0, 1))); tr.Commit(); } [Fact] public void SimpleEraseCurrentWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.CreateKey(_key1); tr.CreateKey(_key2); tr.CreateKey(_key3); tr.EraseCurrent(); Assert.True(tr.FindFirstKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(_key1, tr.GetKey().ToArray()); Assert.True(tr.FindNextKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(_key2, tr.GetKey().ToArray()); Assert.False(tr.FindNextKey(ReadOnlySpan<byte>.Empty)); Assert.Equal(2, tr.GetKeyValueCount()); } [Fact] public void AdvancedEraseRangeWorks() { foreach (var range in EraseRangeSource()) AdvancedEraseRangeWorksCore(range[0], range[1], range[2]); } void AdvancedEraseRangeWorksCore(int createKeys, int removeStart, int removeCount) { using IKeyValueDB db = new InMemoryKeyValueDB(); var key = new byte[2]; using (var tr = db.StartTransaction()) { for (var i = 0; i < createKeys; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); tr.CreateKey(key); } tr.Commit(); } using (var tr = db.StartTransaction()) { tr.EraseRange(removeStart, removeStart + removeCount - 1); Assert.Equal(createKeys - removeCount, tr.GetKeyValueCount()); tr.Commit(); } using (var tr = db.StartTransaction()) { Assert.Equal(createKeys - removeCount, tr.GetKeyValueCount()); for (var i = 0; i < createKeys; i++) { key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); if (i >= removeStart && i < removeStart + removeCount) { Assert.False(tr.FindExactKey(key), $"{i} should be removed"); } else { Assert.True(tr.FindExactKey(key), $"{i} should be found"); } } } } // ReSharper disable UnusedMember.Global public static IEnumerable<int[]> EraseRangeSource() // ReSharper restore UnusedMember.Global { yield return new[] { 1, 0, 1 }; for (var i = 11; i < 1000; i += i) { yield return new[] { i, 0, 1 }; yield return new[] { i, i - 1, 1 }; yield return new[] { i, i / 2, 1 }; yield return new[] { i, i / 2, i / 4 }; yield return new[] { i, i / 4, 1 }; yield return new[] { i, i / 4, i / 2 }; yield return new[] { i, i - i / 2, i / 2 }; yield return new[] { i, 0, i / 2 }; yield return new[] { i, 3 * i / 4, 1 }; yield return new[] { i, 0, i }; } } [Fact] public void ALotOf5KbTransactionsWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); for (var i = 0; i < 5000; i++) { var key = new byte[5000]; using var tr = db.StartTransaction(); key[0] = (byte)(i / 256); key[1] = (byte)(i % 256); Assert.True(tr.CreateKey(key)); tr.Commit(); } } [Fact] public void SetKeyPrefixInOneTransaction() { using IKeyValueDB db = new InMemoryKeyValueDB(); var key = new byte[5]; var value = new byte[100]; var rnd = new Random(); using (var tr = db.StartTransaction()) { for (byte i = 0; i < 100; i++) { key[0] = i; for (byte j = 0; j < 100; j++) { key[4] = j; rnd.NextBytes(value); tr.CreateOrUpdateKeyValue(key, value); } } tr.Commit(); } using (var tr = db.StartTransaction()) { for (byte i = 0; i < 100; i++) { key[0] = i; Assert.Equal(100, tr.GetKeyValueCount(key.AsSpan(0, 4))); } } } [Fact] public void CompressibleValueLoad() { using IKeyValueDB db = new InMemoryKeyValueDB(); using var tr = db.StartTransaction(); tr.CreateOrUpdateKeyValue(_key1, new byte[1000]); Assert.Equal(new byte[1000], tr.GetValue().ToArray()); tr.Commit(); } [Fact] public void StartWritingTransactionWorks() { using IKeyValueDB db = new InMemoryKeyValueDB(); var tr1 = db.StartWritingTransaction().Result; var tr2Task = db.StartWritingTransaction(); var task = Task.Factory.StartNew(() => { var tr2 = tr2Task.Result; Assert.True(tr2.FindExactKey(_key1)); tr2.CreateKey(_key2); tr2.Commit(); tr2.Dispose(); }); tr1.CreateKey(_key1); tr1.Commit(); tr1.Dispose(); task.Wait(1000); using var tr = db.StartTransaction(); Assert.True(tr.FindExactKey(_key1)); Assert.True(tr.FindExactKey(_key2)); } readonly byte[] _key1 = { 1, 2, 3 }; readonly byte[] _key2 = { 1, 3, 2 }; readonly byte[] _key3 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; } }
using System; using ChainUtils.BouncyCastle.Crypto.Digests; using ChainUtils.BouncyCastle.Crypto.Modes; using ChainUtils.BouncyCastle.Crypto.Parameters; using ChainUtils.BouncyCastle.Security; using ChainUtils.BouncyCastle.Utilities; namespace ChainUtils.BouncyCastle.Crypto.Engines { /** * Wrap keys according to * <a href="http://www.ietf.org/internet-drafts/draft-ietf-smime-key-wrap-01.txt"> * draft-ietf-smime-key-wrap-01.txt</a>. * <p> * Note: * <ul> * <li>this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.</li> * <li>if you are using this to wrap triple-des keys you need to set the * parity bits on the key and, if it's a two-key triple-des key, pad it * yourself.</li> * </ul> * </p> */ public class DesEdeWrapEngine : IWrapper { /** Field engine */ private CbcBlockCipher engine; /** Field param */ private KeyParameter param; /** Field paramPlusIV */ private ParametersWithIV paramPlusIV; /** Field iv */ private byte[] iv; /** Field forWrapping */ private bool forWrapping; /** Field IV2 */ private static readonly byte[] IV2 = { (byte) 0x4a, (byte) 0xdd, (byte) 0xa2, (byte) 0x2c, (byte) 0x79, (byte) 0xe8, (byte) 0x21, (byte) 0x05 }; // // checksum digest // private readonly IDigest sha1 = new Sha1Digest(); private readonly byte[] digest = new byte[20]; /** * Method init * * @param forWrapping * @param param */ public void Init( bool forWrapping, ICipherParameters parameters) { this.forWrapping = forWrapping; engine = new CbcBlockCipher(new DesEdeEngine()); SecureRandom sr; if (parameters is ParametersWithRandom) { var pr = (ParametersWithRandom) parameters; parameters = pr.Parameters; sr = pr.Random; } else { sr = new SecureRandom(); } if (parameters is KeyParameter) { param = (KeyParameter) parameters; if (this.forWrapping) { // Hm, we have no IV but we want to wrap ?!? // well, then we have to create our own IV. iv = new byte[8]; sr.NextBytes(iv); paramPlusIV = new ParametersWithIV(param, iv); } } else if (parameters is ParametersWithIV) { if (!forWrapping) throw new ArgumentException("You should not supply an IV for unwrapping"); paramPlusIV = (ParametersWithIV) parameters; iv = paramPlusIV.GetIV(); param = (KeyParameter) paramPlusIV.Parameters; if (iv.Length != 8) throw new ArgumentException("IV is not 8 octets", "parameters"); } } /** * Method GetAlgorithmName * * @return */ public string AlgorithmName { get { return "DESede"; } } /** * Method wrap * * @param in * @param inOff * @param inLen * @return */ public byte[] Wrap( byte[] input, int inOff, int length) { if (!forWrapping) { throw new InvalidOperationException("Not initialized for wrapping"); } var keyToBeWrapped = new byte[length]; Array.Copy(input, inOff, keyToBeWrapped, 0, length); // Compute the CMS Key Checksum, (section 5.6.1), call this CKS. var CKS = CalculateCmsKeyChecksum(keyToBeWrapped); // Let WKCKS = WK || CKS where || is concatenation. var WKCKS = new byte[keyToBeWrapped.Length + CKS.Length]; Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length); Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length); // Encrypt WKCKS in CBC mode using KEK as the key and IV as the // initialization vector. Call the results TEMP1. var blockSize = engine.GetBlockSize(); if (WKCKS.Length % blockSize != 0) throw new InvalidOperationException("Not multiple of block length"); engine.Init(true, paramPlusIV); var TEMP1 = new byte[WKCKS.Length]; for (var currentBytePos = 0; currentBytePos != WKCKS.Length; currentBytePos += blockSize) { engine.ProcessBlock(WKCKS, currentBytePos, TEMP1, currentBytePos); } // Let TEMP2 = IV || TEMP1. var TEMP2 = new byte[iv.Length + TEMP1.Length]; Array.Copy(iv, 0, TEMP2, 0, iv.Length); Array.Copy(TEMP1, 0, TEMP2, iv.Length, TEMP1.Length); // Reverse the order of the octets in TEMP2 and call the result TEMP3. var TEMP3 = reverse(TEMP2); // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired // result. It is 40 octets long if a 168 bit key is being wrapped. var param2 = new ParametersWithIV(param, IV2); engine.Init(true, param2); for (var currentBytePos = 0; currentBytePos != TEMP3.Length; currentBytePos += blockSize) { engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos); } return TEMP3; } /** * Method unwrap * * @param in * @param inOff * @param inLen * @return * @throws InvalidCipherTextException */ public byte[] Unwrap( byte[] input, int inOff, int length) { if (forWrapping) { throw new InvalidOperationException("Not set for unwrapping"); } if (input == null) { throw new InvalidCipherTextException("Null pointer as ciphertext"); } var blockSize = engine.GetBlockSize(); if (length % blockSize != 0) { throw new InvalidCipherTextException("Ciphertext not multiple of " + blockSize); } /* // Check if the length of the cipher text is reasonable given the key // type. It must be 40 bytes for a 168 bit key and either 32, 40, or // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported // or inconsistent with the algorithm for which the key is intended, // return error. // // we do not accept 168 bit keys. it has to be 192 bit. int lengthA = (estimatedKeyLengthInBit / 8) + 16; int lengthB = estimatedKeyLengthInBit % 8; if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) { throw new XMLSecurityException("empty"); } */ // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3. var param2 = new ParametersWithIV(param, IV2); engine.Init(false, param2); var TEMP3 = new byte[length]; for (var currentBytePos = 0; currentBytePos != TEMP3.Length; currentBytePos += blockSize) { engine.ProcessBlock(input, inOff + currentBytePos, TEMP3, currentBytePos); } // Reverse the order of the octets in TEMP3 and call the result TEMP2. var TEMP2 = reverse(TEMP3); // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets. iv = new byte[8]; var TEMP1 = new byte[TEMP2.Length - 8]; Array.Copy(TEMP2, 0, iv, 0, 8); Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8); // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV // found in the previous step. Call the result WKCKS. paramPlusIV = new ParametersWithIV(param, iv); engine.Init(false, paramPlusIV); var WKCKS = new byte[TEMP1.Length]; for (var currentBytePos = 0; currentBytePos != WKCKS.Length; currentBytePos += blockSize) { engine.ProcessBlock(TEMP1, currentBytePos, WKCKS, currentBytePos); } // Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are // those octets before the CKS. var result = new byte[WKCKS.Length - 8]; var CKStoBeVerified = new byte[8]; Array.Copy(WKCKS, 0, result, 0, WKCKS.Length - 8); Array.Copy(WKCKS, WKCKS.Length - 8, CKStoBeVerified, 0, 8); // Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare // with the CKS extracted in the above step. If they are not equal, return error. if (!CheckCmsKeyChecksum(result, CKStoBeVerified)) { throw new InvalidCipherTextException( "Checksum inside ciphertext is corrupted"); } // WK is the wrapped key, now extracted for use in data decryption. return result; } /** * Some key wrap algorithms make use of the Key Checksum defined * in CMS [CMS-Algorithms]. This is used to provide an integrity * check value for the key being wrapped. The algorithm is * * - Compute the 20 octet SHA-1 hash on the key being wrapped. * - Use the first 8 octets of this hash as the checksum value. * * @param key * @return * @throws Exception * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum */ private byte[] CalculateCmsKeyChecksum( byte[] key) { sha1.BlockUpdate(key, 0, key.Length); sha1.DoFinal(digest, 0); var result = new byte[8]; Array.Copy(digest, 0, result, 0, 8); return result; } /** * @param key * @param checksum * @return * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum */ private bool CheckCmsKeyChecksum( byte[] key, byte[] checksum) { return Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum); } private static byte[] reverse(byte[] bs) { var result = new byte[bs.Length]; for (var i = 0; i < bs.Length; i++) { result[i] = bs[bs.Length - (i + 1)]; } return result; } } }
// 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure Batch job. /// </summary> public partial class CloudJob : ITransportObjectProvider<Models.JobAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty; public readonly PropertyAccessor<JobConstraints> ConstraintsProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<JobExecutionInformation> ExecutionInformationProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty; public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty; public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty; public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty; public readonly PropertyAccessor<PoolInformation> PoolInformationProperty; public readonly PropertyAccessor<Common.JobState?> PreviousStateProperty; public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty; public readonly PropertyAccessor<int?> PriorityProperty; public readonly PropertyAccessor<Common.JobState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<JobStatistics> StatisticsProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("CommonEnvironmentSettings", BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None); this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobExecutionInformation>("ExecutionInformation", BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write); this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>("JobManagerTask", BindingAccess.Read | BindingAccess.Write); this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>("JobPreparationTask", BindingAccess.Read | BindingAccess.Write); this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>("JobReleaseTask", BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>("Metadata", BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>("OnAllTasksComplete", BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>("OnTaskFailure", BindingAccess.Read | BindingAccess.Write); this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>("PoolInformation", BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobState?>("PreviousState", BindingAccess.None); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("PreviousStateTransitionTime", BindingAccess.None); this.PriorityProperty = this.CreatePropertyAccessor<int?>("Priority", BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.JobState?>("State", BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<JobStatistics>("Statistics", BindingAccess.None); this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>("UsesTaskDependencies", BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudJob protocolObject) : base(BindingState.Bound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.CommonEnvironmentSettings), "CommonEnvironmentSettings", BindingAccess.Read); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)), "Constraints", BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, "CreationTime", BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, "DisplayName", BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, "ETag", BindingAccess.Read); this.ExecutionInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobExecutionInformation(o).Freeze()), "ExecutionInformation", BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, "Id", BindingAccess.Read); this.JobManagerTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o).Freeze()), "JobManagerTask", BindingAccess.Read); this.JobPreparationTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o).Freeze()), "JobPreparationTask", BindingAccess.Read); this.JobReleaseTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o).Freeze()), "JobReleaseTask", BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, "LastModified", BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), "Metadata", BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete), "OnAllTasksComplete", BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure), "OnTaskFailure", BindingAccess.Read); this.PoolInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)), "PoolInformation", BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.PreviousState), "PreviousState", BindingAccess.Read); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.PreviousStateTransitionTime, "PreviousStateTransitionTime", BindingAccess.Read); this.PriorityProperty = this.CreatePropertyAccessor( protocolObject.Priority, "Priority", BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.State), "State", BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, "StateTransitionTime", BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobStatistics(o).Freeze()), "Statistics", BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, "Url", BindingAccess.Read); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor( protocolObject.UsesTaskDependencies, "UsesTaskDependencies", BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudJob"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudJob( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudJob( BatchClient parentBatchClient, Models.CloudJob protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudJob"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudJob /// <summary> /// Gets or sets a list of common environment variable settings. These environment variables are set for all tasks /// in this <see cref="CloudJob"/> (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> public IList<EnvironmentSetting> CommonEnvironmentSettings { get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; } set { this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> public JobConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets the creation time of the job. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets or sets the display name of the job. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the job. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets the execution information for the job. /// </summary> public JobExecutionInformation ExecutionInformation { get { return this.propertyContainer.ExecutionInformationProperty.Value; } } /// <summary> /// Gets or sets the id of the job. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets the Job Manager task. The Job Manager task is launched when the <see cref="CloudJob"/> is started. /// </summary> public JobManagerTask JobManagerTask { get { return this.propertyContainer.JobManagerTaskProperty.Value; } set { this.propertyContainer.JobManagerTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Preparation task. The Batch service will run the Job Preparation task on a compute node /// before starting any tasks of that job on that compute node. /// </summary> public JobPreparationTask JobPreparationTask { get { return this.propertyContainer.JobPreparationTaskProperty.Value; } set { this.propertyContainer.JobPreparationTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Release task. The Batch service runs the Job Release task when the job ends, on each compute /// node where any task of the job has run. /// </summary> public JobReleaseTask JobReleaseTask { get { return this.propertyContainer.JobReleaseTaskProperty.Value; } set { this.propertyContainer.JobReleaseTaskProperty.Value = value; } } /// <summary> /// Gets the last modified time of the job. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/> /// state. /// </summary> public Common.OnAllTasksComplete? OnAllTasksComplete { get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; } set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; } } /// <summary> /// Gets or sets the action the Batch service should take when any task in the job fails. /// </summary> /// <remarks> /// A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count, /// or if it had a scheduling error. /// </remarks> public Common.OnTaskFailure? OnTaskFailure { get { return this.propertyContainer.OnTaskFailureProperty.Value; } set { this.propertyContainer.OnTaskFailureProperty.Value = value; } } /// <summary> /// Gets or sets the pool on which the Batch service runs the job's tasks. /// </summary> public PoolInformation PoolInformation { get { return this.propertyContainer.PoolInformationProperty.Value; } set { this.propertyContainer.PoolInformationProperty.Value = value; } } /// <summary> /// Gets the previous state of the job. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousState property is not defined. /// </remarks> public Common.JobState? PreviousState { get { return this.propertyContainer.PreviousStateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its previous state. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousStateTransitionTime property /// is not defined. /// </remarks> public DateTime? PreviousStateTransitionTime { get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the priority of the job. Priority values can range from -1000 to 1000, with -1000 being the lowest /// priority and 1000 being the highest priority. /// </summary> /// <remarks> /// The default value is 0. /// </remarks> public int? Priority { get { return this.propertyContainer.PriorityProperty.Value; } set { this.propertyContainer.PriorityProperty.Value = value; } } /// <summary> /// Gets the current state of the job. /// </summary> public Common.JobState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets resource usage statistics for the entire lifetime of the job. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudJob"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. /// </remarks> public JobStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets the URL of the job. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets whether tasks in the job can define dependencies on each other. /// </summary> /// <remarks> /// The default value is false. /// </remarks> public bool? UsesTaskDependencies { get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; } set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; } } #endregion // CloudJob #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobAddParameter ITransportObjectProvider<Models.JobAddParameter>.GetTransportObject() { Models.JobAddParameter result = new Models.JobAddParameter() { CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings), Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()), JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()), JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()), Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete), OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure), PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()), Priority = this.Priority, UsesTaskDependencies = this.UsesTaskDependencies, }; return result; } #endregion // Internal/private methods } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Dashboard Component Feed ///<para>SObject Name: DashboardComponentFeed</para> ///<para>Custom Object: False</para> ///</summary> public class SfDashboardComponentFeed : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "DashboardComponentFeed"; } } ///<summary> /// Feed Item ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Parent ID /// <para>Name: ParentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "parentId")] [Updateable(false), Createable(false)] public string ParentId { get; set; } ///<summary> /// ReferenceTo: DashboardComponent /// <para>RelationshipName: Parent</para> ///</summary> [JsonProperty(PropertyName = "parent")] [Updateable(false), Createable(false)] public SfDashboardComponent Parent { get; set; } ///<summary> /// Feed Item Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "type")] [Updateable(false), Createable(false)] public string Type { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Comment Count /// <para>Name: CommentCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "commentCount")] [Updateable(false), Createable(false)] public int? CommentCount { get; set; } ///<summary> /// Like Count /// <para>Name: LikeCount</para> /// <para>SF Type: int</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "likeCount")] [Updateable(false), Createable(false)] public int? LikeCount { get; set; } ///<summary> /// Title /// <para>Name: Title</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "title")] [Updateable(false), Createable(false)] public string Title { get; set; } ///<summary> /// Body /// <para>Name: Body</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "body")] [Updateable(false), Createable(false)] public string Body { get; set; } ///<summary> /// Link Url /// <para>Name: LinkUrl</para> /// <para>SF Type: url</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "linkUrl")] [Updateable(false), Createable(false)] public string LinkUrl { get; set; } ///<summary> /// Is Rich Text /// <para>Name: IsRichText</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isRichText")] [Updateable(false), Createable(false)] public bool? IsRichText { get; set; } ///<summary> /// Related Record ID /// <para>Name: RelatedRecordId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "relatedRecordId")] [Updateable(false), Createable(false)] public string RelatedRecordId { get; set; } ///<summary> /// InsertedBy ID /// <para>Name: InsertedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "insertedById")] [Updateable(false), Createable(false)] public string InsertedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: InsertedBy</para> ///</summary> [JsonProperty(PropertyName = "insertedBy")] [Updateable(false), Createable(false)] public SfUser InsertedBy { get; set; } ///<summary> /// Best Comment ID /// <para>Name: BestCommentId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "bestCommentId")] [Updateable(false), Createable(false)] public string BestCommentId { get; set; } ///<summary> /// ReferenceTo: FeedComment /// <para>RelationshipName: BestComment</para> ///</summary> [JsonProperty(PropertyName = "bestComment")] [Updateable(false), Createable(false)] public SfFeedComment BestComment { get; set; } } }
//------------------------------------------------------------------------------ // <copyright file="WebConfigManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls.Util { using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.IO; using System.Windows.Forms; using System.Web.UI.MobileControls; using System.Web.UI.Design; using System.Web.UI.Design.MobileControls; using System.Xml; using SR = System.Web.UI.Design.MobileControls.SR; [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class WebConfigManager { private readonly String _path = null; private ISite _site = null; private XmlDocument _document = null; private WebConfigManager() { } internal WebConfigManager(ISite site) { Debug.Assert(site != null); _site = site; IWebApplication webApplicationService = (IWebApplication)_site.GetService(typeof(IWebApplication)); if (webApplicationService != null) { IProjectItem dataFileProjectItem = webApplicationService.GetProjectItemFromUrl("~/web.config"); if (dataFileProjectItem != null) { _path = dataFileProjectItem.PhysicalPath; } } /* VSWhidbey 271075, 257678 // the following inspired by: // \VSDesigner\Designer\Microsoft\VisualStudio\Designer\Serialization\BaseDesignerLoader.cs Type projectItemType = Type.GetType("EnvDTE.ProjectItem, " + AssemblyRef.EnvDTE); if (projectItemType != null) { Object currentProjItem = _site.GetService(projectItemType); PropertyInfo containingProjectProp = projectItemType.GetProperty("ContainingProject"); Object dteProject = containingProjectProp.GetValue(currentProjItem, new Object[0]); Type projectType = Type.GetType("EnvDTE.Project, " + AssemblyRef.EnvDTE); PropertyInfo fullNameProperty = projectType.GetProperty("FullName"); String projectPath = (String)fullNameProperty.GetValue(dteProject, new Object[0]); _path = Path.GetDirectoryName(projectPath) + "\\web.config"; } */ } internal XmlDocument Document { get { if (_document == null) { _document = new XmlDocument(); } return _document; } } private void LoadDocument() { try { Document.Load(_path); } catch (Exception ex) { Debug.Fail(ex.ToString()); throw new Exception(SR.GetString(SR.WebConfig_FileLoadException)); } } internal void EnsureWebConfigCheckedOut() { DesignerUtility.EnsureFileCheckedOut(_site, _path); } internal void EnsureWebConfigIsPresent() { if(!File.Exists(_path)) { // We throw our own exception type so we can easily tell // between a corrupt web.config and a missing one. throw new FileNotFoundException( SR.GetString(SR.WebConfig_FileNotFoundException) ); } } internal ArrayList ReadDeviceFilters() { EnsureWebConfigIsPresent(); // Reload the document everytime we read filters LoadDocument(); XmlNode filters = FindFilterSection(Document, false); ArrayList DeviceFilterList = new ArrayList(); if (filters != null) { Hashtable filterTable = new Hashtable(); foreach(XmlNode childNode in filters.ChildNodes) { if (childNode.Name != null && childNode.Name.Equals("filter")) { // Ignore the empty filter. if (childNode.Attributes["name"] == null || childNode.Attributes["name"].Value == null || childNode.Attributes["name"].Value.Length == 0) { continue; } String filterName = childNode.Attributes["name"].Value; if (filterTable[filterName] != null) { throw new Exception(SR.GetString(SR.DeviceFilterEditorDialog_DuplicateNames)); } DeviceFilterNode node = new DeviceFilterNode(this, childNode); DeviceFilterList.Add(node); filterTable[filterName] = true; } } } return DeviceFilterList; } private bool IsSystemWebSectionPresent() { EnsureWebConfigIsPresent(); XmlNode filters = FindFilterSection(Document, false); return filters != null; } private XmlElement FindXmlNode(XmlNode node, string name) { Debug.Assert(node != null); if (node.HasChildNodes) { foreach (XmlNode child in node.ChildNodes) { if (String.Equals(child.Name, name, StringComparison.Ordinal) && child is XmlElement) { return (XmlElement)child; } } } return null; } internal XmlElement FindFilterSection(XmlDocument document, bool createIfNotExists) { XmlNode configSection = FindXmlNode(document, "configuration"); if (configSection == null) { if (createIfNotExists) { throw new Exception(SR.GetString(SR.WebConfig_FileLoadException)); } return null; } XmlElement webSection = FindXmlNode(configSection, "system.web"); if (webSection == null) { if (createIfNotExists) { webSection = Document.CreateElement("system.web"); configSection.AppendChild(webSection); } return null; } XmlElement filters = FindXmlNode(webSection, "deviceFilters"); if (filters == null) { if (createIfNotExists) { filters = Document.CreateElement("deviceFilters"); webSection.AppendChild(filters); } return null; } return filters; } internal void EnsureSystemWebSectionIsPresent() { if (!IsSystemWebSectionPresent()) { Debug.Assert(Document != null); FindFilterSection(Document, true); } } internal void Save() { Document.Save(_path); } } [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class DeviceFilterNode : ICloneable { internal enum DeviceFilterMode { Compare, Delegate }; private WebConfigManager _webConfig = null; private XmlNode _xmlNode = null; internal DeviceFilterMode Mode; private String _name; private String _type; private String _method; private String _compare; private String _argument; internal DeviceFilterNode(WebConfigManager webConfig) : base() { _webConfig = webConfig; _xmlNode = webConfig.Document.CreateElement("filter"); Name = SR.GetString(SR.DeviceFilterNode_DefaultFilterName); Mode = DeviceFilterMode.Compare; } internal DeviceFilterNode( WebConfigManager webConfig, XmlNode xmlNode ) { _webConfig = webConfig; _xmlNode = xmlNode; Debug.Assert(_xmlNode.Attributes != null); if (_xmlNode.Attributes["type"] != null) { Mode = DeviceFilterMode.Delegate; Debug.Assert( _xmlNode.Attributes["argument"] == null && _xmlNode.Attributes["compare"] == null, "Managementobject contains both Compare and Delegate mode properties." ); } else { Mode = DeviceFilterMode.Compare; // we already know type is null, but it nevers hurts... Debug.Assert( _xmlNode.Attributes["type"] == null && _xmlNode.Attributes["method"] == null, "Managementobject contains both Compare and Delegate mode properties." ); } _name = _xmlNode.Attributes["name"] == null? null : _xmlNode.Attributes["name"].Value; _compare = _xmlNode.Attributes["compare"] == null? null : _xmlNode.Attributes["compare"].Value; _argument = _xmlNode.Attributes["argument"] == null? null : _xmlNode.Attributes["argument"].Value; _type = _xmlNode.Attributes["type"] == null? null : _xmlNode.Attributes["type"].Value; _method = _xmlNode.Attributes["method"] == null? null : _xmlNode.Attributes["method"].Value; } internal void Delete() { Debug.Assert(_xmlNode != null); if (_xmlNode.ParentNode != null) { _xmlNode.ParentNode.RemoveChild(_xmlNode); } } internal void Save() { Debug.Assert(_xmlNode != null); if (_xmlNode.Attributes["name"] == null) { _xmlNode.Attributes.Append(_webConfig.Document.CreateAttribute("name")); } _xmlNode.Attributes["name"].Value = Name; if(Mode == DeviceFilterMode.Compare) { Type = null; Method = null; _xmlNode.Attributes.RemoveNamedItem("type"); _xmlNode.Attributes.RemoveNamedItem("method"); if (_xmlNode.Attributes["compare"] == null) { _xmlNode.Attributes.Append(_webConfig.Document.CreateAttribute("compare")); } _xmlNode.Attributes["compare"].Value = Compare; if (_xmlNode.Attributes["argument"] == null) { _xmlNode.Attributes.Append(_webConfig.Document.CreateAttribute("argument")); } _xmlNode.Attributes["argument"].Value = Argument; } else { Compare = null; Argument = null; _xmlNode.Attributes.RemoveNamedItem("compare"); _xmlNode.Attributes.RemoveNamedItem("argument"); if (_xmlNode.Attributes["type"] == null) { _xmlNode.Attributes.Append(_webConfig.Document.CreateAttribute("type")); } _xmlNode.Attributes["type"].Value = Type; if (_xmlNode.Attributes["method"] == null) { _xmlNode.Attributes.Append(_webConfig.Document.CreateAttribute("method")); } _xmlNode.Attributes["method"].Value = Method; } _webConfig.EnsureSystemWebSectionIsPresent(); XmlNode filters = _webConfig.FindFilterSection(_webConfig.Document, false); filters.AppendChild(_xmlNode); } // Cause the DeviceFilterNode to display correctly when inserted // in a combo box. public override String ToString() { if(Name == null || Name.Length == 0) { return SR.GetString(SR.DeviceFilter_DefaultChoice); } return Name; } internal String Name { get { return _name; } set { _name = value; } } internal String Type { get { return _type; } set { _type = value; } } internal String Method { get { return _method; } set { _method = value; } } internal String Compare { get { return _compare; } set { _compare = value; } } internal String Argument { get { return _argument; } set { _argument = value; } } // <summary> // Returns a copy of this node's encapsulated data. Does not // copy TreeNode fields. // </summary> public Object Clone() { DeviceFilterNode newNode = new DeviceFilterNode( _webConfig ); newNode.Name = this.Name; newNode.Mode = this.Mode; if(this.Mode == DeviceFilterMode.Compare) { newNode.Compare = this.Compare; newNode.Argument = this.Argument; } else { newNode.Type = this.Type; newNode.Method = this.Method; } return (Object) newNode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; namespace System.Data { /// <summary> /// This a locale mapper for non windows /// </summary> internal class LocaleMapper { private static readonly Dictionary<int, LocaleCodePage> s_mapper = new Dictionary<int, LocaleCodePage>(431) { #region <<Locale Mapper>> {1, new LocaleCodePage("ar", 1256)}, {2, new LocaleCodePage("bg", 1251)}, {3, new LocaleCodePage("ca", 1252)}, {4, new LocaleCodePage("zh-CHS", 936)}, {5, new LocaleCodePage("cs", 1250)}, {6, new LocaleCodePage("da", 1252)}, {7, new LocaleCodePage("de", 1252)}, {8, new LocaleCodePage("el", 1253)}, {9, new LocaleCodePage("en", 1252)}, {10, new LocaleCodePage("es", 1252)}, {11, new LocaleCodePage("fi", 1252)}, {12, new LocaleCodePage("fr", 1252)}, {13, new LocaleCodePage("he", 1255)}, {14, new LocaleCodePage("hu", 1250)}, {15, new LocaleCodePage("is", 1252)}, {16, new LocaleCodePage("it", 1252)}, {17, new LocaleCodePage("ja", 932)}, {18, new LocaleCodePage("ko", 949)}, {19, new LocaleCodePage("nl", 1252)}, {20, new LocaleCodePage("no", 1252)}, {21, new LocaleCodePage("pl", 1250)}, {22, new LocaleCodePage("pt", 1252)}, {23, new LocaleCodePage("rm", 1252)}, {24, new LocaleCodePage("ro", 1250)}, {25, new LocaleCodePage("ru", 1251)}, {26, new LocaleCodePage("hr", 1250)}, {27, new LocaleCodePage("sk", 1250)}, {28, new LocaleCodePage("sq", 1250)}, {29, new LocaleCodePage("sv", 1252)}, {30, new LocaleCodePage("th", 874)}, {31, new LocaleCodePage("tr", 1254)}, {32, new LocaleCodePage("ur", 1256)}, {33, new LocaleCodePage("id", 1252)}, {34, new LocaleCodePage("uk", 1251)}, {35, new LocaleCodePage("be", 1251)}, {36, new LocaleCodePage("sl", 1250)}, {37, new LocaleCodePage("et", 1257)}, {38, new LocaleCodePage("lv", 1257)}, {39, new LocaleCodePage("lt", 1257)}, {40, new LocaleCodePage("tg", 1251)}, {41, new LocaleCodePage("fa", 1256)}, {42, new LocaleCodePage("vi", 1258)}, {43, new LocaleCodePage("hy", 0)}, {44, new LocaleCodePage("az", 1254)}, {45, new LocaleCodePage("eu", 1252)}, {46, new LocaleCodePage("hsb", 1252)}, {47, new LocaleCodePage("mk", 1251)}, {48, new LocaleCodePage("st", 0)}, {49, new LocaleCodePage("ts", 0)}, {50, new LocaleCodePage("tn", 1252)}, {52, new LocaleCodePage("xh", 1252)}, {53, new LocaleCodePage("zu", 1252)}, {54, new LocaleCodePage("af", 1252)}, {55, new LocaleCodePage("ka", 0)}, {56, new LocaleCodePage("fo", 1252)}, {57, new LocaleCodePage("hi", 0)}, {58, new LocaleCodePage("mt", 0)}, {59, new LocaleCodePage("se", 1252)}, {60, new LocaleCodePage("ga", 1252)}, {62, new LocaleCodePage("ms", 1252)}, {63, new LocaleCodePage("kk", 0)}, {64, new LocaleCodePage("ky", 1251)}, {65, new LocaleCodePage("sw", 1252)}, {66, new LocaleCodePage("tk", 1250)}, {67, new LocaleCodePage("uz", 1254)}, {68, new LocaleCodePage("tt", 1251)}, {69, new LocaleCodePage("bn", 0)}, {70, new LocaleCodePage("pa", 0)}, {71, new LocaleCodePage("gu", 0)}, {72, new LocaleCodePage("or", 0)}, {73, new LocaleCodePage("ta", 0)}, {74, new LocaleCodePage("te", 0)}, {75, new LocaleCodePage("kn", 0)}, {76, new LocaleCodePage("ml", 0)}, {77, new LocaleCodePage("as", 0)}, {78, new LocaleCodePage("mr", 0)}, {79, new LocaleCodePage("sa", 0)}, {80, new LocaleCodePage("mn", 1251)}, {81, new LocaleCodePage("bo", 0)}, {82, new LocaleCodePage("cy", 1252)}, {83, new LocaleCodePage("km", 0)}, {84, new LocaleCodePage("lo", 0)}, {85, new LocaleCodePage("my", 0)}, {86, new LocaleCodePage("gl", 1252)}, {87, new LocaleCodePage("kok", 0)}, {89, new LocaleCodePage("sd", 1256)}, {90, new LocaleCodePage("syr", 0)}, {91, new LocaleCodePage("si", 0)}, {92, new LocaleCodePage("chr", 0)}, {93, new LocaleCodePage("iu", 1252)}, {94, new LocaleCodePage("am", 0)}, {95, new LocaleCodePage("tzm", 1252)}, {97, new LocaleCodePage("ne", 0)}, {98, new LocaleCodePage("fy", 1252)}, {99, new LocaleCodePage("ps", 0)}, {100, new LocaleCodePage("fil", 1252)}, {101, new LocaleCodePage("dv", 0)}, {103, new LocaleCodePage("ff", 1252)}, {104, new LocaleCodePage("ha", 1252)}, {106, new LocaleCodePage("yo", 1252)}, {107, new LocaleCodePage("quz", 1252)}, {108, new LocaleCodePage("nso", 1252)}, {109, new LocaleCodePage("ba", 1251)}, {110, new LocaleCodePage("lb", 1252)}, {111, new LocaleCodePage("kl", 1252)}, {112, new LocaleCodePage("ig", 1252)}, {114, new LocaleCodePage("om", 0)}, {115, new LocaleCodePage("ti", 0)}, {116, new LocaleCodePage("gn", 1252)}, {117, new LocaleCodePage("haw", 1252)}, {119, new LocaleCodePage("so", 0)}, {120, new LocaleCodePage("ii", 0)}, {122, new LocaleCodePage("arn", 1252)}, {124, new LocaleCodePage("moh", 1252)}, {126, new LocaleCodePage("br", 1252)}, {127, new LocaleCodePage("", 1252)}, {128, new LocaleCodePage("ug", 1256)}, {129, new LocaleCodePage("mi", 0)}, {130, new LocaleCodePage("oc", 1252)}, {131, new LocaleCodePage("co", 1252)}, {132, new LocaleCodePage("gsw", 1252)}, {133, new LocaleCodePage("sah", 1251)}, {134, new LocaleCodePage("qut", 1252)}, {135, new LocaleCodePage("rw", 1252)}, {136, new LocaleCodePage("wo", 1252)}, {140, new LocaleCodePage("prs", 1256)}, {145, new LocaleCodePage("gd", 1252)}, {146, new LocaleCodePage("ku", 1256)}, {1025, new LocaleCodePage("ar-SA", 1256)}, {1026, new LocaleCodePage("bg-BG", 1251)}, {1027, new LocaleCodePage("ca-ES", 1252)}, {1028, new LocaleCodePage("zh-TW", 950)}, {1029, new LocaleCodePage("cs-CZ", 1250)}, {1030, new LocaleCodePage("da-DK", 1252)}, {1031, new LocaleCodePage("de-DE", 1252)}, {1032, new LocaleCodePage("el-GR", 1253)}, {1033, new LocaleCodePage("en-US", 1252)}, {1034, new LocaleCodePage("es-ES", 1252)}, {1035, new LocaleCodePage("fi-FI", 1252)}, {1036, new LocaleCodePage("fr-FR", 1252)}, {1037, new LocaleCodePage("he-IL", 1255)}, {1038, new LocaleCodePage("hu-HU", 1250)}, {1039, new LocaleCodePage("is-IS", 1252)}, {1040, new LocaleCodePage("it-IT", 1252)}, {1041, new LocaleCodePage("ja-JP", 932)}, {1042, new LocaleCodePage("ko-KR", 949)}, {1043, new LocaleCodePage("nl-NL", 1252)}, {1044, new LocaleCodePage("nb-NO", 1252)}, {1045, new LocaleCodePage("pl-PL", 1250)}, {1046, new LocaleCodePage("pt-BR", 1252)}, {1047, new LocaleCodePage("rm-CH", 1252)}, {1048, new LocaleCodePage("ro-RO", 1250)}, {1049, new LocaleCodePage("ru-RU", 1251)}, {1050, new LocaleCodePage("hr-HR", 1250)}, {1051, new LocaleCodePage("sk-SK", 1250)}, {1052, new LocaleCodePage("sq-AL", 1250)}, {1053, new LocaleCodePage("sv-SE", 1252)}, {1054, new LocaleCodePage("th-TH", 874)}, {1055, new LocaleCodePage("tr-TR", 1254)}, {1056, new LocaleCodePage("ur-PK", 1256)}, {1057, new LocaleCodePage("id-ID", 1252)}, {1058, new LocaleCodePage("uk-UA", 1251)}, {1059, new LocaleCodePage("be-BY", 1251)}, {1060, new LocaleCodePage("sl-SI", 1250)}, {1061, new LocaleCodePage("et-EE", 1257)}, {1062, new LocaleCodePage("lv-LV", 1257)}, {1063, new LocaleCodePage("lt-LT", 1257)}, {1064, new LocaleCodePage("tg-Cyrl-TJ", 1251)}, {1065, new LocaleCodePage("fa-IR", 1256)}, {1066, new LocaleCodePage("vi-VN", 1258)}, {1067, new LocaleCodePage("hy-AM", 0)}, {1068, new LocaleCodePage("az-Latn-AZ", 1254)}, {1069, new LocaleCodePage("eu-ES", 1252)}, {1070, new LocaleCodePage("hsb-DE", 1252)}, {1071, new LocaleCodePage("mk-MK", 1251)}, {1072, new LocaleCodePage("st-ZA", 0)}, {1073, new LocaleCodePage("ts-ZA", 0)}, {1074, new LocaleCodePage("tn-ZA", 1252)}, {1076, new LocaleCodePage("xh-ZA", 1252)}, {1077, new LocaleCodePage("zu-ZA", 1252)}, {1078, new LocaleCodePage("af-ZA", 1252)}, {1079, new LocaleCodePage("ka-GE", 0)}, {1080, new LocaleCodePage("fo-FO", 1252)}, {1081, new LocaleCodePage("hi-IN", 0)}, {1082, new LocaleCodePage("mt-MT", 0)}, {1083, new LocaleCodePage("se-NO", 1252)}, {1086, new LocaleCodePage("ms-MY", 1252)}, {1087, new LocaleCodePage("kk-KZ", 0)}, {1088, new LocaleCodePage("ky-KG", 1251)}, {1089, new LocaleCodePage("sw-KE", 1252)}, {1090, new LocaleCodePage("tk-TM", 1250)}, {1091, new LocaleCodePage("uz-Latn-UZ", 1254)}, {1092, new LocaleCodePage("tt-RU", 1251)}, {1093, new LocaleCodePage("bn-IN", 0)}, {1094, new LocaleCodePage("pa-IN", 0)}, {1095, new LocaleCodePage("gu-IN", 0)}, {1096, new LocaleCodePage("or-IN", 0)}, {1097, new LocaleCodePage("ta-IN", 0)}, {1098, new LocaleCodePage("te-IN", 0)}, {1099, new LocaleCodePage("kn-IN", 0)}, {1100, new LocaleCodePage("ml-IN", 0)}, {1101, new LocaleCodePage("as-IN", 0)}, {1102, new LocaleCodePage("mr-IN", 0)}, {1103, new LocaleCodePage("sa-IN", 0)}, {1104, new LocaleCodePage("mn-MN", 1251)}, {1105, new LocaleCodePage("bo-CN", 0)}, {1106, new LocaleCodePage("cy-GB", 1252)}, {1107, new LocaleCodePage("km-KH", 0)}, {1108, new LocaleCodePage("lo-LA", 0)}, {1109, new LocaleCodePage("my-MM", 0)}, {1110, new LocaleCodePage("gl-ES", 1252)}, {1111, new LocaleCodePage("kok-IN", 0)}, {1114, new LocaleCodePage("syr-SY", 0)}, {1115, new LocaleCodePage("si-LK", 0)}, {1116, new LocaleCodePage("chr-Cher-US", 0)}, {1117, new LocaleCodePage("iu-Cans-CA", 0)}, {1118, new LocaleCodePage("am-ET", 0)}, {1121, new LocaleCodePage("ne-NP", 0)}, {1122, new LocaleCodePage("fy-NL", 1252)}, {1123, new LocaleCodePage("ps-AF", 0)}, {1124, new LocaleCodePage("fil-PH", 1252)}, {1125, new LocaleCodePage("dv-MV", 0)}, {1128, new LocaleCodePage("ha-Latn-NG", 1252)}, {1130, new LocaleCodePage("yo-NG", 1252)}, {1131, new LocaleCodePage("quz-BO", 1252)}, {1132, new LocaleCodePage("nso-ZA", 1252)}, {1133, new LocaleCodePage("ba-RU", 1251)}, {1134, new LocaleCodePage("lb-LU", 1252)}, {1135, new LocaleCodePage("kl-GL", 1252)}, {1136, new LocaleCodePage("ig-NG", 1252)}, {1138, new LocaleCodePage("om-ET", 0)}, {1139, new LocaleCodePage("ti-ET", 0)}, {1140, new LocaleCodePage("gn-PY", 1252)}, {1141, new LocaleCodePage("haw-US", 1252)}, {1143, new LocaleCodePage("so-SO", 0)}, {1144, new LocaleCodePage("ii-CN", 0)}, {1146, new LocaleCodePage("arn-CL", 1252)}, {1148, new LocaleCodePage("moh-CA", 1252)}, {1150, new LocaleCodePage("br-FR", 1252)}, {1152, new LocaleCodePage("ug-CN", 1256)}, {1153, new LocaleCodePage("mi-NZ", 0)}, {1154, new LocaleCodePage("oc-FR", 1252)}, {1155, new LocaleCodePage("co-FR", 1252)}, {1156, new LocaleCodePage("gsw-FR", 1252)}, {1157, new LocaleCodePage("sah-RU", 1251)}, {1158, new LocaleCodePage("qut-GT", 1252)}, {1159, new LocaleCodePage("rw-RW", 1252)}, {1160, new LocaleCodePage("wo-SN", 1252)}, {1164, new LocaleCodePage("prs-AF", 1256)}, {1169, new LocaleCodePage("gd-GB", 1252)}, {1170, new LocaleCodePage("ku-Arab-IQ", 1256)}, {1281, new LocaleCodePage("qps-ploc", 1250)}, {1534, new LocaleCodePage("qps-ploca", 932)}, {2049, new LocaleCodePage("ar-IQ", 1256)}, {2051, new LocaleCodePage("ca-ES-valencia", 1252)}, {2052, new LocaleCodePage("zh-CN", 936)}, {2055, new LocaleCodePage("de-CH", 1252)}, {2057, new LocaleCodePage("en-GB", 1252)}, {2058, new LocaleCodePage("es-MX", 1252)}, {2060, new LocaleCodePage("fr-BE", 1252)}, {2064, new LocaleCodePage("it-CH", 1252)}, {2067, new LocaleCodePage("nl-BE", 1252)}, {2068, new LocaleCodePage("nn-NO", 1252)}, {2070, new LocaleCodePage("pt-PT", 1252)}, {2072, new LocaleCodePage("ro-MD", 0)}, {2074, new LocaleCodePage("sr-Latn-CS", 1250)}, {2077, new LocaleCodePage("sv-FI", 1252)}, {2080, new LocaleCodePage("ur-IN", 0)}, {2092, new LocaleCodePage("az-Cyrl-AZ", 1251)}, {2094, new LocaleCodePage("dsb-DE", 1252)}, {2098, new LocaleCodePage("tn-BW", 1252)}, {2107, new LocaleCodePage("se-SE", 1252)}, {2108, new LocaleCodePage("ga-IE", 1252)}, {2110, new LocaleCodePage("ms-BN", 1252)}, {2115, new LocaleCodePage("uz-Cyrl-UZ", 1251)}, {2117, new LocaleCodePage("bn-BD", 0)}, {2118, new LocaleCodePage("pa-Arab-PK", 1256)}, {2121, new LocaleCodePage("ta-LK", 0)}, {2128, new LocaleCodePage("mn-Mong-CN", 0)}, {2137, new LocaleCodePage("sd-Arab-PK", 1256)}, {2141, new LocaleCodePage("iu-Latn-CA", 1252)}, {2143, new LocaleCodePage("tzm-Latn-DZ", 1252)}, {2145, new LocaleCodePage("ne-IN", 0)}, {2151, new LocaleCodePage("ff-Latn-SN", 1252)}, {2155, new LocaleCodePage("quz-EC", 1252)}, {2163, new LocaleCodePage("ti-ER", 0)}, {2305, new LocaleCodePage("qps-Latn-x-sh", 1252)}, {2559, new LocaleCodePage("qps-plocm", 1256)}, {3073, new LocaleCodePage("ar-EG", 1256)}, {3076, new LocaleCodePage("zh-HK", 950)}, {3079, new LocaleCodePage("de-AT", 1252)}, {3081, new LocaleCodePage("en-AU", 1252)}, {3082, new LocaleCodePage("es-ES", 1252)}, {3084, new LocaleCodePage("fr-CA", 1252)}, {3098, new LocaleCodePage("sr-Cyrl-CS", 1251)}, {3131, new LocaleCodePage("se-FI", 1252)}, {3152, new LocaleCodePage("mn-Mong-MN", 0)}, {3179, new LocaleCodePage("quz-PE", 1252)}, {4097, new LocaleCodePage("ar-LY", 1256)}, {4100, new LocaleCodePage("zh-SG", 936)}, {4103, new LocaleCodePage("de-LU", 1252)}, {4105, new LocaleCodePage("en-CA", 1252)}, {4106, new LocaleCodePage("es-GT", 1252)}, {4108, new LocaleCodePage("fr-CH", 1252)}, {4122, new LocaleCodePage("hr-BA", 1250)}, {4155, new LocaleCodePage("smj-NO", 1252)}, {4191, new LocaleCodePage("tzm-Tfng-MA", 0)}, {5121, new LocaleCodePage("ar-DZ", 1256)}, {5124, new LocaleCodePage("zh-MO", 950)}, {5127, new LocaleCodePage("de-LI", 1252)}, {5129, new LocaleCodePage("en-NZ", 1252)}, {5130, new LocaleCodePage("es-CR", 1252)}, {5132, new LocaleCodePage("fr-LU", 1252)}, {5146, new LocaleCodePage("bs-Latn-BA", 1250)}, {5179, new LocaleCodePage("smj-SE", 1252)}, {6145, new LocaleCodePage("ar-MA", 1256)}, {6153, new LocaleCodePage("en-IE", 1252)}, {6154, new LocaleCodePage("es-PA", 1252)}, {6156, new LocaleCodePage("fr-MC", 1252)}, {6170, new LocaleCodePage("sr-Latn-BA", 1250)}, {6203, new LocaleCodePage("sma-NO", 1252)}, {7169, new LocaleCodePage("ar-TN", 1256)}, {7177, new LocaleCodePage("en-ZA", 1252)}, {7178, new LocaleCodePage("es-DO", 1252)}, {7194, new LocaleCodePage("sr-Cyrl-BA", 1251)}, {7227, new LocaleCodePage("sma-SE", 1252)}, {8192, new LocaleCodePage("en-US", 1252)}, {8193, new LocaleCodePage("ar-OM", 1256)}, {8201, new LocaleCodePage("en-JM", 1252)}, {8202, new LocaleCodePage("es-VE", 1252)}, {8204, new LocaleCodePage("fr-RE", 0)}, {8218, new LocaleCodePage("bs-Cyrl-BA", 1251)}, {8251, new LocaleCodePage("sms-FI", 1252)}, {9216, new LocaleCodePage("en-US", 1252)}, {9217, new LocaleCodePage("ar-YE", 1256)}, {9225, new LocaleCodePage("en-029", 1252)}, {9226, new LocaleCodePage("es-CO", 1252)}, {9228, new LocaleCodePage("fr-CD", 0)}, {9242, new LocaleCodePage("sr-Latn-RS", 1250)}, {9275, new LocaleCodePage("smn-FI", 1252)}, {10240, new LocaleCodePage("en-US", 1252)}, {10241, new LocaleCodePage("ar-SY", 1256)}, {10249, new LocaleCodePage("en-BZ", 1252)}, {10250, new LocaleCodePage("es-PE", 1252)}, {10252, new LocaleCodePage("fr-SN", 0)}, {10266, new LocaleCodePage("sr-Cyrl-RS", 1251)}, {11264, new LocaleCodePage("en-US", 1252)}, {11265, new LocaleCodePage("ar-JO", 1256)}, {11273, new LocaleCodePage("en-TT", 1252)}, {11274, new LocaleCodePage("es-AR", 1252)}, {11276, new LocaleCodePage("fr-CM", 0)}, {11290, new LocaleCodePage("sr-Latn-ME", 1250)}, {12288, new LocaleCodePage("en-US", 1252)}, {12289, new LocaleCodePage("ar-LB", 1256)}, {12297, new LocaleCodePage("en-ZW", 1252)}, {12298, new LocaleCodePage("es-EC", 1252)}, {12300, new LocaleCodePage("fr-CI", 0)}, {12314, new LocaleCodePage("sr-Cyrl-ME", 1251)}, {13312, new LocaleCodePage("en-US", 1252)}, {13313, new LocaleCodePage("ar-KW", 1256)}, {13321, new LocaleCodePage("en-PH", 1252)}, {13322, new LocaleCodePage("es-CL", 1252)}, {13324, new LocaleCodePage("fr-ML", 0)}, {14336, new LocaleCodePage("en-US", 1252)}, {14337, new LocaleCodePage("ar-AE", 1256)}, {14346, new LocaleCodePage("es-UY", 1252)}, {14348, new LocaleCodePage("fr-MA", 0)}, {15360, new LocaleCodePage("en-US", 1252)}, {15361, new LocaleCodePage("ar-BH", 1256)}, {15369, new LocaleCodePage("en-HK", 0)}, {15370, new LocaleCodePage("es-PY", 1252)}, {15372, new LocaleCodePage("fr-HT", 0)}, {16384, new LocaleCodePage("en-US", 1252)}, {16385, new LocaleCodePage("ar-QA", 1256)}, {16393, new LocaleCodePage("en-IN", 1252)}, {16394, new LocaleCodePage("es-BO", 1252)}, {17408, new LocaleCodePage("en-US", 1252)}, {17417, new LocaleCodePage("en-MY", 1252)}, {17418, new LocaleCodePage("es-SV", 1252)}, {18432, new LocaleCodePage("en-US", 1252)}, {18441, new LocaleCodePage("en-SG", 1252)}, {18442, new LocaleCodePage("es-HN", 1252)}, {19456, new LocaleCodePage("en-US", 1252)}, {19466, new LocaleCodePage("es-NI", 1252)}, {20490, new LocaleCodePage("es-PR", 1252)}, {21514, new LocaleCodePage("es-US", 1252)}, {22538, new LocaleCodePage("es-419", 0)}, {25626, new LocaleCodePage("bs-Cyrl", 1251)}, {26650, new LocaleCodePage("bs-Latn", 1250)}, {27674, new LocaleCodePage("sr-Cyrl", 1251)}, {28698, new LocaleCodePage("sr-Latn", 1250)}, {28731, new LocaleCodePage("smn", 1252)}, {29740, new LocaleCodePage("az-Cyrl", 1251)}, {29755, new LocaleCodePage("sms", 1252)}, {30724, new LocaleCodePage("zh", 936)}, {30740, new LocaleCodePage("nn", 1252)}, {30746, new LocaleCodePage("bs", 1250)}, {30764, new LocaleCodePage("az-Latn", 1254)}, {30779, new LocaleCodePage("sma", 1252)}, {30787, new LocaleCodePage("uz-Cyrl", 1251)}, {30800, new LocaleCodePage("mn-Cyrl", 1251)}, {30813, new LocaleCodePage("iu-Cans", 0)}, {30815, new LocaleCodePage("tzm-Tfng", 0)}, {31748, new LocaleCodePage("zh-CHT", 950)}, {31764, new LocaleCodePage("nb", 1252)}, {31770, new LocaleCodePage("sr", 1250)}, {31784, new LocaleCodePage("tg-Cyrl", 1251)}, {31790, new LocaleCodePage("dsb", 1252)}, {31803, new LocaleCodePage("smj", 1252)}, {31811, new LocaleCodePage("uz-Latn", 1254)}, {31814, new LocaleCodePage("pa-Arab", 1256)}, {31824, new LocaleCodePage("mn-Mong", 0)}, {31833, new LocaleCodePage("sd-Arab", 1256)}, {31836, new LocaleCodePage("chr-Cher", 0)}, {31837, new LocaleCodePage("iu-Latn", 1252)}, {31839, new LocaleCodePage("tzm-Latn", 1252)}, {31847, new LocaleCodePage("ff-Latn", 1252)}, {31848, new LocaleCodePage("ha-Latn", 1252)}, {31890, new LocaleCodePage("ku-Arab", 1256)}, {65663, new LocaleCodePage("x-IV", 1252)}, {66567, new LocaleCodePage("de-DE", 1252)}, {66574, new LocaleCodePage("hu-HU", 1250)}, {66615, new LocaleCodePage("ka-GE", 0)}, {133124, new LocaleCodePage("zh-CN", 936)}, {135172, new LocaleCodePage("zh-SG", 936)}, {136196, new LocaleCodePage("zh-MO", 950)}, {197636, new LocaleCodePage("zh-TW", 950)}, {263172, new LocaleCodePage("zh-TW", 950)}, {263185, new LocaleCodePage("ja-JP", 932)}, {265220, new LocaleCodePage("zh-HK", 950)}, {267268, new LocaleCodePage("zh-MO", 950)} #endregion }; public static string LcidToLocaleNameInternal(int lcid) { return s_mapper[lcid].LocaleName; } public static int LocaleNameToAnsiCodePage(string localeName) { return s_mapper.FirstOrDefault(t => t.Value.LocaleName == localeName).Value.CodePage; } public static int GetLcidForLocaleName(string localeName) { return s_mapper.FirstOrDefault(t => t.Value.LocaleName == localeName).Key; } } internal class LocaleCodePage { internal readonly string LocaleName; internal readonly int CodePage; internal LocaleCodePage(string localeName, int codePage) { this.LocaleName = localeName; this.CodePage = codePage; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Aurora.Simulation.Base; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using ChatSessionMember = Aurora.Framework.ChatSessionMember; namespace Aurora.Modules.Groups { public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector { public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; private IUserAccountService m_accountService; private int m_cacheTimeout = 30; private bool m_connectorEnabled; private bool m_disableKeepAlive; private string m_groupReadKey = string.Empty; private string m_groupWriteKey = string.Empty; // Used to track which agents are have dropped from a group chat session // Should be reset per agent, on logon // TODO: move this to Flotsam XmlRpc Service // SessionID, List<AgentID> private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>(); private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>(); private string m_groupsServerURI = string.Empty; private ExpiringCache<string, XmlRpcResponse> m_memoryCache; #region IGroupsServicesConnector Members /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); param["Name"] = name; param["Charter"] = charter; param["ShowInList"] = showInList ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = 0; param["OpenEnrollment"] = openEnrollment ? 1 : 0; param["AllowPublish"] = allowPublish ? 1 : 0; param["MaturePublish"] = maturePublish ? 1 : 0; param["FounderID"] = founderID.ToString(); param["EveryonePowers"] = ((ulong) m_DefaultEveryonePowers).ToString(); param["OwnerRoleID"] = OwnerRoleID.ToString(); // Would this be cleaner as (GroupPowers)ulong.MaxValue; GroupPowers OwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; param["OwnersPowers"] = ((ulong) OwnerPowers).ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param); if (respData.Contains("error")) { // UUID is not nullable return UUID.Zero; } return UUID.Parse((string) respData["GroupID"]); } public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["Charter"] = charter; param["ShowInList"] = showInList ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = membershipFee; param["OpenEnrollment"] = openEnrollment ? 1 : 0; param["AllowPublish"] = allowPublish ? 1 : 0; param["MaturePublish"] = maturePublish ? 1 : 0; XmlRpcCall(requestingAgentID, "groups.updateGroup", param); } public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); param["Name"] = name; param["Description"] = description; param["Title"] = title; param["Powers"] = powers.ToString(); XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param); } public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param); } public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); if (name != null) { param["Name"] = name; } if (description != null) { param["Description"] = description; } if (title != null) { param["Title"] = title; } param["Powers"] = powers.ToString(); XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param); } public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName) { Hashtable param = new Hashtable(); if (GroupID != UUID.Zero) { param["GroupID"] = GroupID.ToString(); } if (!string.IsNullOrEmpty(GroupName)) { param["Name"] = GroupName; } Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param); if (respData.Contains("error")) { return null; } return GroupProfileHashtableToGroupRecord(respData); } public string SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param); return GetAgentGroupMembership(requestingAgentID, AgentID, GroupID).GroupTitle; } public string SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["SelectedRoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param); return GetAgentGroupMembership(requestingAgentID, AgentID, GroupID).GroupTitle; } public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["AcceptNotices"] = AcceptNotices ? "1" : "0"; param["ListInProfile"] = ListInProfile ? "1" : "0"; XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param); } public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID, string FromAgentName) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); param["AgentID"] = agentID.ToString(); param["RoleID"] = roleID.ToString(); param["GroupID"] = groupID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param); } public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param); if (respData.Contains("error")) { return null; } GroupInviteInfo inviteInfo = new GroupInviteInfo { InviteID = inviteID, GroupID = UUID.Parse((string) respData["GroupID"]), RoleID = UUID.Parse((string) respData["RoleID"]), AgentID = UUID.Parse((string) respData["AgentID"]) }; return inviteInfo; } public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param); } public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param); } public bool RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param); return true; } public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param); } public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param); } public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search, uint? start, uint? count, uint queryflags) { Hashtable param = new Hashtable(); param["Search"] = search; Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param); List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); if (!respData.Contains("error")) { Hashtable results = (Hashtable) respData["results"]; foreach (Hashtable groupFind in results.Values) { DirGroupsReplyData data = new DirGroupsReplyData {groupID = new UUID((string) groupFind["GroupID"])}; ; data.groupName = (string) groupFind["Name"]; data.members = int.Parse((string) groupFind["Members"]); // data.searchOrder = order; findings.Add(data); } } return findings; } public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param); if (respData.Contains("error")) { return null; } GroupMembershipData data = HashTableToGroupMembershipData(respData); return data; } public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param); if (respData.Contains("error")) { return null; } return HashTableToGroupMembershipData(respData); } public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param); List<GroupMembershipData> memberships = new List<GroupMembershipData>(); if (!respData.Contains("error")) { memberships.AddRange(from object membership in respData.Values select HashTableToGroupMembershipData((Hashtable) membership)); } return memberships; } public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } Roles.AddRange(from Hashtable role in respData.Values select new GroupRolesData { RoleID = new UUID((string) role["RoleID"]), Name = (string) role["Name"], Description = (string) role["Description"], Powers = ulong.Parse((string) role["Powers"]), Title = (string) role["Title"] }); return Roles; } public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } Roles.AddRange(from Hashtable role in respData.Values select new GroupRolesData { Description = (string) role["Description"], Members = int.Parse((string) role["Members"]), Name = (string) role["Name"], Powers = ulong.Parse((string) role["Powers"]), RoleID = new UUID((string) role["RoleID"]), Title = (string) role["Title"] }); return Roles; } public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param); List<GroupMembersData> members = new List<GroupMembersData>(); if (respData.Contains("error")) { return members; } members.AddRange(from Hashtable membership in respData.Values select new GroupMembersData { AcceptNotices = ((string) membership["AcceptNotices"]) == "1", AgentID = new UUID((string) membership["AgentID"]), Contribution = int.Parse((string) membership["Contribution"]), IsOwner = ((string) membership["IsOwner"]) == "1", ListInProfile = ((string) membership["ListInProfile"]) == "1", AgentPowers = ulong.Parse((string) membership["AgentPowers"]), Title = (string) membership["Title"] }); return members; } public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param); List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); if (!respData.Contains("error")) { members.AddRange(from Hashtable membership in respData.Values select new GroupRoleMembersData { MemberID = new UUID((string) membership["AgentID"]), RoleID = new UUID((string) membership["RoleID"]) }); } return members; } public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param); List<GroupNoticeData> values = new List<GroupNoticeData>(); if (!respData.Contains("error")) { values.AddRange(from Hashtable value in respData.Values select new GroupNoticeData { NoticeID = UUID.Parse((string) value["NoticeID"]), Timestamp = uint.Parse((string) value["Timestamp"]), FromName = (string) value["FromName"], Subject = (string) value["Subject"], HasAttachment = false, AssetType = 0 }); } return values; } public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID) { Hashtable param = new Hashtable(); param["NoticeID"] = noticeID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param); if (respData.Contains("error")) { return null; } GroupNoticeInfo data = new GroupNoticeInfo { GroupID = UUID.Parse((string) respData["GroupID"]), Message = (string) respData["Message"], BinaryBucket = Utils.HexStringToBytes((string) respData["BinaryBucket"], true), noticeData = { NoticeID = UUID.Parse((string) respData["NoticeID"]), Timestamp = uint.Parse((string) respData["Timestamp"]), FromName = (string) respData["FromName"], Subject = (string) respData["Subject"], HasAttachment = false, AssetType = 0 } }; if (data.Message == null) { data.Message = string.Empty; } return data; } public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, UUID ItemID, int AssetType, string ItemName) { string binBucket = Utils.BytesToHexString(new byte[0], ""); Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["NoticeID"] = noticeID.ToString(); param["FromName"] = fromName; param["Subject"] = subject; param["Message"] = message; param["BinaryBucket"] = binBucket; param["TimeStamp"] = ((uint) Util.UnixTimeSinceEpoch()).ToString(); XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param); } public List<GroupInviteInfo> GetGroupInvites(UUID requestingAgentID) { Hashtable param = new Hashtable(); param["AgentID"] = requestingAgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupInvites", param); if (!respData.Contains("error")) { List<GroupInviteInfo> GroupInvites = new List<GroupInviteInfo>(); Hashtable results = (Hashtable) respData["results"]; if (results != null) { GroupInvites.AddRange(from Hashtable invite in results.Values select new GroupInviteInfo { AgentID = new UUID((string) invite["AgentID"]), GroupID = new UUID((string) invite["GroupID"]), InviteID = new UUID((string) invite["InviteID"]), RoleID = new UUID((string) invite["RoleID"]) }); } return GroupInvites; } return new List<GroupInviteInfo>(); } public void AddGroupProposal(UUID agentID, GroupProposalInfo info) { } public bool CreateSession(ChatSession chatSession) { return false; } public void AddMemberToGroup(ChatSessionMember chatSessionMember, UUID GroupID) { } public ChatSession GetSession(UUID SessionID) { return null; } public ChatSessionMember FindMember(UUID sessionid, UUID Agent) { return null; } public void RemoveSession(UUID sessionid) { } #endregion #region XmlRpcHashtableMarshalling private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile) { GroupProfileData group = new GroupProfileData(); group.GroupID = UUID.Parse((string) groupProfile["GroupID"]); group.Name = (string) groupProfile["Name"]; if (groupProfile["Charter"] != null) { group.Charter = (string) groupProfile["Charter"]; } group.ShowInList = ((string) groupProfile["ShowInList"]) == "1"; group.InsigniaID = UUID.Parse((string) groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string) groupProfile["MembershipFee"]); group.OpenEnrollment = ((string) groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string) groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string) groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string) groupProfile["FounderID"]); group.OwnerRole = UUID.Parse((string) groupProfile["OwnerRoleID"]); group.GroupMembershipCount = int.Parse((string) groupProfile["GroupMembershipCount"]); group.GroupRolesCount = int.Parse((string) groupProfile["GroupRolesCount"]); return group; } private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile) { GroupRecord group = new GroupRecord(); group.GroupID = UUID.Parse((string) groupProfile["GroupID"]); group.GroupName = groupProfile["Name"].ToString(); if (groupProfile["Charter"] != null) { group.Charter = (string) groupProfile["Charter"]; } group.ShowInList = ((string) groupProfile["ShowInList"]) == "1"; group.GroupPicture = UUID.Parse((string) groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string) groupProfile["MembershipFee"]); group.OpenEnrollment = ((string) groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string) groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string) groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string) groupProfile["FounderID"]); group.OwnerRoleID = UUID.Parse((string) groupProfile["OwnerRoleID"]); return group; } private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData) { GroupMembershipData data = new GroupMembershipData { AcceptNotices = ((string) respData["AcceptNotices"] == "1"), Contribution = int.Parse((string) respData["Contribution"]), ListInProfile = ((string) respData["ListInProfile"] == "1"), ActiveRole = new UUID((string) respData["SelectedRoleID"]), GroupTitle = (string) respData["Title"], GroupPowers = ulong.Parse((string) respData["GroupPowers"]), GroupID = new UUID((string) respData["GroupID"]) }; // Is this group the agent's active group UUID ActiveGroup = new UUID((string) respData["ActiveGroupID"]); data.Active = data.GroupID.Equals(ActiveGroup); data.AllowPublish = ((string) respData["AllowPublish"] == "1"); if (respData["Charter"] != null) { data.Charter = (string) respData["Charter"]; } data.FounderID = new UUID((string) respData["FounderID"]); data.GroupID = new UUID((string) respData["GroupID"]); data.GroupName = (string) respData["GroupName"]; data.GroupPicture = new UUID((string) respData["InsigniaID"]); data.MaturePublish = ((string) respData["MaturePublish"] == "1"); data.MembershipFee = int.Parse((string) respData["MembershipFee"]); data.OpenEnrollment = ((string) respData["OpenEnrollment"] == "1"); data.ShowInList = ((string) respData["ShowInList"] == "1"); return data; } #endregion #region ISharedRegionModule Members public string Name { get { return "XmlRpcGroupsServicesConnector"; } } // this module is not intended to be replaced, but there should only be 1 of them. public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name)) { m_connectorEnabled = false; return; } MainConsole.Instance.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name); m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty); if (string.IsNullOrEmpty(m_groupsServerURI)) { MainConsole.Instance.ErrorFormat("Please specify a valid URL for GroupsServerURI in Aurora.ini, [Groups]"); m_connectorEnabled = false; return; } m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false); m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty); m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty); m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30); if (m_cacheTimeout == 0) { MainConsole.Instance.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled."); } else { MainConsole.Instance.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout); } // If we got all the config options we need, lets start'er'up m_memoryCache = new ExpiringCache<string, XmlRpcResponse>(); m_connectorEnabled = true; } } public void Close() { MainConsole.Instance.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(IScene scene) { if (m_connectorEnabled) { if (m_accountService == null) { m_accountService = scene.UserAccountService; } scene.RegisterModuleInterface<IGroupsServicesConnector>(this); } } public void RemoveRegion(IScene scene) { if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) { scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); } } public void RegionLoaded(IScene scene) { // TODO: May want to consider listenning for Agent Connections so we can pre-cache group info // scene.EventManager.OnNewClient += OnNewClient; } public void PostInitialise() { // NoOp } #endregion public GroupProfileData GetGroupProfile(UUID requestingAgentID, UUID GroupID) { GroupProfileData profile = new GroupProfileData(); GroupRecord groupInfo = GetGroupRecord(requestingAgentID, GroupID, null); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = GroupID; profile.GroupMembershipCount = GetGroupMembers(requestingAgentID, GroupID).Count; profile.GroupRolesCount = GetGroupRoles(requestingAgentID, GroupID).Count; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; // TODO: Get this from the currency server? profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } GroupMembershipData memberInfo = GetAgentGroupMembership(requestingAgentID, requestingAgentID, GroupID); if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } return profile; } public List<GroupTitlesData> GetGroupTitles(UUID requestingAgentID, UUID GroupID) { List<GroupRolesData> agentRoles = GetAgentGroupRoles(requestingAgentID, requestingAgentID, GroupID); GroupMembershipData agentMembership = GetAgentGroupMembership( requestingAgentID, requestingAgentID, GroupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData { Name = role.Title, UUID = role.RoleID }; if (agentMembership != null) title.Selected = agentMembership.ActiveRole == role.RoleID; titles.Add(title); } return titles; } public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param); if (respData.Contains("error")) { // GroupProfileData is not nullable return new GroupProfileData(); } GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID); GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } public List<GroupProposalInfo> GetActiveProposals(UUID agentID, UUID groupID) { return new List<GroupProposalInfo>(); } public List<GroupProposalInfo> GetInactiveProposals(UUID agentID, UUID groupID) { return new List<GroupProposalInfo>(); } public void VoteOnActiveProposals(UUID agentID, UUID groupID, UUID proposalID, string vote) { } /// <summary> /// Encapsulate the XmlRpc call to standardize security and error handling. /// </summary> private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param) { XmlRpcResponse resp = null; string CacheKey = null; // Only bother with the cache if it isn't disabled. if (m_cacheTimeout > 0) { if (!function.StartsWith("groups.get")) { // Any and all updates cause the cache to clear m_memoryCache.Clear(); } else { StringBuilder sb = new StringBuilder(requestingAgentID + function); #if (!ISWIN) foreach (object key in param.Keys) { if (param[key] != null) { sb.AppendFormat(",{0}:{1}", key, param[key]); } } #else foreach (object key in param.Keys.Cast<object>().Where(key => param[key] != null)) { sb.AppendFormat(",{0}:{1}", key, param[key]); } #endif CacheKey = sb.ToString(); m_memoryCache.TryGetValue(CacheKey, out resp); } } if (resp == null) { string UserService; UUID SessionID; GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID); param.Add("RequestingAgentID", requestingAgentID.ToString()); param.Add("RequestingAgentUserService", UserService); param.Add("RequestingSessionID", SessionID.ToString()); param.Add("ReadKey", m_groupReadKey); param.Add("WriteKey", m_groupWriteKey); IList parameters = new ArrayList(); parameters.Add(param); ConfigurableKeepAliveXmlRpcRequest req; req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive); try { resp = req.Send(m_groupsServerURI, 10000); if ((m_cacheTimeout > 0) && (CacheKey != null)) { m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout)); } } catch (Exception e) { MainConsole.Instance.ErrorFormat( "[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}", function, m_groupsServerURI); MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}{1}", e.Message, e.StackTrace); foreach ( string ResponseLine in req.RequestResponse.Split(new[] {Environment.NewLine}, StringSplitOptions.None)) { MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine); } foreach (string key in param.Keys) { MainConsole.Instance.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key]); } Hashtable respData = new Hashtable {{"error", e.ToString()}}; return respData; } } if (resp.Value is Hashtable) { Hashtable respData = (Hashtable) resp.Value; if (respData.Contains("error") && !respData.Contains("succeed")) { LogRespDataToConsoleError(respData); } return respData; } MainConsole.Instance.ErrorFormat( "[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType()); if (resp.Value is ArrayList) { ArrayList al = (ArrayList) resp.Value; MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count); foreach (object o in al) { MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType(), o); } } else { MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value); } Hashtable error = new Hashtable {{"error", "invalid return value"}}; return error; } private void LogRespDataToConsoleError(Hashtable respData) { MainConsole.Instance.Error("[XMLRPC-GROUPS-CONNECTOR]: Error:"); foreach (string key in respData.Keys) { MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Key: {0}", key); string[] lines = respData[key].ToString().Split(new[] {'\n'}); foreach (string line in lines) { MainConsole.Instance.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}", line); } } } /// <summary> /// Group Request Tokens are an attempt to allow the groups service to authenticate /// requests. /// TODO: This broke after the big grid refactor, either find a better way, or discard this /// </summary> /// <param name = "client"></param> /// <returns></returns> private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID) { UserServiceURL = ""; SessionID = UUID.Zero; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; namespace System.Data.Common { internal class DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is easier to verify correctness // without the risk of the objects of the class being modified during execution. #if DEBUG private const string ConnectionStringPattern = // may not contain embedded null except trailing last value "([\\s;]*" // leading whitespace and extra semicolons + "(?![\\s;])" // key does not start with space or semicolon + "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '==' + "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts + "(?<value>" + "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as "" + "|" + "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as '' + "|" + "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted + "(?<![\"']))" // unquoted value must not stop with " or ' + ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line + ")*" // repeat the key-value pair + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end ; private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture); #endif private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null private const string ConnectionStringQuoteValuePattern = "^[^\"'=;\\s\\p{Cc}]*$"; // generally do not quote the value if it matches the pattern internal const string DataDirectory = "|datadirectory|"; private static readonly Regex s_connectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern); private static readonly Regex s_connectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern); private static readonly Regex s_connectionStringQuoteValueRegex = new Regex(ConnectionStringQuoteValuePattern); // connection string common keywords private static class KEY { internal const string Integrated_Security = "integrated security"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string User_ID = "user id"; }; // known connection string common synonyms private static class SYNONYM { internal const string Pwd = "pwd"; internal const string UID = "uid"; }; private readonly string _usersConnectionString; private readonly Dictionary<string,string> _parsetable; internal readonly NameValuePair KeyChain; internal readonly bool HasPasswordKeyword; // synonyms hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string public DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms) { _parsetable = new Dictionary<string, string>(); _usersConnectionString = ((null != connectionString) ? connectionString : ""); // first pass on parsing, initial syntax check if (0 < _usersConnectionString.Length) { KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, false); HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd)); } } protected DbConnectionOptions(DbConnectionOptions connectionOptions) { // Clone used by SqlConnectionString _usersConnectionString = connectionOptions._usersConnectionString; HasPasswordKeyword = connectionOptions.HasPasswordKeyword; _parsetable = connectionOptions._parsetable; KeyChain = connectionOptions.KeyChain; } internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules) { ADP.CheckArgumentNull(builder, "builder"); ADP.CheckArgumentLength(keyName, "keyName"); if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) { throw ADP.InvalidKeyname(keyName); } if ((null != keyValue) && !IsValueValidInternal(keyValue)) { throw ADP.InvalidValue(keyName); } if ((0 < builder.Length) && (';' != builder[builder.Length - 1])) { builder.Append(";"); } if (useOdbcRules) { builder.Append(keyName); } else { builder.Append(keyName.Replace("=", "==")); } builder.Append("="); if (null != keyValue) { // else <keyword>=; if (s_connectionStringQuoteValueRegex.IsMatch(keyValue)) { // <value> -> <value> builder.Append(keyValue); } else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\''))) { // <val"ue> -> <'val"ue'> builder.Append('\''); builder.Append(keyValue); builder.Append('\''); } else { // <val'ue> -> <"val'ue"> // <=value> -> <"=value"> // <;value> -> <";value"> // < value> -> <" value"> // <va lue> -> <"va lue"> // <va'"lue> -> <"va'""lue"> builder.Append('\"'); builder.Append(keyValue.Replace("\"", "\"\"")); builder.Append('\"'); } } } static private string GetKeyName(StringBuilder buffer) { int count = buffer.Length; while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1])) { count--; // trailing whitespace } return buffer.ToString(0, count).ToLowerInvariant(); } static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace) { int count = buffer.Length; int index = 0; if (trimWhitespace) { while ((index < count) && Char.IsWhiteSpace(buffer[index])) { index++; // leading whitespace } while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1])) { count--; // trailing whitespace } } return buffer.ToString(index, count - index); } // transition states used for parsing private enum ParserState { NothingYet = 1, //start point Key, KeyEqual, KeyEnd, UnquotedValue, DoubleQuoteValue, DoubleQuoteValueQuote, SingleQuoteValue, SingleQuoteValueQuote, BraceQuoteValue, BraceQuoteValueQuote, QuotedValueEnd, NullTermination, }; static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue) { int startposition = currentPosition; buffer.Length = 0; keyname = null; keyvalue = null; char currentChar = '\0'; ParserState parserState = ParserState.NothingYet; int length = connectionString.Length; for (; currentPosition < length; ++currentPosition) { currentChar = connectionString[currentPosition]; switch (parserState) { case ParserState.NothingYet: // [\\s;]* if ((';' == currentChar) || Char.IsWhiteSpace(currentChar)) { continue; } if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); } startposition = currentPosition; if ('=' != currentChar) { parserState = ParserState.Key; break; } else { parserState = ParserState.KeyEqual; continue; } case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+) if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; } if (Char.IsWhiteSpace(currentChar)) { break; } if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.KeyEqual: // \\s*=(?!=)\\s* if (!useOdbcRules && '=' == currentChar) { parserState = ParserState.Key; break; } keyname = GetKeyName(buffer); if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); } buffer.Length = 0; parserState = ParserState.KeyEnd; goto case ParserState.KeyEnd; case ParserState.KeyEnd: if (Char.IsWhiteSpace(currentChar)) { continue; } if (useOdbcRules) { if ('{' == currentChar) { parserState = ParserState.BraceQuoteValue; break; } } else { if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; } if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; } } if (';' == currentChar) { goto ParserExit; } if ('\0' == currentChar) { goto ParserExit; } if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); } parserState = ParserState.UnquotedValue; break; case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))" if (Char.IsWhiteSpace(currentChar)) { break; } if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; } break; case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")" if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; } if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.DoubleQuoteValueQuote: if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; } keyvalue = GetKeyValue(buffer, false); parserState = ParserState.QuotedValueEnd; goto case ParserState.QuotedValueEnd; case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')" if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; } if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.SingleQuoteValueQuote: if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; } keyvalue = GetKeyValue(buffer, false); parserState = ParserState.QuotedValueEnd; goto case ParserState.QuotedValueEnd; case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})" if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; } if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.BraceQuoteValueQuote: if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; } keyvalue = GetKeyValue(buffer, false); parserState = ParserState.QuotedValueEnd; goto case ParserState.QuotedValueEnd; case ParserState.QuotedValueEnd: if (Char.IsWhiteSpace(currentChar)) { continue; } if (';' == currentChar) { goto ParserExit; } if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote case ParserState.NullTermination: // [\\s;\u0000]* if ('\0' == currentChar) { continue; } if (Char.IsWhiteSpace(currentChar)) { continue; } throw ADP.ConnectionStringSyntax(currentPosition); default: throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1); } buffer.Append(currentChar); } ParserExit: switch (parserState) { case ParserState.Key: case ParserState.DoubleQuoteValue: case ParserState.SingleQuoteValue: case ParserState.BraceQuoteValue: // keyword not found/unbalanced double/single quote throw ADP.ConnectionStringSyntax(startposition); case ParserState.KeyEqual: // equal sign at end of line keyname = GetKeyName(buffer); if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.UnquotedValue: // unquoted value at end of line keyvalue = GetKeyValue(buffer, true); char tmpChar = keyvalue[keyvalue.Length - 1]; if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar))) { throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc } break; case ParserState.DoubleQuoteValueQuote: case ParserState.SingleQuoteValueQuote: case ParserState.BraceQuoteValueQuote: case ParserState.QuotedValueEnd: // quoted value at end of line keyvalue = GetKeyValue(buffer, false); break; case ParserState.NothingYet: case ParserState.KeyEnd: case ParserState.NullTermination: // do nothing break; default: throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2); } if ((';' == currentChar) && (currentPosition < connectionString.Length)) { currentPosition++; } return currentPosition; } static private bool IsValueValidInternal(string keyvalue) { if (null != keyvalue) { #if DEBUG bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue); Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex"); #endif return (-1 == keyvalue.IndexOf('\u0000')); } return true; } static private bool IsKeyNameValid(string keyname) { if (null != keyname) { #if DEBUG bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname); Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex"); #endif return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))); } return false; } #if DEBUG private static Dictionary<string,string> SplitConnectionString(string connectionString, Dictionary<string, string> synonyms, bool firstKey) { Dictionary<string, string> parsetable = new Dictionary<string, string>(); Debug.Assert(!firstKey, "ODBC rules are not supported in CoreCLR"); Regex parser = s_connectionStringRegex; const int KeyIndex = 1, ValueIndex = 2; Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index"); Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index"); if (null != connectionString) { Match match = parser.Match(connectionString); if (!match.Success || (match.Length != connectionString.Length)) { throw ADP.ConnectionStringSyntax(match.Length); } int indexValue = 0; CaptureCollection keyvalues = match.Groups[ValueIndex].Captures; foreach (Capture keypair in match.Groups[KeyIndex].Captures) { string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant(); string keyvalue = keyvalues[indexValue++].Value; if (0 < keyvalue.Length) { if (!firstKey) { switch (keyvalue[0]) { case '\"': keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\""); break; case '\'': keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'"); break; default: break; } } } else { keyvalue = null; } string realkeyname = null; if (synonyms == null || !synonyms.TryGetValue(keyname, out realkeyname)) { realkeyname = keyname; } if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); } if (!firstKey || !parsetable.ContainsKey(realkeyname)) { parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } } } return parsetable; } private static void ParseComparison(Dictionary<string, string> parsetable, string connectionString, Dictionary<string, string> synonyms, bool firstKey, Exception e) { try { Dictionary<string, string> parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey); foreach (KeyValuePair<string, string> entry in parsedvalues) { string keyname = entry.Key; string value1 = entry.Value; string value2 = null; parsetable.TryGetValue(keyname, out value2); Debug.Assert(parsetable.ContainsKey(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">"); Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">"); } } catch (ArgumentException f) { if (null != e) { string msg1 = e.Message; string msg2 = f.Message; const string KeywordNotSupportedMessagePrefix = "Keyword not supported:"; const string WrongFormatMessagePrefix = "Format of the initialization string"; bool isEquivalent = (msg1 == msg2); if (!isEquivalent) { // We also accept cases were Regex parser (debug only) reports "wrong format" and // retail parsing code reports format exception in different location or "keyword not supported" if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) { if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) { isEquivalent = true; } } } Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">"); } else { Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message); } e = null; } if (null != e) { Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch"); } } #endif private static NameValuePair ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms, bool firstKey) { Debug.Assert(null != connectionString, "null connectionstring"); StringBuilder buffer = new StringBuilder(); NameValuePair localKeychain = null, keychain = null; #if DEBUG try { #endif int nextStartPosition = 0; int endPosition = connectionString.Length; while (nextStartPosition < endPosition) { int startPosition = nextStartPosition; string keyname, keyvalue; nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue); if (ADP.IsEmpty(keyname)) { break; } #if DEBUG Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname"); Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue"); #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); } if (!firstKey || !parsetable.ContainsKey(realkeyname)) { parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } if (null != localKeychain) { localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); } else if (buildChain) { // first time only - don't contain modified chain from UDL file keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); } } #if DEBUG } catch (ArgumentException e) { ParseComparison(parsetable, connectionString, synonyms, firstKey, e); throw; } ParseComparison(parsetable, connectionString, synonyms, firstKey, null); #endif return keychain; } internal static void ValidateKeyValuePair(string keyword, string value) { if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) { throw ADP.InvalidKeyname(keyword); } if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value)) { throw ADP.InvalidValue(keyword); } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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 Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; namespace Aurora.Modules.Wind { public class WindModule : IWindModule, INonSharedRegionModule { private const string m_dWindPluginName = "SimpleRandomWind"; private readonly Dictionary<string, IWindModelPlugin> m_availableWindPlugins = new Dictionary<string, IWindModelPlugin>(); private string desiredWindPlugin = ""; private IWindModelPlugin m_activeWindPlugin; private bool m_enabled; private uint m_frame; private uint m_frameLastUpdateClientArray; private int m_frameUpdateRate = 150; //private Random m_rndnums = new Random(Environment.TickCount); private bool m_ready; private IScene m_scene; private IConfig windConfig; private Vector2[] windSpeeds = new Vector2[16*16]; #region IRegion Methods public bool IsSharedModule { get { return false; } } public void Initialise(IConfigSource config) { windConfig = config.Configs["Wind"]; desiredWindPlugin = m_dWindPluginName; if (windConfig != null) { m_enabled = windConfig.GetBoolean("enabled", true); m_frameUpdateRate = windConfig.GetInt("wind_update_rate", 150); // Determine which wind model plugin is desired if (windConfig.Contains("wind_plugin")) { desiredWindPlugin = windConfig.GetString("wind_plugin"); } } } public void AddRegion(IScene scene) { m_scene = scene; if (m_enabled) { //MainConsole.Instance.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate); m_frame = 0; // Register all the Wind Model Plug-ins foreach (IWindModelPlugin windPlugin in AuroraModuleLoader.PickupModules<IWindModelPlugin>()) { //MainConsole.Instance.InfoFormat("[WIND] Found Plugin: {0}", windPlugin.Name); m_availableWindPlugins.Add(windPlugin.Name, windPlugin); } // Check for desired plugin if (m_availableWindPlugins.ContainsKey(desiredWindPlugin)) { m_activeWindPlugin = m_availableWindPlugins[desiredWindPlugin]; //MainConsole.Instance.InfoFormat("[WIND] {0} plugin found, initializing.", desiredWindPlugin); if (windConfig != null) { m_activeWindPlugin.Initialise(); m_activeWindPlugin.WindConfig(m_scene, windConfig); } } // if the plug-in wasn't found, default to no wind. if (m_activeWindPlugin == null) { MainConsole.Instance.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", desiredWindPlugin); MainConsole.Instance.ErrorFormat("[WIND] Defaulting to no wind."); } if (MainConsole.Instance != null) { // Get a list of the parameters for each plugin foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values) { MainConsole.Instance.Commands.AddCommand( String.Format("wind base wind_plugin {0}", windPlugin.Name), String.Format("{0} - {1}", windPlugin.Name, windPlugin.Description), "", HandleConsoleBaseCommand); MainConsole.Instance.Commands.AddCommand( String.Format("wind base wind_update_rate"), "Change the wind update rate.", "", HandleConsoleBaseCommand); foreach (KeyValuePair<string, string> kvp in windPlugin.WindParams()) { MainConsole.Instance.Commands.AddCommand( String.Format("wind {0} {1}", windPlugin.Name, kvp.Key), String.Format("{0} : {1} - {2}", windPlugin.Name, kvp.Key, kvp.Value), "", HandleConsoleParamCommand); } } } // Register event handlers for when Avatars enter the region, and frame ticks m_scene.EventManager.OnFrame += WindUpdate; m_scene.EventManager.OnMakeRootAgent += OnAgentEnteredRegion; // Register the wind module m_scene.RegisterModuleInterface<IWindModule>(this); // Generate initial wind values GenWindPos(); // Mark Module Ready for duty m_ready = true; } } public void RemoveRegion(IScene scene) { if (m_enabled) { m_ready = false; m_activeWindPlugin = null; m_availableWindPlugins.Clear(); // Remove our hooks m_scene.EventManager.OnFrame -= WindUpdate; m_scene.EventManager.OnMakeRootAgent -= OnAgentEnteredRegion; } } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public void Close() { } public string Name { get { return "WindModule"; } } public void PostInitialise() { } #endregion #region Console Commands private void ValidateConsole() { if (MainConsole.Instance.ConsoleScene != m_scene) { MainConsole.Instance.InfoFormat("[WIND]: Console Scene is not my scene."); return; } } /// <summary> /// Base console command handler, only used if a person specifies the base command with now options /// </summary> private void HandleConsoleCommand(string[] cmdparams) { ValidateConsole(); MainConsole.Instance.Info( "[WIND] The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins."); } /// <summary> /// Called to change the active wind model plugin /// </summary> private void HandleConsoleBaseCommand(string[] cmdparams) { ValidateConsole(); if ((cmdparams.Length != 4) || !cmdparams[1].Equals("base")) { MainConsole.Instance.Info( "[WIND] Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>"); return; } switch (cmdparams[2]) { case "wind_update_rate": int newRate = 1; if (int.TryParse(cmdparams[3], out newRate)) { m_frameUpdateRate = newRate; } else { MainConsole.Instance.InfoFormat("[WIND] Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]); return; } break; case "wind_plugin": string desiredPlugin = cmdparams[3]; if (desiredPlugin.Equals(m_activeWindPlugin.Name)) { MainConsole.Instance.InfoFormat("[WIND] Wind model plugin {0} is already active", cmdparams[3]); return; } if (m_availableWindPlugins.ContainsKey(desiredPlugin)) { m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]]; MainConsole.Instance.InfoFormat("[WIND] {0} wind model plugin now active", m_activeWindPlugin.Name); } else { MainConsole.Instance.InfoFormat("[WIND] Could not find wind model plugin {0}", desiredPlugin); } break; } } /// <summary> /// Called to change plugin parameters. /// </summary> private void HandleConsoleParamCommand(string[] cmdparams) { ValidateConsole(); // wind <plugin> <param> [value] if ((cmdparams.Length != 4) && (cmdparams.Length != 3)) { MainConsole.Instance.Info("[WIND] Usage: wind <plugin> <param> [value]"); return; } string plugin = cmdparams[1]; string param = cmdparams[2]; float value = 0f; if (cmdparams.Length == 4) { if (!float.TryParse(cmdparams[3], out value)) { MainConsole.Instance.InfoFormat("[WIND] Invalid value {0}", cmdparams[3]); } try { WindParamSet(plugin, param, value); } catch (Exception e) { MainConsole.Instance.InfoFormat("[WIND] {0}", e.Message); } } else { try { value = WindParamGet(plugin, param); MainConsole.Instance.InfoFormat("[WIND] {0} : {1}", param, value); } catch (Exception e) { MainConsole.Instance.InfoFormat("[WIND] {0}", e.Message); } } } #endregion #region IWindModule Methods /// <summary> /// Retrieve the wind speed at the given region coordinate. This /// implimentation ignores Z. /// </summary> /// <param name = "x">0...255</param> /// <param name = "y">0...255</param> public Vector3 WindSpeed(int x, int y, int z) { if (m_activeWindPlugin != null) { return m_activeWindPlugin.WindSpeed(x, y, z); } else { return new Vector3(0.0f, 0.0f, 0.0f); } } public void WindParamSet(string plugin, string param, float value) { if (m_availableWindPlugins.ContainsKey(plugin)) { IWindModelPlugin windPlugin = m_availableWindPlugins[plugin]; windPlugin.WindParamSet(param, value); MainConsole.Instance.InfoFormat("[WIND] {0} set to {1}", param, value); } else { throw new Exception(String.Format("Could not find plugin {0}", plugin)); } } public float WindParamGet(string plugin, string param) { if (m_availableWindPlugins.ContainsKey(plugin)) { IWindModelPlugin windPlugin = m_availableWindPlugins[plugin]; return windPlugin.WindParamGet(param); } else { throw new Exception(String.Format("Could not find plugin {0}", plugin)); } } public string WindActiveModelPluginName { get { if (m_activeWindPlugin != null) { return m_activeWindPlugin.Name; } else { return String.Empty; } } } #endregion /// <summary> /// Called on each frame update. Updates the wind model and clients as necessary. /// </summary> public void WindUpdate() { if (((m_frame++%m_frameUpdateRate) != 0) || !m_ready) { return; } GenWindPos(); SendWindAllClients(); } public void OnAgentEnteredRegion(IScenePresence avatar) { if (m_ready) { if (m_activeWindPlugin != null) { // Ask wind plugin to generate a LL wind array to be cached locally // Try not to update this too often, as it may involve array copies if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate)) { windSpeeds = m_activeWindPlugin.WindLLClientArray(); m_frameLastUpdateClientArray = m_frame; } } avatar.ControllingClient.SendWindData(windSpeeds); } } private void SendWindAllClients() { if (m_ready) { // Ask wind plugin to generate a LL wind array to be cached locally // Try not to update this too often, as it may involve array copies if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate)) { windSpeeds = m_activeWindPlugin.WindLLClientArray(); m_frameLastUpdateClientArray = m_frame; } m_scene.ForEachScenePresence(delegate(IScenePresence sp) { if (!sp.IsChildAgent) sp.ControllingClient.SendWindData(windSpeeds); }); } } /// <summary> /// Calculate the sun's orbital position and its velocity. /// </summary> private void GenWindPos() { if (m_activeWindPlugin != null) { // Tell Wind Plugin to update it's wind data m_activeWindPlugin.WindUpdate(m_frame); } } } }
// 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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting.Test; using Roslyn.Test.Utilities; using Xunit; #pragma warning disable RS0003 // Do not directly await a Task namespace Microsoft.CodeAnalysis.Scripting.CSharp.UnitTests { public class HostModel { public readonly int Foo; } public class InteractiveSessionTests : TestBase { private static readonly Assembly s_lazySystemRuntimeAssembly; private static readonly Assembly SystemRuntimeAssembly = s_lazySystemRuntimeAssembly ?? (s_lazySystemRuntimeAssembly = Assembly.Load(new AssemblyName("System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"))); private static readonly Assembly HostAssembly = typeof(InteractiveSessionTests).GetTypeInfo().Assembly; // TODO: shouldn't be needed private static readonly ScriptOptions OptionsWithFacades = ScriptOptions.Default.AddReferences(SystemRuntimeAssembly); #region Namespaces, Types [Fact] public void CompilationChain_NestedTypesClass() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Foo(string str) { outerStr = str; } class InnerClass { public string innerStr = null; public void Goo() { Foo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerClass iC = new InnerClass(); iC.Goo(); ").ContinueWith(@" System.Console.WriteLine(iC.innerStr); "); using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { script.RunAsync().Wait(); Assert.Equal("test", redirect.Output.Trim()); } } [Fact] public void CompilationChain_NestedTypesStruct() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Foo(string str) { outerStr = str; } struct InnerStruct { public string innerStr; public void Goo() { Foo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerStruct iS = new InnerStruct(); iS.Goo(); ").ContinueWith(@" System.Console.WriteLine(iS.innerStr); "); using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { script.RunAsync().Wait(); Assert.Equal("test", redirect.Output.Trim()); } } [Fact] public void CompilationChain_InterfaceTypes() { var script = CSharpScript.Create(@" interface I1 { int Goo();} class InnerClass : I1 { public int Goo() { return 1; } }").ContinueWith(@" I1 iC = new InnerClass(); ").ContinueWith(@" iC.Goo() "); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void ScriptMemberAccessFromNestedClass() { var script = CSharpScript.Create(@" object field; object Property { get; set; } void Method() { } ").ContinueWith(@" class C { public void Foo() { object f = field; object p = Property; Method(); } } "); ScriptingTestHelpers.AssertCompilationError(script, // (6,20): error CS0120: An object reference is required for the non-static field, method, or property 'field' Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("field"), // (7,20): error CS0120: An object reference is required for the non-static field, method, or property 'Property' Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("Property"), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'Method()' Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("Method()")); } #region Anonymous Types [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith<Array>(@" var c = new { f = 1 }; var d = new { g = 1 }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions2() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith(@" var c = new { f = 1 }; var d = new { g = 1 }; object.ReferenceEquals(a.GetType(), c.GetType()).ToString() + "" "" + object.ReferenceEquals(a.GetType(), b.GetType()).ToString() + "" "" + object.ReferenceEquals(b.GetType(), d.GetType()).ToString() "); Assert.Equal("True False True", script.EvaluateAsync().Result.ToString()); } [WorkItem(543863)] [Fact] public void AnonymousTypes_Redefinition() { var script = CSharpScript.Create(@" var x = new { Foo = ""foo"" }; ").ContinueWith(@" var x = new { Foo = ""foo"" }; ").ContinueWith(@" x.Foo "); var result = script.EvaluateAsync().Result; Assert.Equal("foo", result); } [Fact] public void AnonymousTypes_TopLevel_Empty() { var script = CSharpScript.Create(@" var a = new { }; ").ContinueWith(@" var b = new { }; ").ContinueWith<Array>(@" var c = new { }; var d = new { }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } #endregion #region Dynamic [Fact] public void Dynamic_Expando() { var options = OptionsWithFacades. AddReferences( typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ExpandoObject).GetTypeInfo().Assembly). AddNamespaces( "System.Dynamic"); var script = CSharpScript.Create(@" dynamic expando = new ExpandoObject(); ", options).ContinueWith(@" expando.foo = 1; ").ContinueWith(@" expando.foo "); Assert.Equal(1, script.EvaluateAsync().Result); } #endregion [Fact] public void Enums() { var script = CSharpScript.Create(@" public enum Enum1 { A, B, C } Enum1 E = Enum1.C; E "); var e = script.EvaluateAsync().Result; Assert.True(e.GetType().GetTypeInfo().IsEnum, "Expected enum"); Assert.Equal(typeof(int), Enum.GetUnderlyingType(e.GetType())); } #endregion #region Attributes [Fact] public void PInvoke() { var source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [DllImport(""foo"", EntryPoint = ""bar"", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = true, BestFitMapping = true, ThrowOnUnmappableChar = true)] public static extern void M(); class C { } typeof(C) "; Type c = CSharpScript.EvaluateAsync<Type>(source).Result; var m = c.DeclaringType.GetTypeInfo().GetDeclaredMethod("M"); Assert.Equal(MethodImplAttributes.PreserveSig, m.MethodImplementationFlags); // Reflection synthesizes DllImportAttribute var dllImport = (DllImportAttribute)m.GetCustomAttributes(typeof(DllImportAttribute), inherit: false).Single(); Assert.True(dllImport.BestFitMapping); Assert.Equal(CallingConvention.Cdecl, dllImport.CallingConvention); Assert.Equal(CharSet.Unicode, dllImport.CharSet); Assert.True(dllImport.ExactSpelling); Assert.True(dllImport.SetLastError); Assert.True(dllImport.PreserveSig); Assert.True(dllImport.ThrowOnUnmappableChar); Assert.Equal("bar", dllImport.EntryPoint); Assert.Equal("foo", dllImport.Value); } #endregion // extension methods - must be private, can be top level #region Modifiers and Visibility [Fact] public void PrivateTopLevel() { var script = CSharpScript.Create<int>(@" private int foo() { return 1; } private static int bar() { return 10; } private static int f = 100; foo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" foo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" class C { public static int baz() { return bar() + f; } } C.baz() "); Assert.Equal(110, script.EvaluateAsync().Result); } [Fact] public void NestedVisibility() { var script = CSharpScript.Create(@" private class C { internal class D { internal static int foo() { return 1; } } private class E { internal static int foo() { return 1; } } public class F { internal protected static int foo() { return 1; } } internal protected class G { internal static int foo() { return 1; } } } "); Assert.Equal(1, script.ContinueWith<int>("C.D.foo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.F.foo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.G.foo()").EvaluateAsync().Result); ScriptingTestHelpers.AssertCompilationError(script.ContinueWith<int>(@"C.E.foo()"), // error CS0122: 'C.E' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "E").WithArguments("C.E")); } [Fact] public void Fields_Visibility() { var script = CSharpScript.Create(@" private int i = 2; // test comment; public int j = 2; protected int k = 2; internal protected int l = 2; internal int pi = 2; ").ContinueWith(@" i = i + i; j = j + j; k = k + k; l = l + l; ").ContinueWith(@" pi = i + j + k + l; "); Assert.Equal(4, script.ContinueWith<int>("i").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("j").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("k").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("l").EvaluateAsync().Result); Assert.Equal(16, script.ContinueWith<int>("pi").EvaluateAsync().Result); } #endregion #region Chaining [Fact] public void CompilationChain_BasicFields() { var script = CSharpScript.Create("var x = 1;").ContinueWith("x"); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalNamespaceAndUsings() { var result = CSharpScript.Create("using InteractiveFixtures.C;", OptionsWithFacades.AddReferences(HostAssembly)). ContinueWith("using InteractiveFixtures.C;"). ContinueWith("System.Environment.ProcessorCount"). EvaluateAsync().Result; Assert.Equal(Environment.ProcessorCount, result); } [Fact] public void CompilationChain_CurrentSubmissionUsings() { var s0 = CSharpScript.RunAsync("", OptionsWithFacades.AddReferences(HostAssembly)); var state = s0. ContinueWith("class X { public int foo() { return 1; } }"). ContinueWith("class X { public int foo() { return 1; } }"). ContinueWith("using InteractiveFixtures.A;"). ContinueWith("new X().foo()"); Assert.Equal(1, state.Result.ReturnValue); state = s0. ContinueWith("class X { public int foo() { return 1; } }"). ContinueWith(@" using InteractiveFixtures.A; new X().foo() "); Assert.Equal(1, state.Result.ReturnValue); } [Fact] public void CompilationChain_UsingDuplicates() { var script = CSharpScript.Create(@" using System; using System; ").ContinueWith(@" using System; using System; ").ContinueWith(@" Environment.ProcessorCount "); Assert.Equal(Environment.ProcessorCount, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalImports() { var options = ScriptOptions.Default.AddNamespaces("System"); var state = CSharpScript.RunAsync("Environment.ProcessorCount", options); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); state = state.ContinueWith("Environment.ProcessorCount"); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); } [Fact] public void CompilationChain_SubmissionSlotResize() { var state = CSharpScript.RunAsync(""); for (int i = 0; i < 17; i++) { state = state.ContinueWith(@"public int i = 1;"); } using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { state.ContinueWith(@"System.Console.WriteLine(i);").Wait(); Assert.Equal(1, int.Parse(redirect.Output)); } } [Fact] public void CompilationChain_UsingNotHidingPreviousSubmission() { int result1 = CSharpScript.Create("using System;"). ContinueWith("int Environment = 1;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result1); int result2 = CSharpScript.Create("int Environment = 1;"). ContinueWith("using System;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result2); } [Fact] public void CompilationChain_DefinitionHidesGlobal() { var result = CSharpScript.Create("int System = 1;"). ContinueWith("System"). EvaluateAsync().Result; Assert.Equal(1, result); } public class C1 { public readonly int System = 1; public readonly int Environment = 2; } /// <summary> /// Symbol declaration in host object model hides global definition. /// </summary> [Fact] public void CompilationChain_HostObjectMembersHidesGlobal() { var result = CSharpScript.RunAsync("System", globals: new C1()). Result.ReturnValue; Assert.Equal(1, result); } [Fact] public void CompilationChain_UsingNotHidingHostObjectMembers() { var result = CSharpScript.RunAsync("using System;", globals: new C1()). ContinueWith("Environment"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void CompilationChain_DefinitionHidesHostObjectMembers() { var result = CSharpScript.RunAsync("int System = 2;", globals: new C1()). ContinueWith("System"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void Submissions_ExecutionOrder1() { var s0 = CSharpScript.Create("int x = 1;"); var s1 = s0.ContinueWith("int y = 2;"); var s2 = s1.ContinueWith<int>("x + y"); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); } [Fact] public async Task Submissions_ExecutionOrder2() { var s0 = await CSharpScript.RunAsync("int x = 1;"); Assert.Throws<CompilationErrorException>(() => s0.ContinueWithAsync("invalid$syntax").Result); var s1 = await s0.ContinueWithAsync("x = 2; x = 10"); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("invalid$syntax").Result); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("x = undefined_symbol").Result); var s2 = await s1.ContinueWithAsync("int y = 2;"); Assert.Null(s2.ReturnValue); var s3 = await s2.ContinueWithAsync("x + y"); Assert.Equal(12, s3.ReturnValue); } public class HostObjectWithOverrides { public override bool Equals(object obj) => true; public override int GetHashCode() => 1234567; public override string ToString() => "HostObjectToString impl"; } [Fact] public async Task ObjectOverrides1() { var state0 = await CSharpScript.RunAsync("", OptionsWithFacades, new HostObjectWithOverrides()); var state1 = await state0.ContinueWithAsync<bool>("Equals(null)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<int>("GetHashCode()"); Assert.Equal(1234567, state2.ReturnValue); var state3 = await state2.ContinueWithAsync<string>("ToString()"); Assert.Equal("HostObjectToString impl", state3.ReturnValue); } [Fact] public async Task ObjectOverrides2() { var state0 = await CSharpScript.RunAsync("", OptionsWithFacades, new object()); var state1 = await state0.ContinueWithAsync<bool>(@" object x = 1; object y = x; ReferenceEquals(x, y)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<string>("ToString()"); Assert.Equal("System.Object", state2.ReturnValue); var state3 = await state2.ContinueWithAsync<bool>("Equals(null)"); Assert.False(state3.ReturnValue); } [Fact] public void ObjectOverrides3() { var state0 = CSharpScript.RunAsync("", OptionsWithFacades); var src1 = @" Equals(null); GetHashCode(); ToString(); ReferenceEquals(null, null);"; ScriptingTestHelpers.AssertCompilationError(state0, src1, // (2,1): error CS0103: The name 'Equals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Equals").WithArguments("Equals"), // (3,1): error CS0103: The name 'GetHashCode' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "GetHashCode").WithArguments("GetHashCode"), // (4,1): error CS0103: The name 'ToString' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ToString").WithArguments("ToString"), // (5,1): error CS0103: The name 'ReferenceEquals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ReferenceEquals").WithArguments("ReferenceEquals")); var src2 = @" public override string ToString() { return null; } "; ScriptingTestHelpers.AssertCompilationError(state0, src2, // (1,24): error CS0115: 'ToString()': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "ToString").WithArguments("ToString()")); } #endregion #region Generics [Fact, WorkItem(201759)] public void CompilationChain_GenericTypes() { var script = CSharpScript.Create(@" class InnerClass<T> { public int method(int value) { return value + 1; } public int field = 2; }").ContinueWith(@" InnerClass<int> iC = new InnerClass<int>(); ").ContinueWith(@" iC.method(iC.field) "); Assert.Equal(3, script.EvaluateAsync().Result); } [WorkItem(529243)] [Fact] public void RecursiveBaseType() { CSharpScript.EvaluateAsync(@" class A<T> { } class B<T> : A<B<B<T>>> { } "); } [WorkItem(5378, "DevDiv_Projects/Roslyn")] [Fact] public void CompilationChain_GenericMethods() { var s0 = CSharpScript.Create(@" public int foo<T, R>(T arg) { return 1; } public static T bar<T>(T i) { return i; } "); Assert.Equal(1, s0.ContinueWith(@"foo<int, int>(1)").EvaluateAsync().Result); Assert.Equal(5, s0.ContinueWith(@"bar(5)").EvaluateAsync().Result); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn() { var state = CSharpScript.RunAsync(@" public class C { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C.f)() + new System.Func<int>(new C().g)() + new System.Func<int>(new C().h)()" ); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C.gf<int>)() + new System.Func<int>(new C().gg<object>)() + new System.Func<int>(new C().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn_GenericType() { var state = CSharpScript.RunAsync(@" public class C<S> { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C<byte>.f)() + new System.Func<int>(new C<byte>().g)() + new System.Func<int>(new C<byte>().h)() "); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C<byte>.gf<int>)() + new System.Func<int>(new C<byte>().gg<object>)() + new System.Func<int>(new C<byte>().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } #endregion #region Statements and Expressions [Fact] public void IfStatement() { var result = CSharpScript.EvaluateAsync<int>(@" using static System.Console; int x; if (true) { x = 5; } else { x = 6; } x ").Result; Assert.Equal(5, result); } [Fact] public void ExprStmtParenthesesUsedToOverrideDefaultEval() { Assert.Equal(18, CSharpScript.EvaluateAsync<int>("(4 + 5) * 2").Result); Assert.Equal(1, CSharpScript.EvaluateAsync<long>("6 / (2 * 3)").Result); } [WorkItem(5397, "DevDiv_Projects/Roslyn")] [Fact] public void TopLevelLambda() { var s = CSharpScript.RunAsync(@" using System; delegate void TestDelegate(string s); "); s = s.ContinueWith(@" TestDelegate testDelB = delegate (string s) { Console.WriteLine(s); }; "); using (var redirect = new OutputRedirect(CultureInfo.InvariantCulture)) { s.ContinueWith(@"testDelB(""hello"");").Wait(); Assert.Equal("hello", redirect.Output.Trim()); } } [Fact] public void Closure() { var f = CSharpScript.EvaluateAsync<Func<int, int>>(@" int Foo(int arg) { return arg + 1; } System.Func<int, int> f = (arg) => { return Foo(arg); }; f ").Result; Assert.Equal(3, f(2)); } [Fact] public void Closure2() { var result = CSharpScript.EvaluateAsync<List<string>>(@" #r ""System.Core"" using System; using System.Linq; using System.Collections.Generic; List<string> result = new List<string>(); string s = ""hello""; Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s)); result ").Result; AssertEx.Equal(new[] { "hello", "hello" }, result); } [Fact] public void UseDelegateMixStaticAndDynamic() { var f = CSharpScript.RunAsync("using System;"). ContinueWith("int Sqr(int x) {return x*x;}"). ContinueWith<Func<int, int>>("new Func<int,int>(Sqr)").Result.ReturnValue; Assert.Equal(4, f(2)); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Arrays() { var s = CSharpScript.RunAsync(@" int[] arr_1 = { 1, 2, 3 }; int[] arr_2 = new int[] { 1, 2, 3 }; int[] arr_3 = new int[5]; ").ContinueWith(@" arr_2[0] = 5; "); Assert.Equal(3, s.ContinueWith(@"arr_1[2]").Result.ReturnValue); Assert.Equal(5, s.ContinueWith(@"arr_2[0]").Result.ReturnValue); Assert.Equal(0, s.ContinueWith(@"arr_3[0]").Result.ReturnValue); } [Fact] public void FieldInitializers() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); int b = 2; int a; int x = 1, y = b; static int g = 1; static int f = g + 1; a = x + y; result.Add(a); int z = 4 + f; result.Add(z); result.Add(a * z); result ").Result; Assert.Equal(3, result.Count); Assert.Equal(3, result[0]); Assert.Equal(6, result[1]); Assert.Equal(18, result[2]); } [Fact] public void FieldInitializersWithBlocks() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); const int constant = 1; { int x = constant; result.Add(x); } int field = 2; { int x = field; result.Add(x); } result.Add(constant); result.Add(field); result ").Result; Assert.Equal(4, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(1, result[2]); Assert.Equal(2, result[3]); } [Fact] public void TestInteractiveClosures() { var result = CSharpScript.RunAsync(@" using System.Collections.Generic; static List<int> result = new List<int>();"). ContinueWith("int x = 1;"). ContinueWith("System.Func<int> f = () => x++;"). ContinueWith("result.Add(f());"). ContinueWith("result.Add(x);"). ContinueWith<List<int>>("result").Result.ReturnValue; Assert.Equal(2, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); } [Fact] public void ExtensionMethods() { var options = ScriptOptions.Default.AddReferences( typeof(Enumerable).GetTypeInfo().Assembly); var result = CSharpScript.EvaluateAsync<int>(@" using System.Linq; string[] fruit = { ""banana"", ""orange"", ""lime"", ""apple"", ""kiwi"" }; fruit.Skip(1).Where(s => s.Length > 4).Count()", options).Result; Assert.Equal(2, result); } [Fact] public void ImplicitlyTypedFields() { var result = CSharpScript.EvaluateAsync<object[]>(@" var x = 1; var y = x; var z = foo(x); string foo(int a) { return null; } int foo(string a) { return 0; } new object[] { x, y, z } ").Result; AssertEx.Equal(new object[] { 1, 1, null }, result); } /// <summary> /// Name of PrivateImplementationDetails type needs to be unique across submissions. /// The compiler should suffix it with a MVID of the current submission module so we should be fine. /// </summary> [WorkItem(949559)] [WorkItem(540237)] [WorkItem(9229, "DevDiv_Projects/Roslyn")] [WorkItem(2721, "https://github.com/dotnet/roslyn/issues/2721")] [Fact] public async Task PrivateImplementationDetailsType() { var result1 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4 }"); AssertEx.Equal(new[] { 1, 2, 3, 4 }, result1); var result2 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4,5 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, result2); var s1 = await CSharpScript.RunAsync<int[]>("new int[] { 1,2,3,4,5,6 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6 }, s1.ReturnValue); var s2 = await s1.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, s2.ReturnValue); var s3 = await s2.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7,8 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, s3.ReturnValue); } [Fact] public void NoAwait() { // No await. The return value is Task<int> rather than int. var result = CSharpScript.EvaluateAsync("System.Threading.Tasks.Task.FromResult(1)").Result; Assert.Equal(1, ((Task<int>)result).Result); } /// <summary> /// 'await' expression at top-level. /// </summary> [Fact] public void Await() { Assert.Equal(2, CSharpScript.EvaluateAsync("await System.Threading.Tasks.Task.FromResult(2)").Result); } /// <summary> /// 'await' in sub-expression. /// </summary> [Fact] public void AwaitSubExpression() { Assert.Equal(3, CSharpScript.EvaluateAsync<int>("0 + await System.Threading.Tasks.Task.FromResult(3)").Result); } [Fact] public void AwaitVoid() { var task = CSharpScript.EvaluateAsync<object>("await System.Threading.Tasks.Task.Run(() => { })"); Assert.Equal(null, task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } /// <summary> /// 'await' in lambda should be ignored. /// </summary> [Fact] public async Task AwaitInLambda() { var s0 = await CSharpScript.RunAsync(@" using System; using System.Threading.Tasks; static T F<T>(Func<Task<T>> f) { return f().Result; } static T G<T>(T t, Func<T, Task<T>> f) { return f(t).Result; }"); var s1 = await s0.ContinueWithAsync("F(async () => await Task.FromResult(4))"); Assert.Equal(4, s1.ReturnValue); var s2 = await s1.ContinueWithAsync("G(5, async x => await Task.FromResult(x))"); Assert.Equal(5, s2.ReturnValue); } [Fact] public void AwaitChain1() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddNamespaces("System.Threading.Tasks"); var state = CSharpScript.RunAsync("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact] public void AwaitChain2() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddNamespaces("System.Threading.Tasks"); var state = CSharpScript.Create("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). RunAsync(). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } #endregion #region References [Fact] public void ReferenceDirective_FileWithDependencies() { string file1 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; string file2 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).Path; // ICSPropImpl in CSClasses01.dll implements ICSProp in CSInterfces01.dll. object result = CSharpScript.EvaluateAsync(@" #r """ + file1 + @""" #r """ + file2 + @""" new Metadata.ICSPropImpl() ").Result; Assert.NotNull(result); } [Fact] public void ReferenceDirective_RelativeToBaseParent() { string path = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; string fileName = Path.GetFileName(path); string dir = Path.Combine(Path.GetDirectoryName(path), "subdir"); var script = CSharpScript.Create($@"#r ""..\{fileName}""", ScriptOptions.Default.WithPath(Path.Combine(dir, "a.csx"))); script.GetCompilation().VerifyDiagnostics(); } [Fact] public void ReferenceDirective_RelativeToBaseRoot() { string path = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; string root = Path.GetPathRoot(path); string unrooted = path.Substring(root.Length); string dir = Path.Combine(root, "foo", "bar", "baz"); var script = CSharpScript.Create($@"#r ""\{unrooted}""", ScriptOptions.Default.WithPath(Path.Combine(dir, "a.csx"))); script.GetCompilation().VerifyDiagnostics(); } #endregion #region UsingDeclarations [Fact] public void UsingAlias() { object result = CSharpScript.EvaluateAsync(@" using D = System.Collections.Generic.Dictionary<string, int>; D d = new D(); d ").Result; Assert.True(result is Dictionary<string, int>, "Expected Dictionary<string, int>"); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings1() { var options = ScriptOptions.Default. AddNamespaces("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); object result = CSharpScript.EvaluateAsync("new int[] { 1, 2, 3 }.First()", options).Result; Assert.Equal(1, result); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings2() { var options = ScriptOptions.Default. AddNamespaces("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); var s1 = CSharpScript.RunAsync("new int[] { 1, 2, 3 }.First()", options); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith("new List<int>()", options.AddNamespaces("System.Collections.Generic")); Assert.IsType<List<int>>(s2.Result.ReturnValue); } [Fact] public void AddNamespaces_Errors() { // no immediate error, error is reported if the namespace can't be found when compiling: var options = ScriptOptions.Default.AddNamespaces("?1", "?2"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS0246: The type or namespace name '?1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?1"), // error CS0246: The type or namespace name '?2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?2")); options = ScriptOptions.Default.AddNamespaces(""); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); options = ScriptOptions.Default.AddNamespaces(".abc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ".abc")); options = ScriptOptions.Default.AddNamespaces("a\0bc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "a\0bc")); } #endregion #region Host Object Binding and Conversions public class C<T> { } [Fact] public void Submission_HostConversions() { Assert.Equal(2, CSharpScript.EvaluateAsync<int>("1+1").Result); Assert.Equal(null, CSharpScript.EvaluateAsync<string>("null").Result); try { CSharpScript.RunAsync<C<int>>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { // error CS0400: The type or namespace name 'Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source.InteractiveSessionTests+C`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Roslyn.Compilers.CSharp.Emit.UnitTests, Version=42.42.42.42, Culture=neutral, PublicKeyToken=fc793a00266884fb' could not be found in the global namespace (are you missing an assembly reference?) Assert.Equal(ErrorCode.ERR_GlobalSingleTypeNameNotFound, (ErrorCode)e.Diagnostics.Single().Code); // Can't use Verify() because the version number of the test dll is different in the build lab. } var options = OptionsWithFacades.AddReferences(HostAssembly); var cint = CSharpScript.EvaluateAsync<C<int>>("null", options).Result; Assert.Equal(null, cint); Assert.Equal(null, CSharpScript.EvaluateAsync<int?>("null", options).Result); try { CSharpScript.RunAsync<int>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // null Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int")); } try { CSharpScript.RunAsync<string>("1+1"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0029: Cannot implicitly convert type 'int' to 'string' // 1+1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1+1").WithArguments("int", "string")); } } [Fact] public void Submission_HostVarianceConversions() { var value = CSharpScript.EvaluateAsync<IEnumerable<Exception>>(@" using System; using System.Collections.Generic; new List<ArgumentException>() ").Result; Assert.Equal(null, value.FirstOrDefault()); } public class B { public int x = 1, w = 4; } public class C : B, I { public static readonly int StaticField = 123; public int Y => 2; public string N { get; set; } = "2"; public int Z() => 3; public override int GetHashCode() => 123; } public interface I { string N { get; set; } int Z(); } private class PrivateClass : I { public string N { get; set; } = null; public int Z() => 3; } public class M<T> { private int F() => 3; public T G() => default(T); } [Fact] public void HostObjectBinding_PublicClassMembers() { var c = new C(); var s0 = CSharpScript.RunAsync<int>("x + Y + Z()", OptionsWithFacades, globals: c); Assert.Equal(6, s0.Result.ReturnValue); var s1 = s0.ContinueWith<int>("x"); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith<int>("int x = 20;"); var s3 = s2.ContinueWith<int>("x"); Assert.Equal(20, s3.Result.ReturnValue); } [Fact] public void HostObjectBinding_PublicGenericClassMembers() { var m = new M<string>(); var result = CSharpScript.EvaluateAsync<string>("G()", OptionsWithFacades, globals: m); Assert.Equal(null, result.Result); } [Fact] public async Task HostObjectBinding_Interface() { var c = new C(); var s0 = await CSharpScript.RunAsync<int>("Z()", OptionsWithFacades, c, typeof(I)); Assert.Equal(3, s0.ReturnValue); ScriptingTestHelpers.AssertCompilationError(s0, @"x + Y", // The name '{0}' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y")); var s1 = await s0.ContinueWithAsync<string>("N"); Assert.Equal("2", s1.ReturnValue); } [Fact] public void HostObjectBinding_PrivateClass() { var c = new PrivateClass(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", OptionsWithFacades, c), // (1,1): error CS0122: '<Fully Qualified Name of PrivateClass>.Z()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Z").WithArguments(typeof(PrivateClass).FullName.Replace("+", ".") + ".Z()")); } [Fact] public void HostObjectBinding_PrivateMembers() { object c = new M<int>(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", OptionsWithFacades, c), // (1,1): error CS0103: The name 'z' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Z").WithArguments("Z")); } [Fact] public void HostObjectBinding_PrivateClassImplementingPublicInterface() { var c = new PrivateClass(); var result = CSharpScript.EvaluateAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, result.Result); } [Fact] public void HostObjectBinding_StaticMembers() { var s0 = CSharpScript.RunAsync("static int foo = StaticField;", globals: new C()); var s1 = s0.ContinueWith("static int bar { get { return foo; } }"); var s2 = s1.ContinueWith("class C { public static int baz() { return bar; } }"); var s3 = s2.ContinueWith("C.baz()"); Assert.Equal(123, s3.Result.ReturnValue); } public class D { public int foo(int a) { return 0; } } /// <summary> /// Host object members don't form a method group with submission members. /// </summary> [Fact] public void HostObjectBinding_Overloads() { var s0 = CSharpScript.RunAsync("int foo(double a) { return 2; }", globals: new D()); var s1 = s0.ContinueWith("foo(1)"); Assert.Equal(2, s1.Result.ReturnValue); var s2 = s1.ContinueWith("foo(1.0)"); Assert.Equal(2, s2.Result.ReturnValue); } [Fact] public void HostObjectInRootNamespace() { var obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r0 = CSharpScript.EvaluateAsync<int>("X + Y + Z", globals: obj); Assert.Equal(6, r0.Result); obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r1 = CSharpScript.EvaluateAsync<int>("X", globals: obj); Assert.Equal(1, r1.Result); } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto_defs/grpc/TransactionService.proto #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace VirtualWallet.Proto.Grpc { public static partial class TransactionService { static readonly string __ServiceName = "VirtualWallet.Proto.Grpc.TransactionService"; static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::VirtualWallet.Proto.Messages.Transaction> __Marshaller_Transaction = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::VirtualWallet.Proto.Messages.Transaction.Parser.ParseFrom); static readonly grpc::Marshaller<global::VirtualWallet.Proto.Grpc.TopUpRequest> __Marshaller_TopUpRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::VirtualWallet.Proto.Grpc.TopUpRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::VirtualWallet.Proto.Grpc.TransferRequest> __Marshaller_TransferRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::VirtualWallet.Proto.Grpc.TransferRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::VirtualWallet.Proto.Grpc.PurchaseRequest> __Marshaller_PurchaseRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::VirtualWallet.Proto.Grpc.PurchaseRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::VirtualWallet.Proto.Grpc.TransactionId> __Marshaller_TransactionId = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::VirtualWallet.Proto.Grpc.TransactionId.Parser.ParseFrom); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::VirtualWallet.Proto.Messages.Transaction> __Method_GetAllTransactions = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::VirtualWallet.Proto.Messages.Transaction>( grpc::MethodType.ServerStreaming, __ServiceName, "GetAllTransactions", __Marshaller_Empty, __Marshaller_Transaction); static readonly grpc::Method<global::VirtualWallet.Proto.Grpc.TopUpRequest, global::VirtualWallet.Proto.Messages.Transaction> __Method_NewTopUp = new grpc::Method<global::VirtualWallet.Proto.Grpc.TopUpRequest, global::VirtualWallet.Proto.Messages.Transaction>( grpc::MethodType.Unary, __ServiceName, "NewTopUp", __Marshaller_TopUpRequest, __Marshaller_Transaction); static readonly grpc::Method<global::VirtualWallet.Proto.Grpc.TransferRequest, global::VirtualWallet.Proto.Messages.Transaction> __Method_NewTransfer = new grpc::Method<global::VirtualWallet.Proto.Grpc.TransferRequest, global::VirtualWallet.Proto.Messages.Transaction>( grpc::MethodType.Unary, __ServiceName, "NewTransfer", __Marshaller_TransferRequest, __Marshaller_Transaction); static readonly grpc::Method<global::VirtualWallet.Proto.Grpc.PurchaseRequest, global::VirtualWallet.Proto.Messages.Transaction> __Method_NewPurchase = new grpc::Method<global::VirtualWallet.Proto.Grpc.PurchaseRequest, global::VirtualWallet.Proto.Messages.Transaction>( grpc::MethodType.Unary, __ServiceName, "NewPurchase", __Marshaller_PurchaseRequest, __Marshaller_Transaction); static readonly grpc::Method<global::VirtualWallet.Proto.Grpc.TransactionId, global::VirtualWallet.Proto.Messages.Transaction> __Method_ViewTransaction = new grpc::Method<global::VirtualWallet.Proto.Grpc.TransactionId, global::VirtualWallet.Proto.Messages.Transaction>( grpc::MethodType.ServerStreaming, __ServiceName, "ViewTransaction", __Marshaller_TransactionId, __Marshaller_Transaction); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::VirtualWallet.Proto.Grpc.TransactionServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of TransactionService</summary> public abstract partial class TransactionServiceBase { public virtual global::System.Threading.Tasks.Task GetAllTransactions(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::IServerStreamWriter<global::VirtualWallet.Proto.Messages.Transaction> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::VirtualWallet.Proto.Messages.Transaction> NewTopUp(global::VirtualWallet.Proto.Grpc.TopUpRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::VirtualWallet.Proto.Messages.Transaction> NewTransfer(global::VirtualWallet.Proto.Grpc.TransferRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::VirtualWallet.Proto.Messages.Transaction> NewPurchase(global::VirtualWallet.Proto.Grpc.PurchaseRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task ViewTransaction(global::VirtualWallet.Proto.Grpc.TransactionId request, grpc::IServerStreamWriter<global::VirtualWallet.Proto.Messages.Transaction> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for TransactionService</summary> public partial class TransactionServiceClient : grpc::ClientBase<TransactionServiceClient> { /// <summary>Creates a new client for TransactionService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public TransactionServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for TransactionService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public TransactionServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected TransactionServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected TransactionServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual grpc::AsyncServerStreamingCall<global::VirtualWallet.Proto.Messages.Transaction> GetAllTransactions(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetAllTransactions(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncServerStreamingCall<global::VirtualWallet.Proto.Messages.Transaction> GetAllTransactions(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_GetAllTransactions, null, options, request); } public virtual global::VirtualWallet.Proto.Messages.Transaction NewTopUp(global::VirtualWallet.Proto.Grpc.TopUpRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return NewTopUp(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::VirtualWallet.Proto.Messages.Transaction NewTopUp(global::VirtualWallet.Proto.Grpc.TopUpRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_NewTopUp, null, options, request); } public virtual grpc::AsyncUnaryCall<global::VirtualWallet.Proto.Messages.Transaction> NewTopUpAsync(global::VirtualWallet.Proto.Grpc.TopUpRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return NewTopUpAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::VirtualWallet.Proto.Messages.Transaction> NewTopUpAsync(global::VirtualWallet.Proto.Grpc.TopUpRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_NewTopUp, null, options, request); } public virtual global::VirtualWallet.Proto.Messages.Transaction NewTransfer(global::VirtualWallet.Proto.Grpc.TransferRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return NewTransfer(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::VirtualWallet.Proto.Messages.Transaction NewTransfer(global::VirtualWallet.Proto.Grpc.TransferRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_NewTransfer, null, options, request); } public virtual grpc::AsyncUnaryCall<global::VirtualWallet.Proto.Messages.Transaction> NewTransferAsync(global::VirtualWallet.Proto.Grpc.TransferRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return NewTransferAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::VirtualWallet.Proto.Messages.Transaction> NewTransferAsync(global::VirtualWallet.Proto.Grpc.TransferRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_NewTransfer, null, options, request); } public virtual global::VirtualWallet.Proto.Messages.Transaction NewPurchase(global::VirtualWallet.Proto.Grpc.PurchaseRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return NewPurchase(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::VirtualWallet.Proto.Messages.Transaction NewPurchase(global::VirtualWallet.Proto.Grpc.PurchaseRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_NewPurchase, null, options, request); } public virtual grpc::AsyncUnaryCall<global::VirtualWallet.Proto.Messages.Transaction> NewPurchaseAsync(global::VirtualWallet.Proto.Grpc.PurchaseRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return NewPurchaseAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::VirtualWallet.Proto.Messages.Transaction> NewPurchaseAsync(global::VirtualWallet.Proto.Grpc.PurchaseRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_NewPurchase, null, options, request); } public virtual grpc::AsyncServerStreamingCall<global::VirtualWallet.Proto.Messages.Transaction> ViewTransaction(global::VirtualWallet.Proto.Grpc.TransactionId request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ViewTransaction(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncServerStreamingCall<global::VirtualWallet.Proto.Messages.Transaction> ViewTransaction(global::VirtualWallet.Proto.Grpc.TransactionId request, grpc::CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_ViewTransaction, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override TransactionServiceClient NewInstance(ClientBaseConfiguration configuration) { return new TransactionServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(TransactionServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_GetAllTransactions, serviceImpl.GetAllTransactions) .AddMethod(__Method_NewTopUp, serviceImpl.NewTopUp) .AddMethod(__Method_NewTransfer, serviceImpl.NewTransfer) .AddMethod(__Method_NewPurchase, serviceImpl.NewPurchase) .AddMethod(__Method_ViewTransaction, serviceImpl.ViewTransaction).Build(); } } } #endregion
using System; using Newtonsoft.Json.Linq; namespace XBMCRPC.Methods { public partial class AudioLibrary { private readonly Client _client; public AudioLibrary(Client client) { _client = client; } /// <summary> /// Cleans the audio library from non-existent items /// </summary> public string Clean(bool showdialogs=false) { var jArgs = new JObject(); if (showdialogs != null) { var jpropshowdialogs = JToken.FromObject(showdialogs, _client.Serializer); jArgs.Add(new JProperty("showdialogs", jpropshowdialogs)); } return _client.GetData<string>("AudioLibrary.Clean", jArgs); } /// <summary> /// Exports all items from the audio library /// </summary> public string Export(XBMCRPC.AudioLibrary.Export_optionsPath options) { var jArgs = new JObject(); if (options != null) { var jpropoptions = JToken.FromObject(options, _client.Serializer); jArgs.Add(new JProperty("options", jpropoptions)); } return _client.GetData<string>("AudioLibrary.Export", jArgs); } /// <summary> /// Exports all items from the audio library /// </summary> public string Export(XBMCRPC.AudioLibrary.Export_options1 options) { var jArgs = new JObject(); if (options != null) { var jpropoptions = JToken.FromObject(options, _client.Serializer); jArgs.Add(new JProperty("options", jpropoptions)); } return _client.GetData<string>("AudioLibrary.Export", jArgs); } /// <summary> /// Exports all items from the audio library /// </summary> public string Export() { var jArgs = new JObject(); return _client.GetData<string>("AudioLibrary.Export", jArgs); } /// <summary> /// Retrieve details about a specific album /// </summary> public XBMCRPC.AudioLibrary.GetAlbumDetailsResponse GetAlbumDetails(int albumid=0, XBMCRPC.Audio.Fields.Album properties=null) { var jArgs = new JObject(); if (albumid != null) { var jpropalbumid = JToken.FromObject(albumid, _client.Serializer); jArgs.Add(new JProperty("albumid", jpropalbumid)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumDetailsResponse>("AudioLibrary.GetAlbumDetails", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.AudioLibrary.GetAlbums_filterGenreid filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.AudioLibrary.GetAlbums_filterGenre filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.AudioLibrary.GetAlbums_filterArtistid filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.AudioLibrary.GetAlbums_filterArtist filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.List.Filter.AlbumsAnd filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.List.Filter.AlbumsOr filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.List.Filter.Rule.Albums filter, XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve all albums from specified artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetAlbumsResponse GetAlbums(XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetAlbumsResponse>("AudioLibrary.GetAlbums", jArgs); } /// <summary> /// Retrieve details about a specific artist /// </summary> public XBMCRPC.AudioLibrary.GetArtistDetailsResponse GetArtistDetails(int artistid=0, XBMCRPC.Audio.Fields.Artist properties=null) { var jArgs = new JObject(); if (artistid != null) { var jpropartistid = JToken.FromObject(artistid, _client.Serializer); jArgs.Add(new JProperty("artistid", jpropartistid)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistDetailsResponse>("AudioLibrary.GetArtistDetails", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.AudioLibrary.GetArtists_filterGenreid filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.AudioLibrary.GetArtists_filterGenre filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.AudioLibrary.GetArtists_filterAlbumid filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.AudioLibrary.GetArtists_filterAlbum filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.AudioLibrary.GetArtists_filterSongid filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.List.Filter.ArtistsAnd filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.List.Filter.ArtistsOr filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(XBMCRPC.List.Filter.Rule.Artists filter, bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all artists /// </summary> public XBMCRPC.AudioLibrary.GetArtistsResponse GetArtists(bool? albumartistsonly=null, XBMCRPC.Audio.Fields.Artist properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumartistsonly != null) { var jpropalbumartistsonly = JToken.FromObject(albumartistsonly, _client.Serializer); jArgs.Add(new JProperty("albumartistsonly", jpropalbumartistsonly)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } return _client.GetData<XBMCRPC.AudioLibrary.GetArtistsResponse>("AudioLibrary.GetArtists", jArgs); } /// <summary> /// Retrieve all genres /// </summary> public XBMCRPC.AudioLibrary.GetGenresResponse GetGenres(XBMCRPC.Library.Fields.Genre properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } return _client.GetData<XBMCRPC.AudioLibrary.GetGenresResponse>("AudioLibrary.GetGenres", jArgs); } /// <summary> /// Retrieve recently added albums /// </summary> public XBMCRPC.AudioLibrary.GetRecentlyAddedAlbumsResponse GetRecentlyAddedAlbums(XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } return _client.GetData<XBMCRPC.AudioLibrary.GetRecentlyAddedAlbumsResponse>("AudioLibrary.GetRecentlyAddedAlbums", jArgs); } /// <summary> /// Retrieve recently added songs /// </summary> public XBMCRPC.AudioLibrary.GetRecentlyAddedSongsResponse GetRecentlyAddedSongs(int albumlimit=0, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (albumlimit != null) { var jpropalbumlimit = JToken.FromObject(albumlimit, _client.Serializer); jArgs.Add(new JProperty("albumlimit", jpropalbumlimit)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } return _client.GetData<XBMCRPC.AudioLibrary.GetRecentlyAddedSongsResponse>("AudioLibrary.GetRecentlyAddedSongs", jArgs); } /// <summary> /// Retrieve recently played albums /// </summary> public XBMCRPC.AudioLibrary.GetRecentlyPlayedAlbumsResponse GetRecentlyPlayedAlbums(XBMCRPC.Audio.Fields.Album properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } return _client.GetData<XBMCRPC.AudioLibrary.GetRecentlyPlayedAlbumsResponse>("AudioLibrary.GetRecentlyPlayedAlbums", jArgs); } /// <summary> /// Retrieve recently played songs /// </summary> public XBMCRPC.AudioLibrary.GetRecentlyPlayedSongsResponse GetRecentlyPlayedSongs(XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } return _client.GetData<XBMCRPC.AudioLibrary.GetRecentlyPlayedSongsResponse>("AudioLibrary.GetRecentlyPlayedSongs", jArgs); } /// <summary> /// Retrieve details about a specific song /// </summary> public XBMCRPC.AudioLibrary.GetSongDetailsResponse GetSongDetails(int songid=0, XBMCRPC.Audio.Fields.Song properties=null) { var jArgs = new JObject(); if (songid != null) { var jpropsongid = JToken.FromObject(songid, _client.Serializer); jArgs.Add(new JProperty("songid", jpropsongid)); } if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongDetailsResponse>("AudioLibrary.GetSongDetails", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.AudioLibrary.GetSongs_filterGenreid filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.AudioLibrary.GetSongs_filterGenre filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.AudioLibrary.GetSongs_filterArtistid filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.AudioLibrary.GetSongs_filterArtist filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.AudioLibrary.GetSongs_filterAlbumid filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.AudioLibrary.GetSongs_filterAlbum filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.List.Filter.SongsAnd filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.List.Filter.SongsOr filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.List.Filter.Rule.Songs filter, XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (filter != null) { var jpropfilter = JToken.FromObject(filter, _client.Serializer); jArgs.Add(new JProperty("filter", jpropfilter)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Retrieve all songs from specified album, artist or genre /// </summary> public XBMCRPC.AudioLibrary.GetSongsResponse GetSongs(XBMCRPC.Audio.Fields.Song properties=null, XBMCRPC.List.Limits limits=null, XBMCRPC.List.Sort sort=null, bool includesingles=false) { var jArgs = new JObject(); if (properties != null) { var jpropproperties = JToken.FromObject(properties, _client.Serializer); jArgs.Add(new JProperty("properties", jpropproperties)); } if (limits != null) { var jproplimits = JToken.FromObject(limits, _client.Serializer); jArgs.Add(new JProperty("limits", jproplimits)); } if (sort != null) { var jpropsort = JToken.FromObject(sort, _client.Serializer); jArgs.Add(new JProperty("sort", jpropsort)); } if (includesingles != null) { var jpropincludesingles = JToken.FromObject(includesingles, _client.Serializer); jArgs.Add(new JProperty("includesingles", jpropincludesingles)); } return _client.GetData<XBMCRPC.AudioLibrary.GetSongsResponse>("AudioLibrary.GetSongs", jArgs); } /// <summary> /// Scans the audio sources for new library items /// </summary> public string Scan(string directory=null, bool showdialogs=false) { var jArgs = new JObject(); if (directory != null) { var jpropdirectory = JToken.FromObject(directory, _client.Serializer); jArgs.Add(new JProperty("directory", jpropdirectory)); } if (showdialogs != null) { var jpropshowdialogs = JToken.FromObject(showdialogs, _client.Serializer); jArgs.Add(new JProperty("showdialogs", jpropshowdialogs)); } return _client.GetData<string>("AudioLibrary.Scan", jArgs); } /// <summary> /// Update the given album with the given details /// </summary> public string SetAlbumDetails(int albumid=0, string title=null, global::System.Collections.Generic.List<string> artist=null, string description=null, global::System.Collections.Generic.List<string> genre=null, global::System.Collections.Generic.List<string> theme=null, global::System.Collections.Generic.List<string> mood=null, global::System.Collections.Generic.List<string> style=null, string type=null, string albumlabel=null, int? rating=null, int? year=null) { var jArgs = new JObject(); if (albumid != null) { var jpropalbumid = JToken.FromObject(albumid, _client.Serializer); jArgs.Add(new JProperty("albumid", jpropalbumid)); } if (title != null) { var jproptitle = JToken.FromObject(title, _client.Serializer); jArgs.Add(new JProperty("title", jproptitle)); } if (artist != null) { var jpropartist = JToken.FromObject(artist, _client.Serializer); jArgs.Add(new JProperty("artist", jpropartist)); } if (description != null) { var jpropdescription = JToken.FromObject(description, _client.Serializer); jArgs.Add(new JProperty("description", jpropdescription)); } if (genre != null) { var jpropgenre = JToken.FromObject(genre, _client.Serializer); jArgs.Add(new JProperty("genre", jpropgenre)); } if (theme != null) { var jproptheme = JToken.FromObject(theme, _client.Serializer); jArgs.Add(new JProperty("theme", jproptheme)); } if (mood != null) { var jpropmood = JToken.FromObject(mood, _client.Serializer); jArgs.Add(new JProperty("mood", jpropmood)); } if (style != null) { var jpropstyle = JToken.FromObject(style, _client.Serializer); jArgs.Add(new JProperty("style", jpropstyle)); } if (type != null) { var jproptype = JToken.FromObject(type, _client.Serializer); jArgs.Add(new JProperty("type", jproptype)); } if (albumlabel != null) { var jpropalbumlabel = JToken.FromObject(albumlabel, _client.Serializer); jArgs.Add(new JProperty("albumlabel", jpropalbumlabel)); } if (rating != null) { var jproprating = JToken.FromObject(rating, _client.Serializer); jArgs.Add(new JProperty("rating", jproprating)); } if (year != null) { var jpropyear = JToken.FromObject(year, _client.Serializer); jArgs.Add(new JProperty("year", jpropyear)); } return _client.GetData<string>("AudioLibrary.SetAlbumDetails", jArgs); } /// <summary> /// Update the given artist with the given details /// </summary> public string SetArtistDetails(int artistid=0, string artist=null, global::System.Collections.Generic.List<string> instrument=null, global::System.Collections.Generic.List<string> style=null, global::System.Collections.Generic.List<string> mood=null, string born=null, string formed=null, string description=null, global::System.Collections.Generic.List<string> genre=null, string died=null, string disbanded=null, global::System.Collections.Generic.List<string> yearsactive=null) { var jArgs = new JObject(); if (artistid != null) { var jpropartistid = JToken.FromObject(artistid, _client.Serializer); jArgs.Add(new JProperty("artistid", jpropartistid)); } if (artist != null) { var jpropartist = JToken.FromObject(artist, _client.Serializer); jArgs.Add(new JProperty("artist", jpropartist)); } if (instrument != null) { var jpropinstrument = JToken.FromObject(instrument, _client.Serializer); jArgs.Add(new JProperty("instrument", jpropinstrument)); } if (style != null) { var jpropstyle = JToken.FromObject(style, _client.Serializer); jArgs.Add(new JProperty("style", jpropstyle)); } if (mood != null) { var jpropmood = JToken.FromObject(mood, _client.Serializer); jArgs.Add(new JProperty("mood", jpropmood)); } if (born != null) { var jpropborn = JToken.FromObject(born, _client.Serializer); jArgs.Add(new JProperty("born", jpropborn)); } if (formed != null) { var jpropformed = JToken.FromObject(formed, _client.Serializer); jArgs.Add(new JProperty("formed", jpropformed)); } if (description != null) { var jpropdescription = JToken.FromObject(description, _client.Serializer); jArgs.Add(new JProperty("description", jpropdescription)); } if (genre != null) { var jpropgenre = JToken.FromObject(genre, _client.Serializer); jArgs.Add(new JProperty("genre", jpropgenre)); } if (died != null) { var jpropdied = JToken.FromObject(died, _client.Serializer); jArgs.Add(new JProperty("died", jpropdied)); } if (disbanded != null) { var jpropdisbanded = JToken.FromObject(disbanded, _client.Serializer); jArgs.Add(new JProperty("disbanded", jpropdisbanded)); } if (yearsactive != null) { var jpropyearsactive = JToken.FromObject(yearsactive, _client.Serializer); jArgs.Add(new JProperty("yearsactive", jpropyearsactive)); } return _client.GetData<string>("AudioLibrary.SetArtistDetails", jArgs); } /// <summary> /// Update the given song with the given details /// </summary> public string SetSongDetails(int songid=0, string title=null, global::System.Collections.Generic.List<string> artist=null, global::System.Collections.Generic.List<string> albumartist=null, global::System.Collections.Generic.List<string> genre=null, int? year=null, int? rating=null, string album=null, int? track=null, int? disc=null, int? duration=null, string comment=null, string musicbrainztrackid=null, string musicbrainzartistid=null, string musicbrainzalbumid=null, string musicbrainzalbumartistid=null, int? playcount=null, string lastplayed=null) { var jArgs = new JObject(); if (songid != null) { var jpropsongid = JToken.FromObject(songid, _client.Serializer); jArgs.Add(new JProperty("songid", jpropsongid)); } if (title != null) { var jproptitle = JToken.FromObject(title, _client.Serializer); jArgs.Add(new JProperty("title", jproptitle)); } if (artist != null) { var jpropartist = JToken.FromObject(artist, _client.Serializer); jArgs.Add(new JProperty("artist", jpropartist)); } if (albumartist != null) { var jpropalbumartist = JToken.FromObject(albumartist, _client.Serializer); jArgs.Add(new JProperty("albumartist", jpropalbumartist)); } if (genre != null) { var jpropgenre = JToken.FromObject(genre, _client.Serializer); jArgs.Add(new JProperty("genre", jpropgenre)); } if (year != null) { var jpropyear = JToken.FromObject(year, _client.Serializer); jArgs.Add(new JProperty("year", jpropyear)); } if (rating != null) { var jproprating = JToken.FromObject(rating, _client.Serializer); jArgs.Add(new JProperty("rating", jproprating)); } if (album != null) { var jpropalbum = JToken.FromObject(album, _client.Serializer); jArgs.Add(new JProperty("album", jpropalbum)); } if (track != null) { var jproptrack = JToken.FromObject(track, _client.Serializer); jArgs.Add(new JProperty("track", jproptrack)); } if (disc != null) { var jpropdisc = JToken.FromObject(disc, _client.Serializer); jArgs.Add(new JProperty("disc", jpropdisc)); } if (duration != null) { var jpropduration = JToken.FromObject(duration, _client.Serializer); jArgs.Add(new JProperty("duration", jpropduration)); } if (comment != null) { var jpropcomment = JToken.FromObject(comment, _client.Serializer); jArgs.Add(new JProperty("comment", jpropcomment)); } if (musicbrainztrackid != null) { var jpropmusicbrainztrackid = JToken.FromObject(musicbrainztrackid, _client.Serializer); jArgs.Add(new JProperty("musicbrainztrackid", jpropmusicbrainztrackid)); } if (musicbrainzartistid != null) { var jpropmusicbrainzartistid = JToken.FromObject(musicbrainzartistid, _client.Serializer); jArgs.Add(new JProperty("musicbrainzartistid", jpropmusicbrainzartistid)); } if (musicbrainzalbumid != null) { var jpropmusicbrainzalbumid = JToken.FromObject(musicbrainzalbumid, _client.Serializer); jArgs.Add(new JProperty("musicbrainzalbumid", jpropmusicbrainzalbumid)); } if (musicbrainzalbumartistid != null) { var jpropmusicbrainzalbumartistid = JToken.FromObject(musicbrainzalbumartistid, _client.Serializer); jArgs.Add(new JProperty("musicbrainzalbumartistid", jpropmusicbrainzalbumartistid)); } if (playcount != null) { var jpropplaycount = JToken.FromObject(playcount, _client.Serializer); jArgs.Add(new JProperty("playcount", jpropplaycount)); } if (lastplayed != null) { var jproplastplayed = JToken.FromObject(lastplayed, _client.Serializer); jArgs.Add(new JProperty("lastplayed", jproplastplayed)); } return _client.GetData<string>("AudioLibrary.SetSongDetails", jArgs); } public delegate void OnCleanFinishedDelegate(string sender=null, object data=null); public event OnCleanFinishedDelegate OnCleanFinished; internal void RaiseOnCleanFinished(string sender=null, object data=null) { if (OnCleanFinished != null) { OnCleanFinished.BeginInvoke(sender, data, null, null); } } public delegate void OnCleanStartedDelegate(string sender=null, object data=null); public event OnCleanStartedDelegate OnCleanStarted; internal void RaiseOnCleanStarted(string sender=null, object data=null) { if (OnCleanStarted != null) { OnCleanStarted.BeginInvoke(sender, data, null, null); } } public delegate void OnExportDelegate(string sender=null, XBMCRPC.AudioLibrary.OnExport_data data=null); public event OnExportDelegate OnExport; internal void RaiseOnExport(string sender=null, XBMCRPC.AudioLibrary.OnExport_data data=null) { if (OnExport != null) { OnExport.BeginInvoke(sender, data, null, null); } } public delegate void OnRemoveDelegate(string sender=null, XBMCRPC.AudioLibrary.OnRemove_data data=null); public event OnRemoveDelegate OnRemove; internal void RaiseOnRemove(string sender=null, XBMCRPC.AudioLibrary.OnRemove_data data=null) { if (OnRemove != null) { OnRemove.BeginInvoke(sender, data, null, null); } } public delegate void OnScanFinishedDelegate(string sender=null, object data=null); public event OnScanFinishedDelegate OnScanFinished; internal void RaiseOnScanFinished(string sender=null, object data=null) { if (OnScanFinished != null) { OnScanFinished.BeginInvoke(sender, data, null, null); } } public delegate void OnScanStartedDelegate(string sender=null, object data=null); public event OnScanStartedDelegate OnScanStarted; internal void RaiseOnScanStarted(string sender=null, object data=null) { if (OnScanStarted != null) { OnScanStarted.BeginInvoke(sender, data, null, null); } } public delegate void OnUpdateDelegate(string sender=null, XBMCRPC.AudioLibrary.OnUpdate_data data=null); public event OnUpdateDelegate OnUpdate; internal void RaiseOnUpdate(string sender=null, XBMCRPC.AudioLibrary.OnUpdate_data data=null) { if (OnUpdate != null) { OnUpdate.BeginInvoke(sender, data, null, null); } } } }
#region WatiN Copyright (C) 2006-2009 Jeroen van Menen //Copyright 2006-2009 Jeroen van Menen // // 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 Copyright using System; using System.Text.RegularExpressions; using WatiN.Core.Comparers; using WatiN.Core.Constraints; using WatiN.Core.Logging; using WatiN.Core.Native; namespace WatiN.Core { /// <summary> /// This class provides specialized functionality for a HTML table element. /// </summary> /// <remarks> /// <para> /// To find rows that contain particular cell values use the <see cref="Find.ByTextInColumn(string, int)"/> /// constraint as in the following example: /// </para> /// <code> /// // Find a table row with "some text" in the 3rd (!) column. /// Table table = document.Table("my_table"); /// table.OwnTableRow(Find.ByTextInColumn("some text", 2)); /// </code> /// <para> /// To find rows based on other properties of their contents use the <see cref="Find.ByExistenceOfRelatedElement{T}" /> /// constraint as in the following example: /// </para> /// <code> /// // Find a table row with "some text" in any of its columns. /// Table table = document.Table("my_table"); /// table.OwnTableRow(Find.ByExistenceOfRelatedElement(row => row.OwnTableCell("some text"))); /// </code> /// </remarks> [ElementTag("table")] public class Table : ElementContainer<Table> { public Table(DomContainer domContainer, INativeElement htmlTable) : base(domContainer, htmlTable) {} public Table(DomContainer domContainer, ElementFinder finder) : base(domContainer, finder) { } /// <summary> /// Finds a table row within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="elementId">The element id</param> /// <returns>The table row</returns> public virtual TableRow OwnTableRow(string elementId) { return OwnTableRow(Find.ById(elementId)); } /// <summary> /// Finds a table row within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="elementId">The element id regular expression</param> /// <returns>The table row</returns> public virtual TableRow OwnTableRow(Regex elementId) { return OwnTableRow(Find.ById(elementId)); } /// <summary> /// Finds a table row within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="findBy">The constraint</param> /// <returns>The table row</returns> public virtual TableRow OwnTableRow(Constraint findBy) { return new TableRow(DomContainer, CreateElementFinder<TableRow>(nativeElement => nativeElement.TableRows, findBy)); } /// <summary> /// Finds a table row within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="predicate">The predicate</param> /// <returns>The table row</returns> public virtual TableRow OwnTableRow(Predicate<TableRow> predicate) { return OwnTableRow(Find.ByElement(predicate)); } /// <summary> /// Gets a collection of all table rows within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <returns>The table row collection</returns> public virtual TableRowCollection OwnTableRows { get { return new TableRowCollection(DomContainer, CreateElementFinder<TableRow>(nativeElement => nativeElement.TableRows, null)); } } /// <summary> /// Finds a table body within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="elementId">The element id</param> /// <returns>The table body</returns> public virtual TableBody OwnTableBody(string elementId) { return OwnTableBody(Find.ById(elementId)); } /// <summary> /// Finds a table body within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="elementId">The element id regular expression</param> /// <returns>The table body</returns> public virtual TableBody OwnTableBody(Regex elementId) { return OwnTableBody(Find.ById(elementId)); } /// <summary> /// Finds a table body within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="findBy">The constraint</param> /// <returns>The table body</returns> public virtual TableBody OwnTableBody(Constraint findBy) { return new TableBody(DomContainer, CreateElementFinder<TableBody>(nativeElement => nativeElement.TableBodies, findBy)); } /// <summary> /// Finds a table body within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <param name="predicate">The predicate</param> /// <returns>The table body</returns> public virtual TableBody OwnTableBody(Predicate<TableBody> predicate) { return OwnTableBody(Find.ByElement(predicate)); } /// <summary> /// Gets a collection of all table bodies within the table itself (excluding content from any tables that /// might be nested within it). /// </summary> /// <returns>The table body collection</returns> public virtual TableBodyCollection OwnTableBodies { get { return new TableBodyCollection(DomContainer, CreateElementFinder<TableBody>(nativeElement => nativeElement.TableBodies, null)); } } /// <summary> /// Finds te first row that has an exact match with <paramref name="findText"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, null is returned. This method will look for rows in the /// first <see cref="Core.TableBody"/> including rows in nested tables. /// </summary> /// <param name="findText">The text to find.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRow(string findText, int inColumn) { Logger.LogAction("Searching for '" + findText + "' in column " + inColumn + " of " + GetType().Name + " '" + Id + "'"); return FindInTableRows(Find.ByTextInColumn(findText, inColumn)); } /// <summary> /// Finds te first row that has an exact match with <paramref name="findText"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, null is returned. This method will look for rows in all /// <see cref="Core.TableBody"/> elements but will ignore rows in nested tables. /// </summary> /// <param name="findText">The text to find.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRowInOwnTableRows(string findText, int inColumn) { Logger.LogAction("Searching for '" + findText + "' in column " + inColumn + " of " + GetType().Name + " '" + Id + "'"); return FindInOwnTableRows(Find.ByTextInColumn(findText, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="findTextRegex"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in the /// first <see cref="Core.TableBody"/> including rows in nested tables. /// </summary> /// <param name="findTextRegex">The regular expression the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRow(Regex findTextRegex, int inColumn) { Logger.LogAction("Matching regular expression'{0}' with text in column {1} of {2} '{3}'", findTextRegex, inColumn, GetType().Name, Id); return FindInTableRows(Find.ByTextInColumn(findTextRegex, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="findTextRegex"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in all /// <see cref="Core.TableBody"/> elements but will ignore rows in nested tables. /// </summary> /// <param name="findTextRegex">The regular expression the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRowInOwnTableRows(Regex findTextRegex, int inColumn) { Logger.LogAction("Matching regular expression'{0}' with text in column {1} of {2} '{3}'", findTextRegex, inColumn, GetType().Name, Id); return FindInOwnTableRows(Find.ByTextInColumn(findTextRegex, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="comparer"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in the /// first <see cref="Core.TableBody"/> including rows in nested tables. /// </summary> /// <param name="comparer">The comparer that the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRow(Comparer<string> comparer, int inColumn) { Logger.LogAction("Matching comparer'{0}' with text in column {1} of {2} '{3}'", comparer, inColumn, GetType().Name, Id); return FindInTableRows(Find.ByTextInColumn(comparer, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="comparer"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in all /// <see cref="Core.TableBody"/> elements but will ignore rows in nested tables. /// </summary> /// <param name="comparer">The comparer that the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRowInOwnTableRows(Comparer<string> comparer, int inColumn) { Logger.LogAction("Matching comparer'{0}' with text in column {1} of {2} '{3}'", comparer, inColumn, GetType().Name, Id); return FindInOwnTableRows(Find.ByTextInColumn(comparer, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="predicate"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in the /// first <see cref="Core.TableBody"/> including rows in nested tables. /// </summary> /// <param name="predicate">The predicate that the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRow(Predicate<string> predicate, int inColumn) { return FindInTableRows(Find.ByTextInColumn(predicate, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="predicate"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in all /// <see cref="Core.TableBody"/> elements but will ignore rows in nested tables. /// </summary> /// <param name="predicate">The predicate that the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRowInOwnTableRows(Predicate<string> predicate, int inColumn) { return FindInOwnTableRows(Find.ByTextInColumn(predicate, inColumn)); } /// <summary> /// Finds te first row that matches <paramref name="predicate"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in the /// first <see cref="Core.TableBody"/> including rows in nested tables. /// </summary> /// <param name="predicate">The predicate that the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRow(Predicate<TableCell> predicate, int inColumn) { return FindInTableRows(Find.ByExistenceOfRelatedElement<TableRow>(row => row.TableCell(Find.ByIndex(inColumn) & Find.ByElement(predicate)))); } /// <summary> /// Finds te first row that matches <paramref name="predicate"/> in <paramref name="inColumn"/> /// defined as a TD html element. If no match is found, <c>null</c> is returned. This method will look for rows in all /// <see cref="Core.TableBody"/> elements but will ignore rows in nested tables. /// </summary> /// <param name="predicate">The predicate that the cell text must match.</param> /// <param name="inColumn">Index of the column to find the text in.</param> /// <returns>The searched for <see cref="TableRow"/>; otherwise <c>null</c>.</returns> public virtual TableRow FindRowInOwnTableRows(Predicate<TableCell> predicate, int inColumn) { return FindInOwnTableRows(Find.ByExistenceOfRelatedElement<TableRow>(row => row.OwnTableCell(Find.ByIndex(inColumn) & Find.ByElement(predicate)))); } public override string ToString() { return Id; } private TableRow FindInTableRows(Constraint findBy) { var finder = CreateElementFinder<TableRow>(nativeElement => nativeElement.AllDescendants, findBy); var element = finder.FindFirst(); return element == null ? null : new TableRow(DomContainer, element.NativeElement); } private TableRow FindInOwnTableRows(Constraint findBy) { var finder = CreateElementFinder<TableRow>(nativeElement => nativeElement.TableRows, findBy); var element = finder.FindFirst(); return element == null ? null : new TableRow(DomContainer, element.NativeElement); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using LinqToDB.Extensions; namespace LinqToDB.DataProvider.DB2 { using Data; using Mapping; using SchemaProvider; using SqlProvider; public class DB2DataProvider : DynamicDataProviderBase { public DB2DataProvider(string name, DB2Version version) : base(name, null) { Version = version; SqlProviderFlags.AcceptsTakeAsParameter = false; SqlProviderFlags.AcceptsTakeAsParameterIfSkip = true; SqlProviderFlags.IsDistinctOrderBySupported = version != DB2Version.zOS; SetCharField("CHAR", (r,i) => r.GetString(i).TrimEnd()); _sqlOptimizer = new DB2SqlOptimizer(SqlProviderFlags); } protected override void OnConnectionTypeCreated(Type connectionType) { DB2Types.ConnectionType = connectionType; DB2Types.DB2Int64. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Int64", true); DB2Types.DB2Int32. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Int32", true); DB2Types.DB2Int16. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Int16", true); DB2Types.DB2Decimal. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Decimal", true); DB2Types.DB2DecimalFloat.Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2DecimalFloat", true); DB2Types.DB2Real. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Real", true); DB2Types.DB2Real370. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Real370", true); DB2Types.DB2Double. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Double", true); DB2Types.DB2String. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2String", true); DB2Types.DB2Clob. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Clob", true); DB2Types.DB2Binary. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Binary", true); DB2Types.DB2Blob. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Blob", true); DB2Types.DB2Date. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Date", true); DB2Types.DB2Time. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Time", true); DB2Types.DB2TimeStamp. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2TimeStamp", true); DB2Types.DB2Xml = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Xml", true); DB2Types.DB2RowId. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2RowId", true); DB2Types.DB2DateTime. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2DateTime", false); SetProviderField(DB2Types.DB2Int64, typeof(Int64), "GetDB2Int64"); SetProviderField(DB2Types.DB2Int32, typeof(Int32), "GetDB2Int32"); SetProviderField(DB2Types.DB2Int16, typeof(Int16), "GetDB2Int16"); SetProviderField(DB2Types.DB2Decimal, typeof(Decimal), "GetDB2Decimal"); SetProviderField(DB2Types.DB2DecimalFloat, typeof(Decimal), "GetDB2DecimalFloat"); SetProviderField(DB2Types.DB2Real, typeof(Single), "GetDB2Real"); SetProviderField(DB2Types.DB2Real370, typeof(Single), "GetDB2Real370"); SetProviderField(DB2Types.DB2Double, typeof(Double), "GetDB2Double"); SetProviderField(DB2Types.DB2String, typeof(String), "GetDB2String"); SetProviderField(DB2Types.DB2Clob, typeof(String), "GetDB2Clob"); SetProviderField(DB2Types.DB2Binary, typeof(byte[]), "GetDB2Binary"); SetProviderField(DB2Types.DB2Blob, typeof(byte[]), "GetDB2Blob"); SetProviderField(DB2Types.DB2Date, typeof(DateTime), "GetDB2Date"); SetProviderField(DB2Types.DB2Time, typeof(TimeSpan), "GetDB2Time"); SetProviderField(DB2Types.DB2TimeStamp, typeof(DateTime), "GetDB2TimeStamp"); SetProviderField(DB2Types.DB2Xml, typeof(string), "GetDB2Xml"); SetProviderField(DB2Types.DB2RowId, typeof(byte[]), "GetDB2RowId"); MappingSchema.AddScalarType(DB2Types.DB2Int64, GetNullValue(DB2Types.DB2Int64), true, DataType.Int64); MappingSchema.AddScalarType(DB2Types.DB2Int32, GetNullValue(DB2Types.DB2Int32), true, DataType.Int32); MappingSchema.AddScalarType(DB2Types.DB2Int16, GetNullValue(DB2Types.DB2Int16), true, DataType.Int16); MappingSchema.AddScalarType(DB2Types.DB2Decimal, GetNullValue(DB2Types.DB2Decimal), true, DataType.Decimal); MappingSchema.AddScalarType(DB2Types.DB2DecimalFloat, GetNullValue(DB2Types.DB2DecimalFloat), true, DataType.Decimal); MappingSchema.AddScalarType(DB2Types.DB2Real, GetNullValue(DB2Types.DB2Real), true, DataType.Single); MappingSchema.AddScalarType(DB2Types.DB2Real370, GetNullValue(DB2Types.DB2Real370), true, DataType.Single); MappingSchema.AddScalarType(DB2Types.DB2Double, GetNullValue(DB2Types.DB2Double), true, DataType.Double); MappingSchema.AddScalarType(DB2Types.DB2String, GetNullValue(DB2Types.DB2String), true, DataType.NVarChar); MappingSchema.AddScalarType(DB2Types.DB2Clob, GetNullValue(DB2Types.DB2Clob), true, DataType.NText); MappingSchema.AddScalarType(DB2Types.DB2Binary, GetNullValue(DB2Types.DB2Binary), true, DataType.VarBinary); MappingSchema.AddScalarType(DB2Types.DB2Blob, GetNullValue(DB2Types.DB2Blob), true, DataType.Blob); MappingSchema.AddScalarType(DB2Types.DB2Date, GetNullValue(DB2Types.DB2Date), true, DataType.Date); MappingSchema.AddScalarType(DB2Types.DB2Time, GetNullValue(DB2Types.DB2Time), true, DataType.Time); MappingSchema.AddScalarType(DB2Types.DB2TimeStamp, GetNullValue(DB2Types.DB2TimeStamp), true, DataType.DateTime2); MappingSchema.AddScalarType(DB2Types.DB2Xml, GetNullValue(DB2Types.DB2Xml), true, DataType.Xml); MappingSchema.AddScalarType(DB2Types.DB2RowId, GetNullValue(DB2Types.DB2RowId), true, DataType.VarBinary); _setBlob = GetSetParameter(connectionType, "DB2Parameter", "DB2Type", "DB2Type", "Blob"); if (DB2Types.DB2DateTime.IsSupported) { SetProviderField(DB2Types.DB2DateTime, typeof(DateTime), "GetDB2DateTime"); MappingSchema.AddScalarType(DB2Types.DB2DateTime, GetNullValue(DB2Types.DB2DateTime), true, DataType.DateTime); } if (DataConnection.TraceSwitch.TraceInfo) { DataConnection.WriteTraceLine( DataReaderType.AssemblyEx().FullName, DataConnection.TraceSwitch.DisplayName); DataConnection.WriteTraceLine( DB2Types.DB2DateTime.IsSupported ? "DB2DateTime is supported." : "DB2DateTime is not supported.", DataConnection.TraceSwitch.DisplayName); } DB2Tools.Initialized(); } static object GetNullValue(Type type) { var getValue = Expression.Lambda<Func<object>>(Expression.Convert(Expression.Field(null, type, "Null"), typeof(object))); return getValue.Compile()(); } public override string ConnectionNamespace { get { return "IBM.Data.DB2"; } } protected override string ConnectionTypeName { get { return "IBM.Data.DB2.DB2Connection, IBM.Data.DB2"; } } protected override string DataReaderTypeName { get { return "IBM.Data.DB2.DB2DataReader, IBM.Data.DB2"; } } public DB2Version Version { get; private set; } static class MappingSchemaInstance { public static readonly DB2LUWMappingSchema DB2LUWMappingSchema = new DB2LUWMappingSchema(); public static readonly DB2zOSMappingSchema DB2zOSMappingSchema = new DB2zOSMappingSchema(); } public override MappingSchema MappingSchema { get { switch (Version) { case DB2Version.LUW : return MappingSchemaInstance.DB2LUWMappingSchema; case DB2Version.zOS : return MappingSchemaInstance.DB2zOSMappingSchema; } return base.MappingSchema; } } #if !NETSTANDARD public override ISchemaProvider GetSchemaProvider() { return Version == DB2Version.zOS ? new DB2zOSSchemaProvider() : new DB2LUWSchemaProvider(); } #endif public override ISqlBuilder CreateSqlBuilder() { return Version == DB2Version.zOS ? new DB2zOSSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter) as ISqlBuilder: new DB2LUWSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter); } readonly DB2SqlOptimizer _sqlOptimizer; public override ISqlOptimizer GetSqlOptimizer() { return _sqlOptimizer; } public override void InitCommand(DataConnection dataConnection, CommandType commandType, string commandText, DataParameter[] parameters) { dataConnection.DisposeCommand(); base.InitCommand(dataConnection, commandType, commandText, parameters); } static Action<IDbDataParameter> _setBlob; public override void SetParameter(IDbDataParameter parameter, string name, DataType dataType, object value) { if (value is sbyte) { value = (short)(sbyte)value; dataType = DataType.Int16; } else if (value is byte) { value = (short)(byte)value; dataType = DataType.Int16; } switch (dataType) { case DataType.UInt16 : dataType = DataType.Int32; break; case DataType.UInt32 : dataType = DataType.Int64; break; case DataType.UInt64 : dataType = DataType.Decimal; break; case DataType.VarNumeric : dataType = DataType.Decimal; break; case DataType.DateTime2 : dataType = DataType.DateTime; break; case DataType.Char : case DataType.VarChar : case DataType.NChar : case DataType.NVarChar : if (value is Guid) value = ((Guid)value).ToString(); else if (value is bool) value = Common.ConvertTo<char>.From((bool)value); break; case DataType.Boolean : case DataType.Int16 : if (value is bool) { value = (bool)value ? 1 : 0; dataType = DataType.Int16; } break; case DataType.Guid : if (value is Guid) { value = ((Guid)value).ToByteArray(); dataType = DataType.VarBinary; } break; case DataType.Binary : case DataType.VarBinary : if (value is Guid) value = ((Guid)value).ToByteArray(); break; case DataType.Blob : base.SetParameter(parameter, "@" + name, dataType, value); _setBlob(parameter); return; } base.SetParameter(parameter, "@" + name, dataType, value); } #region BulkCopy DB2BulkCopy _bulkCopy; public override BulkCopyRowsCopied BulkCopy<T>(DataConnection dataConnection, BulkCopyOptions options, IEnumerable<T> source) { if (_bulkCopy == null) _bulkCopy = new DB2BulkCopy(GetConnectionType()); return _bulkCopy.BulkCopy( options.BulkCopyType == BulkCopyType.Default ? DB2Tools.DefaultBulkCopyType : options.BulkCopyType, dataConnection, options, source); } #endregion #region Merge public override int Merge<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source, string tableName, string databaseName, string schemaName) { if (delete) throw new LinqToDBException("DB2 MERGE statement does not support DELETE by source."); return new DB2Merge().Merge(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName); } #endregion } }
#if !SILVERLIGHT using System; using System.Collections.Generic; using System.IO; using System.Net; using ServiceStack.Service; using ServiceStack.ServiceHost; using ServiceStack.Text; namespace ServiceStack.Common.Web { public class HttpResult : IHttpResult, IStreamWriter { public HttpResult() : this((object)null, null) { } public HttpResult(object response) : this(response, null) { } public HttpResult(object response, string contentType) : this(response, contentType, HttpStatusCode.OK) { } public HttpResult(HttpStatusCode statusCode, string statusDescription) : this() { StatusCode = statusCode; StatusDescription = statusDescription; } public HttpResult(object response, HttpStatusCode statusCode) : this(response, null, statusCode) { } public HttpResult(object response, string contentType, HttpStatusCode statusCode) { this.Headers = new Dictionary<string, string>(); this.ResponseFilter = HttpResponseFilter.Instance; this.Response = response; this.ContentType = contentType; this.StatusCode = statusCode; } public HttpResult(FileInfo fileResponse) : this(fileResponse, false, MimeTypes.GetMimeType(fileResponse.Name)) { } public HttpResult(FileInfo fileResponse, bool asAttachment) : this(fileResponse, asAttachment, MimeTypes.GetMimeType(fileResponse.Name)) { } public HttpResult(FileInfo fileResponse, bool asAttachment, string contentType) : this(null, contentType, HttpStatusCode.OK) { this.FileInfo = fileResponse; if (!asAttachment) return; var headerValue = "attachment; " + "filename=\"" + fileResponse.Name + "\"; " + "size=" + fileResponse.Length + "; " + "creation-date=" + fileResponse.CreationTimeUtc.ToString("R").Replace(",", "") + "; " + "modification-date=" + fileResponse.LastWriteTimeUtc.ToString("R").Replace(",", "") + "; " + "read-date=" + fileResponse.LastAccessTimeUtc.ToString("R").Replace(",", ""); this.Headers = new Dictionary<string, string> { { HttpHeaders.ContentDisposition, headerValue }, }; } public HttpResult(Stream responseStream, string contentType) : this(null, contentType, HttpStatusCode.OK) { this.ResponseStream = responseStream; } public HttpResult(string responseText, string contentType) : this(null, contentType, HttpStatusCode.OK) { this.ResponseText = responseText; } public string ResponseText { get; private set; } public Stream ResponseStream { get; private set; } public FileInfo FileInfo { get; private set; } public string ContentType { get; set; } public Dictionary<string, string> Headers { get; private set; } public DateTime LastModified { set { this.Headers[HttpHeaders.LastModified] = value.ToUniversalTime().ToString("r"); } } public string Location { set { if (StatusCode == HttpStatusCode.OK) StatusCode = HttpStatusCode.Redirect; this.Headers[HttpHeaders.Location] = value; } } public void SetPermanentCookie(string name, string value) { SetCookie(name, value, DateTime.UtcNow.AddYears(20), null); } public void SetPermanentCookie(string name, string value, string path) { SetCookie(name, value, DateTime.UtcNow.AddYears(20), path); } public void SetSessionCookie(string name, string value) { SetSessionCookie(name, value, null); } public void SetSessionCookie(string name, string value, string path) { path = path ?? "/"; this.Headers[HttpHeaders.SetCookie] = string.Format("{0}={1};path=" + path, name, value); } public void SetCookie(string name, string value, TimeSpan expiresIn, string path) { var expiresAt = DateTime.UtcNow.Add(expiresIn); SetCookie(name, value, expiresAt, path); } public void SetCookie(string name, string value, DateTime expiresAt, string path) { path = path ?? "/"; var cookie = string.Format("{0}={1};expires={2};path={3}", name, value, expiresAt.ToString("R"), path); this.Headers[HttpHeaders.SetCookie] = cookie; } public void DeleteCookie(string name) { var cookie = string.Format("{0}=;expires={1};path=/", name, DateTime.UtcNow.AddDays(-1).ToString("R")); this.Headers[HttpHeaders.SetCookie] = cookie; } public IDictionary<string, string> Options { get { return this.Headers; } } public int Status { get; set; } public HttpStatusCode StatusCode { get { return (HttpStatusCode) Status; } set { Status = (int) value; } } public string StatusDescription { get; set; } public object Response { get; set; } public IContentTypeWriter ResponseFilter { get; set; } public IRequestContext RequestContext { get; set; } public string View { get; set; } public string Template { get; set; } public void WriteTo(Stream responseStream) { if (this.FileInfo != null) { using (var fs = this.FileInfo.OpenRead()) { fs.WriteTo(responseStream); responseStream.Flush(); } return; } if (this.ResponseStream != null) { this.ResponseStream.WriteTo(responseStream); responseStream.Flush(); try { this.ResponseStream.Dispose(); } catch { /*ignore*/ } return; } if (this.ResponseText != null) { var bytes = System.Text.Encoding.UTF8.GetBytes(this.ResponseText); responseStream.Write(bytes, 0, bytes.Length); responseStream.Flush(); return; } if (this.ResponseFilter == null) throw new ArgumentNullException("ResponseFilter"); if (this.RequestContext == null) throw new ArgumentNullException("RequestContext"); var bytesResponse = this.Response as byte[]; if (bytesResponse != null) { responseStream.Write(bytesResponse, 0, bytesResponse.Length); return; } if (View != null) RequestContext.SetItem("View", View); if (Template != null) RequestContext.SetItem("Template", Template); ResponseFilter.SerializeToStream(this.RequestContext, this.Response, responseStream); } public static HttpResult Status201Created(object response, string newLocationUri) { return new HttpResult(response) { StatusCode = HttpStatusCode.Created, Headers = { { HttpHeaders.Location, newLocationUri }, } }; } } } #endif
using Azure; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using DocumentFormat.OpenXml.Office2013.Excel; using Signum.Entities.Files; using Signum.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; namespace Signum.Engine.Files { public static class BlobContainerClientPool { static ConcurrentDictionary<(string connectionString, string blobContainerName), BlobContainerClient> Pool = new ConcurrentDictionary<(string connectionString, string blobContainerName), BlobContainerClient>(); public static BlobContainerClient Get(string connectionString, string blobContainerName) { return Pool.GetOrAdd((connectionString, blobContainerName), t => new BlobContainerClient(t.connectionString, t.blobContainerName)); } } public enum BlobAction { Open, Download } public class AzureBlobStoragebFileTypeAlgorithm : FileTypeAlgorithmBase, IFileTypeAlgorithm { public Func<IFilePath, BlobContainerClient> GetClient { get; private set; } public Func<bool> WebDownload { get; private set; } = () => false; public Func<IFilePath, string> CalculateSuffix { get; set; } = SuffixGenerators.Safe.YearMonth_Guid_Filename; public bool RenameOnCollision { get; set; } = true; public bool WeakFileReference { get; set; } public bool CreateBlobContainerIfNotExists { get; set; } public Func<string, int, string> RenameAlgorithm { get; set; } = FileTypeAlgorithm.DefaultRenameAlgorithm; public Func<IFilePath, BlobAction> BlobAction { get; set; } = (IFilePath ifp) => { return Files.BlobAction.Download; }; public AzureBlobStoragebFileTypeAlgorithm(Func<IFilePath, BlobContainerClient> getClient) { this.GetClient = getClient; } public PrefixPair GetPrefixPair(IFilePath efp) { var client = GetClient(efp); if (!this.WebDownload()) return PrefixPair.None(); //return PrefixPair.WebOnly($"https://{client.Uri}/{efp.Suffix}"); return PrefixPair.WebOnly($"{client.Uri}"); } public BlobProperties GetProperties(IFilePath fp) { using (HeavyProfiler.Log("AzureBlobStorage GetProperties")) { var client = GetClient(fp); return client.GetBlobClient(fp.Suffix).GetProperties(); } } public Stream OpenRead(IFilePath fp) { using (HeavyProfiler.Log("AzureBlobStorage OpenRead")) { var client = GetClient(fp); return client.GetBlobClient(fp.Suffix).Download().Value.Content; } } public byte[] ReadAllBytes(IFilePath fp) { using (HeavyProfiler.Log("AzureBlobStorage ReadAllBytes")) { var client = GetClient(fp); return client.GetBlobClient(fp.Suffix).Download().Value.Content.ReadAllBytes(); } } public virtual void SaveFile(IFilePath fp) { using (HeavyProfiler.Log("AzureBlobStorage SaveFile")) using (new EntityCache(EntityCacheType.ForceNew)) { if (WeakFileReference) return; string suffix = CalculateSuffix(fp); if (!suffix.HasText()) throw new InvalidOperationException("Suffix not set"); fp.SetPrefixPair(GetPrefixPair(fp)); var client = GetClient(fp); if (CreateBlobContainerIfNotExists) { using (HeavyProfiler.Log("AzureBlobStorage CreateIfNotExists")) { client.CreateIfNotExists(); CreateBlobContainerIfNotExists = false; } } int i = 2; fp.Suffix = suffix.Replace("\\", "/"); while (RenameOnCollision && client.ExistsBlob(fp.Suffix)) { fp.Suffix = RenameAlgorithm(suffix, i).Replace("\\", "/"); i++; } try { var action = this.BlobAction(fp); client.GetBlobClient(fp.Suffix).Upload(new MemoryStream(fp.BinaryFile), httpHeaders: new Azure.Storage.Blobs.Models.BlobHttpHeaders { ContentType = action == Files.BlobAction.Download ? "application/octet-stream" : ContentTypesDict.TryGet(Path.GetExtension(fp.FileName).ToLowerInvariant(), "application/octet-stream"), ContentDisposition = action == Files.BlobAction.Download ? "attachment" : "inline" }); } catch (Exception ex) { ex.Data.Add("Suffix", fp.Suffix); ex.Data.Add("AccountName", client.AccountName); ex.Data.Add("ContainerName", client.Name); } } } public void MoveFile(IFilePath ofp, IFilePath nfp) { using (HeavyProfiler.Log("AzureBlobStorage MoveFile")) { if (WeakFileReference) return; throw new NotImplementedException(); } } public void DeleteFiles(IEnumerable<IFilePath> files) { using (HeavyProfiler.Log("AzureBlobStorage DeleteFiles")) { if (WeakFileReference) return; foreach (var f in files) { GetClient(f).DeleteBlob(f.Suffix); } } } public void DeleteFilesIfExist(IEnumerable<IFilePath> files) { using (HeavyProfiler.Log("AzureBlobStorage DeleteFiles")) { if (WeakFileReference) return; foreach (var f in files) { GetClient(f).DeleteBlobIfExists(f.Suffix); } } } public readonly static Dictionary<string, string> ContentTypesDict = new Dictionary<string, string>() { {".x3d", "application/vnd.hzn-3d-crossword"}, {".3gp", "video/3gpp"}, {".3g2", "video/3gpp2"}, {".mseq", "application/vnd.mseq"}, {".pwn", "application/vnd.3m.post-it-notes"}, {".plb", "application/vnd.3gpp.pic-bw-large"}, {".psb", "application/vnd.3gpp.pic-bw-small"}, {".pvb", "application/vnd.3gpp.pic-bw-var"}, {".tcap", "application/vnd.3gpp2.tcap"}, {".7z", "application/x-7z-compressed"}, {".abw", "application/x-abiword"}, {".ace", "application/x-ace-compressed"}, {".acc", "application/vnd.americandynamics.acc"}, {".acu", "application/vnd.acucobol"}, {".atc", "application/vnd.acucorp"}, {".adp", "audio/adpcm"}, {".aab", "application/x-authorware-bin"}, {".aam", "application/x-authorware-map"}, {".aas", "application/x-authorware-seg"}, {".air", "application/vnd.adobe.air-application-installer-package+zip"}, {".swf", "application/x-shockwave-flash"}, {".fxp", "application/vnd.adobe.fxp"}, {".pdf", "application/pdf"}, {".ppd", "application/vnd.cups-ppd"}, {".dir", "application/x-director"}, {".xdp", "application/vnd.adobe.xdp+xml"}, {".xfdf", "application/vnd.adobe.xfdf"}, {".aac", "audio/x-aac"}, {".ahead", "application/vnd.ahead.space"}, {".azf", "application/vnd.airzip.filesecure.azf"}, {".azs", "application/vnd.airzip.filesecure.azs"}, {".azw", "application/vnd.amazon.ebook"}, {".ami", "application/vnd.amiga.ami"}, {".apk", "application/vnd.android.package-archive"}, {".cii", "application/vnd.anser-web-certificate-issue-initiation"}, {".fti", "application/vnd.anser-web-funds-transfer-initiation"}, {".atx", "application/vnd.antix.game-component"}, {".mpkg", "application/vnd.apple.installer+xml"}, {".aw", "application/applixware"}, {".les", "application/vnd.hhe.lesson-player"}, {".swi", "application/vnd.aristanetworks.swi"}, {".s", "text/x-asm"}, {".atomcat", "application/atomcat+xml"}, {".atomsvc", "application/atomsvc+xml"}, {".atom, .xml", "application/atom+xml"}, {".ac", "application/pkix-attr-cert"}, {".aif", "audio/x-aiff"}, {".avi", "video/x-msvideo"}, {".aep", "application/vnd.audiograph"}, {".dxf", "image/vnd.dxf"}, {".dwf", "model/vnd.dwf"}, {".par", "text/plain-bas"}, {".bcpio", "application/x-bcpio"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".torrent", "application/x-bittorrent"}, {".cod", "application/vnd.rim.cod"}, {".mpm", "application/vnd.blueice.multipass"}, {".bmi", "application/vnd.bmi"}, {".sh", "application/x-sh"}, {".btif", "image/prs.btif"}, {".rep", "application/vnd.businessobjects"}, {".bz", "application/x-bzip"}, {".bz2", "application/x-bzip2"}, {".csh", "application/x-csh"}, {".c", "text/x-c"}, {".cdxml", "application/vnd.chemdraw+xml"}, {".css", "text/css"}, {".cdx", "chemical/x-cdx"}, {".cml", "chemical/x-cml"}, {".csml", "chemical/x-csml"}, {".cdbcmsg", "application/vnd.contact.cmsg"}, {".cla", "application/vnd.claymore"}, {".c4g", "application/vnd.clonk.c4group"}, {".sub", "image/vnd.dvb.subtitle"}, {".cdmia", "application/cdmi-capability"}, {".cdmic", "application/cdmi-container"}, {".cdmid", "application/cdmi-domain"}, {".cdmio", "application/cdmi-object"}, {".cdmiq", "application/cdmi-queue"}, {".c11amc", "application/vnd.cluetrust.cartomobile-config"}, {".c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"}, {".ras", "image/x-cmu-raster"}, {".dae", "model/vnd.collada+xml"}, {".csv", "text/csv"}, {".cpt", "application/mac-compactpro"}, {".wmlc", "application/vnd.wap.wmlc"}, {".cgm", "image/cgm"}, {".ice", "x-conference/x-cooltalk"}, {".cmx", "image/x-cmx"}, {".xar", "application/vnd.xara"}, {".cmc", "application/vnd.cosmocaller"}, {".cpio", "application/x-cpio"}, {".clkx", "application/vnd.crick.clicker"}, {".clkk", "application/vnd.crick.clicker.keyboard"}, {".clkp", "application/vnd.crick.clicker.palette"}, {".clkt", "application/vnd.crick.clicker.template"}, {".clkw", "application/vnd.crick.clicker.wordbank"}, {".wbs", "application/vnd.criticaltools.wbs+xml"}, {".cryptonote", "application/vnd.rig.cryptonote"}, {".cif", "chemical/x-cif"}, {".cmdf", "chemical/x-cmdf"}, {".cu", "application/cu-seeme"}, {".cww", "application/prs.cww"}, {".curl", "text/vnd.curl"}, {".dcurl", "text/vnd.curl.dcurl"}, {".mcurl", "text/vnd.curl.mcurl"}, {".scurl", "text/vnd.curl.scurl"}, {".car", "application/vnd.curl.car"}, {".pcurl", "application/vnd.curl.pcurl"}, {".cmp", "application/vnd.yellowriver-custom-menu"}, {".dssc", "application/dssc+der"}, {".xdssc", "application/dssc+xml"}, {".deb", "application/x-debian-package"}, {".uva", "audio/vnd.dece.audio"}, {".uvi", "image/vnd.dece.graphic"}, {".uvh", "video/vnd.dece.hd"}, {".uvm", "video/vnd.dece.mobile"}, {".uvu", "video/vnd.uvvu.mp4"}, {".uvp", "video/vnd.dece.pd"}, {".uvs", "video/vnd.dece.sd"}, {".uvv", "video/vnd.dece.video"}, {".dvi", "application/x-dvi"}, {".seed", "application/vnd.fdsn.seed"}, {".dtb", "application/x-dtbook+xml"}, {".res", "application/x-dtbresource+xml"}, {".ait", "application/vnd.dvb.ait"}, {".svc", "application/vnd.dvb.service"}, {".eol", "audio/vnd.digital-winds"}, {".djvu", "image/vnd.djvu"}, {".dtd", "application/xml-dtd"}, {".mlp", "application/vnd.dolby.mlp"}, {".wad", "application/x-doom"}, {".dpg", "application/vnd.dpgraph"}, {".dra", "audio/vnd.dra"}, {".dfac", "application/vnd.dreamfactory"}, {".dts", "audio/vnd.dts"}, {".dtshd", "audio/vnd.dts.hd"}, {".dwg", "image/vnd.dwg"}, {".geo", "application/vnd.dynageo"}, {".es", "application/ecmascript"}, {".mag", "application/vnd.ecowin.chart"}, {".mmr", "image/vnd.fujixerox.edmics-mmr"}, {".rlc", "image/vnd.fujixerox.edmics-rlc"}, {".exi", "application/exi"}, {".mgz", "application/vnd.proteus.magazine"}, {".epub", "application/epub+zip"}, {".eml", "message/rfc822"}, {".nml", "application/vnd.enliven"}, {".xpr", "application/vnd.is-xpr"}, {".xif", "image/vnd.xiff"}, {".xfdl", "application/vnd.xfdl"}, {".emma", "application/emma+xml"}, {".ez2", "application/vnd.ezpix-album"}, {".ez3", "application/vnd.ezpix-package"}, {".fst", "image/vnd.fst"}, {".fvt", "video/vnd.fvt"}, {".fbs", "image/vnd.fastbidsheet"}, {".fe_launch", "application/vnd.denovo.fcselayout-link"}, {".f4v", "video/x-f4v"}, {".flv", "video/x-flv"}, {".fpx", "image/vnd.fpx"}, {".npx", "image/vnd.net-fpx"}, {".flx", "text/vnd.fmi.flexstor"}, {".fli", "video/x-fli"}, {".ftc", "application/vnd.fluxtime.clip"}, {".fdf", "application/vnd.fdf"}, {".f", "text/x-fortran"}, {".mif", "application/vnd.mif"}, {".fm", "application/vnd.framemaker"}, {".fh", "image/x-freehand"}, {".fsc", "application/vnd.fsc.weblaunch"}, {".fnc", "application/vnd.frogans.fnc"}, {".ltf", "application/vnd.frogans.ltf"}, {".ddd", "application/vnd.fujixerox.ddd"}, {".xdw", "application/vnd.fujixerox.docuworks"}, {".xbd", "application/vnd.fujixerox.docuworks.binder"}, {".oas", "application/vnd.fujitsu.oasys"}, {".oa2", "application/vnd.fujitsu.oasys2"}, {".oa3", "application/vnd.fujitsu.oasys3"}, {".fg5", "application/vnd.fujitsu.oasysgp"}, {".bh2", "application/vnd.fujitsu.oasysprs"}, {".spl", "application/x-futuresplash"}, {".fzs", "application/vnd.fuzzysheet"}, {".g3", "image/g3fax"}, {".gmx", "application/vnd.gmx"}, {".gtw", "model/vnd.gtw"}, {".txd", "application/vnd.genomatix.tuxedo"}, {".ggb", "application/vnd.geogebra.file"}, {".ggt", "application/vnd.geogebra.tool"}, {".gdl", "model/vnd.gdl"}, {".gex", "application/vnd.geometry-explorer"}, {".gxt", "application/vnd.geonext"}, {".g2w", "application/vnd.geoplan"}, {".g3w", "application/vnd.geospace"}, {".gsf", "application/x-font-ghostscript"}, {".bdf", "application/x-font-bdf"}, {".gtar", "application/x-gtar"}, {".texinfo", "application/x-texinfo"}, {".gnumeric", "application/x-gnumeric"}, {".kml", "application/vnd.google-earth.kml+xml"}, {".kmz", "application/vnd.google-earth.kmz"}, {".gqf", "application/vnd.grafeq"}, {".gif", "image/gif"}, {".gv", "text/vnd.graphviz"}, {".gac", "application/vnd.groove-account"}, {".ghf", "application/vnd.groove-help"}, {".gim", "application/vnd.groove-identity-message"}, {".grv", "application/vnd.groove-injector"}, {".gtm", "application/vnd.groove-tool-message"}, {".tpl", "application/vnd.groove-tool-template"}, {".vcg", "application/vnd.groove-vcard"}, {".h261", "video/h261"}, {".h263", "video/h263"}, {".h264", "video/h264"}, {".hpid", "application/vnd.hp-hpid"}, {".hps", "application/vnd.hp-hps"}, {".hdf", "application/x-hdf"}, {".rip", "audio/vnd.rip"}, {".hbci", "application/vnd.hbci"}, {".jlt", "application/vnd.hp-jlyt"}, {".pcl", "application/vnd.hp-pcl"}, {".hpgl", "application/vnd.hp-hpgl"}, {".hvs", "application/vnd.yamaha.hv-script"}, {".hvd", "application/vnd.yamaha.hv-dic"}, {".hvp", "application/vnd.yamaha.hv-voice"}, {".sfd-hdstx", "application/vnd.hydrostatix.sof-data"}, {".stk", "application/hyperstudio"}, {".hal", "application/vnd.hal+xml"}, {".html", "text/html"}, {".irm", "application/vnd.ibm.rights-management"}, {".sc", "application/vnd.ibm.secure-container"}, {".ics", "text/calendar"}, {".icc", "application/vnd.iccprofile"}, {".ico", "image/x-icon"}, {".igl", "application/vnd.igloader"}, {".ief", "image/ief"}, {".ivp", "application/vnd.immervision-ivp"}, {".ivu", "application/vnd.immervision-ivu"}, {".rif", "application/reginfo+xml"}, {".3dml", "text/vnd.in3d.3dml"}, {".spot", "text/vnd.in3d.spot"}, {".igs", "model/iges"}, {".i2g", "application/vnd.intergeo"}, {".cdy", "application/vnd.cinderella"}, {".xpw", "application/vnd.intercon.formnet"}, {".fcs", "application/vnd.isac.fcs"}, {".ipfix", "application/ipfix"}, {".cer", "application/pkix-cert"}, {".pki", "application/pkixcmp"}, {".crl", "application/pkix-crl"}, {".pkipath", "application/pkix-pkipath"}, {".igm", "application/vnd.insors.igm"}, {".rcprofile", "application/vnd.ipunplugged.rcprofile"}, {".irp", "application/vnd.irepository.package+xml"}, {".jad", "text/vnd.sun.j2me.app-descriptor"}, {".jar", "application/java-archive"}, {".class", "application/java-vm"}, {".jnlp", "application/x-java-jnlp-file"}, {".ser", "application/java-serialized-object"}, {".java", "text/x-java-source,java"}, {".js", "application/javascript"}, {".json", "application/json"}, {".joda", "application/vnd.joost.joda-archive"}, {".jpm", "video/jpm"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg" }, {".jpgv", "video/jpeg"}, {".ktz", "application/vnd.kahootz"}, {".mmd", "application/vnd.chipnuts.karaoke-mmd"}, {".karbon", "application/vnd.kde.karbon"}, {".chrt", "application/vnd.kde.kchart"}, {".kfo", "application/vnd.kde.kformula"}, {".flw", "application/vnd.kde.kivio"}, {".kon", "application/vnd.kde.kontour"}, {".kpr", "application/vnd.kde.kpresenter"}, {".ksp", "application/vnd.kde.kspread"}, {".kwd", "application/vnd.kde.kword"}, {".htke", "application/vnd.kenameaapp"}, {".kia", "application/vnd.kidspiration"}, {".kne", "application/vnd.kinar"}, {".sse", "application/vnd.kodak-descriptor"}, {".lasxml", "application/vnd.las.las+xml"}, {".latex", "application/x-latex"}, {".lbd", "application/vnd.llamagraphics.life-balance.desktop"}, {".lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"}, {".jam", "application/vnd.jam"}, {".123", "application/vnd.lotus-1-2-3"}, {".apr", "application/vnd.lotus-approach"}, {".pre", "application/vnd.lotus-freelance"}, {".nsf", "application/vnd.lotus-notes"}, {".org", "application/vnd.lotus-organizer"}, {".scm", "application/vnd.lotus-screencam"}, {".lwp", "application/vnd.lotus-wordpro"}, {".lvp", "audio/vnd.lucent.voice"}, {".m3u", "audio/x-mpegurl"}, {".m4v", "video/x-m4v"}, {".hqx", "application/mac-binhex40"}, {".portpkg", "application/vnd.macports.portpkg"}, {".mgp", "application/vnd.osgeo.mapguide.package"}, {".mrc", "application/marc"}, {".mrcx", "application/marcxml+xml"}, {".mxf", "application/mxf"}, {".nbp", "application/vnd.wolfram.player"}, {".ma", "application/mathematica"}, {".mathml", "application/mathml+xml"}, {".mbox", "application/mbox"}, {".mc1", "application/vnd.medcalcdata"}, {".mscml", "application/mediaservercontrol+xml"}, {".cdkey", "application/vnd.mediastation.cdkey"}, {".mwf", "application/vnd.mfer"}, {".mfm", "application/vnd.mfmp"}, {".msh", "model/mesh"}, {".mads", "application/mads+xml"}, {".mets", "application/mets+xml"}, {".mods", "application/mods+xml"}, {".meta4", "application/metalink4+xml"}, {".potm", "application/vnd.ms-powerpoint.template.macroenabled.12"}, {".docm", "application/vnd.ms-word.document.macroenabled.12"}, {".dotm", "application/vnd.ms-word.template.macroenabled.12"}, {".mcd", "application/vnd.mcd"}, {".flo", "application/vnd.micrografx.flo"}, {".igx", "application/vnd.micrografx.igx"}, {".es3", "application/vnd.eszigno3+xml"}, {".mdb", "application/x-msaccess"}, {".asf", "video/x-ms-asf"}, {".exe", "application/x-msdownload"}, {".cil", "application/vnd.ms-artgalry"}, {".cab", "application/vnd.ms-cab-compressed"}, {".ims", "application/vnd.ms-ims"}, {".application", "application/x-ms-application"}, {".clp", "application/x-msclip"}, {".mdi", "image/vnd.ms-modi"}, {".eot", "application/vnd.ms-fontobject"}, {".xls", "application/vnd.ms-excel"}, {".xlam", "application/vnd.ms-excel.addin.macroenabled.12"}, {".xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"}, {".xltm", "application/vnd.ms-excel.template.macroenabled.12"}, {".xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"}, {".chm", "application/vnd.ms-htmlhelp"}, {".crd", "application/x-mscardfile"}, {".lrm", "application/vnd.ms-lrm"}, {".mvb", "application/x-msmediaview"}, {".mny", "application/x-msmoney"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, {".obd", "application/x-msbinder"}, {".thmx", "application/vnd.ms-officetheme"}, {".onetoc", "application/onenote"}, {".pya", "audio/vnd.ms-playready.media.pya"}, {".pyv", "video/vnd.ms-playready.media.pyv"}, {".ppt", "application/vnd.ms-powerpoint"}, {".ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"}, {".sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"}, {".pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"}, {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"}, {".mpp", "application/vnd.ms-project"}, {".pub", "application/x-mspublisher"}, {".scd", "application/x-msschedule"}, {".xap", "application/x-silverlight-app"}, {".stl", "application/vnd.ms-pki.stl"}, {".cat", "application/vnd.ms-pki.seccat"}, {".vsd", "application/vnd.visio"}, {".wm", "video/x-ms-wm"}, {".wma", "audio/x-ms-wma"}, {".wax", "audio/x-ms-wax"}, {".wmx", "video/x-ms-wmx"}, {".wmd", "application/x-ms-wmd"}, {".wpl", "application/vnd.ms-wpl"}, {".wmz", "application/x-ms-wmz"}, {".wmv", "video/x-ms-wmv"}, {".wvx", "video/x-ms-wvx"}, {".wmf", "application/x-msmetafile"}, {".trm", "application/x-msterminal"}, {".doc", "application/msword"}, {".wri", "application/x-mswrite"}, {".wps", "application/vnd.ms-works"}, {".xbap", "application/x-ms-xbap"}, {".xps", "application/vnd.ms-xpsdocument"}, {".mid", "audio/midi"}, {".mpy", "application/vnd.ibm.minipay"}, {".afp", "application/vnd.ibm.modcap"}, {".rms", "application/vnd.jcp.javame.midlet-rms"}, {".tmo", "application/vnd.tmobile-livetv"}, {".prc", "application/x-mobipocket-ebook"}, {".mbk", "application/vnd.mobius.mbk"}, {".dis", "application/vnd.mobius.dis"}, {".plc", "application/vnd.mobius.plc"}, {".mqy", "application/vnd.mobius.mqy"}, {".msl", "application/vnd.mobius.msl"}, {".txf", "application/vnd.mobius.txf"}, {".daf", "application/vnd.mobius.daf"}, {".fly", "text/vnd.fly"}, {".mpc", "application/vnd.mophun.certificate"}, {".mpn", "application/vnd.mophun.application"}, {".mj2", "video/mj2"}, {".mpga", "audio/mpeg"}, {".mxu", "video/vnd.mpegurl"}, {".mpeg", "video/mpeg"}, {".m21", "application/mp21"}, {".mp4a", "audio/mp4"}, {".mp4", "video/mp4"}, {".m3u8", "application/vnd.apple.mpegurl"}, {".mus", "application/vnd.musician"}, {".msty", "application/vnd.muvee.style"}, {".mxml", "application/xv+xml"}, {".ngdat", "application/vnd.nokia.n-gage.data"}, {".n-gage", "application/vnd.nokia.n-gage.symbian.install"}, {".ncx", "application/x-dtbncx+xml"}, {".nc", "application/x-netcdf"}, {".nlu", "application/vnd.neurolanguage.nlu"}, {".dna", "application/vnd.dna"}, {".nnd", "application/vnd.noblenet-directory"}, {".nns", "application/vnd.noblenet-sealer"}, {".nnw", "application/vnd.noblenet-web"}, {".rpst", "application/vnd.nokia.radio-preset"}, {".rpss", "application/vnd.nokia.radio-presets"}, {".n3", "text/n3"}, {".edm", "application/vnd.novadigm.edm"}, {".edx", "application/vnd.novadigm.edx"}, {".ext", "application/vnd.novadigm.ext"}, {".gph", "application/vnd.flographit"}, {".ecelp4800", "audio/vnd.nuera.ecelp4800"}, {".ecelp7470", "audio/vnd.nuera.ecelp7470"}, {".ecelp9600", "audio/vnd.nuera.ecelp9600"}, {".oda", "application/oda"}, {".ogx", "application/ogg"}, {".oga", "audio/ogg"}, {".ogv", "video/ogg"}, {".dd2", "application/vnd.oma.dd2+xml"}, {".oth", "application/vnd.oasis.opendocument.text-web"}, {".opf", "application/oebps-package+xml"}, {".qbo", "application/vnd.intu.qbo"}, {".oxt", "application/vnd.openofficeorg.extension"}, {".osf", "application/vnd.yamaha.openscoreformat"}, {".weba", "audio/webm"}, {".webm", "video/webm"}, {".odc", "application/vnd.oasis.opendocument.chart"}, {".otc", "application/vnd.oasis.opendocument.chart-template"}, {".odb", "application/vnd.oasis.opendocument.database"}, {".odf", "application/vnd.oasis.opendocument.formula"}, {".odft", "application/vnd.oasis.opendocument.formula-template"}, {".odg", "application/vnd.oasis.opendocument.graphics"}, {".otg", "application/vnd.oasis.opendocument.graphics-template"}, {".odi", "application/vnd.oasis.opendocument.image"}, {".oti", "application/vnd.oasis.opendocument.image-template"}, {".odp", "application/vnd.oasis.opendocument.presentation"}, {".otp", "application/vnd.oasis.opendocument.presentation-template"}, {".ods", "application/vnd.oasis.opendocument.spreadsheet"}, {".ots", "application/vnd.oasis.opendocument.spreadsheet-template"}, {".odt", "application/vnd.oasis.opendocument.text"}, {".odm", "application/vnd.oasis.opendocument.text-master"}, {".ott", "application/vnd.oasis.opendocument.text-template"}, {".ktx", "image/ktx"}, {".sxc", "application/vnd.sun.xml.calc"}, {".stc", "application/vnd.sun.xml.calc.template"}, {".sxd", "application/vnd.sun.xml.draw"}, {".std", "application/vnd.sun.xml.draw.template"}, {".sxi", "application/vnd.sun.xml.impress"}, {".sti", "application/vnd.sun.xml.impress.template"}, {".sxm", "application/vnd.sun.xml.math"}, {".sxw", "application/vnd.sun.xml.writer"}, {".sxg", "application/vnd.sun.xml.writer.global"}, {".stw", "application/vnd.sun.xml.writer.template"}, {".otf", "application/x-font-otf"}, {".osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"}, {".dp", "application/vnd.osgi.dp"}, {".pdb", "application/vnd.palm"}, {".p", "text/x-pascal"}, {".paw", "application/vnd.pawaafile"}, {".pclxl", "application/vnd.hp-pclxl"}, {".efif", "application/vnd.picsel"}, {".pcx", "image/x-pcx"}, {".psd", "image/vnd.adobe.photoshop"}, {".prf", "application/pics-rules"}, {".pic", "image/x-pict"}, {".chat", "application/x-chat"}, {".p10", "application/pkcs10"}, {".p12", "application/x-pkcs12"}, {".p7m", "application/pkcs7-mime"}, {".p7s", "application/pkcs7-signature"}, {".p7r", "application/x-pkcs7-certreqresp"}, {".p7b", "application/x-pkcs7-certificates"}, {".p8", "application/pkcs8"}, {".plf", "application/vnd.pocketlearn"}, {".pnm", "image/x-portable-anymap"}, {".pbm", "image/x-portable-bitmap"}, {".pcf", "application/x-font-pcf"}, {".pfr", "application/font-tdpfr"}, {".pgn", "application/x-chess-pgn"}, {".pgm", "image/x-portable-graymap"}, {".png", "image/png"}, {".ppm", "image/x-portable-pixmap"}, {".pskcxml", "application/pskc+xml"}, {".pml", "application/vnd.ctc-posml"}, {".ai", "application/postscript"}, {".pfa", "application/x-font-type1"}, {".pbd", "application/vnd.powerbuilder6"}, {".pgp", "application/pgp-signature"}, {".box", "application/vnd.previewsystems.box"}, {".ptid", "application/vnd.pvi.ptid1"}, {".pls", "application/pls+xml"}, {".str", "application/vnd.pg.format"}, {".ei6", "application/vnd.pg.osasli"}, {".dsc", "text/prs.lines.tag"}, {".psf", "application/x-font-linux-psf"}, {".qps", "application/vnd.publishare-delta-tree"}, {".wg", "application/vnd.pmi.widget"}, {".qxd", "application/vnd.quark.quarkxpress"}, {".esf", "application/vnd.epson.esf"}, {".msf", "application/vnd.epson.msf"}, {".ssf", "application/vnd.epson.ssf"}, {".qam", "application/vnd.epson.quickanime"}, {".qfx", "application/vnd.intu.qfx"}, {".qt", "video/quicktime"}, {".rar", "application/x-rar-compressed"}, {".ram", "audio/x-pn-realaudio"}, {".rmp", "audio/x-pn-realaudio-plugin"}, {".rsd", "application/rsd+xml"}, {".rm", "application/vnd.rn-realmedia"}, {".bed", "application/vnd.realvnc.bed"}, {".mxl", "application/vnd.recordare.musicxml"}, {".musicxml", "application/vnd.recordare.musicxml+xml"}, {".rnc", "application/relax-ng-compact-syntax"}, {".rdz", "application/vnd.data-vision.rdz"}, {".rdf", "application/rdf+xml"}, {".rp9", "application/vnd.cloanto.rp9"}, {".jisp", "application/vnd.jisp"}, {".rtf", "application/rtf"}, {".rtx", "text/richtext"}, {".link66", "application/vnd.route66.link66+xml"}, {".rss, .xml", "application/rss+xml"}, {".shf", "application/shf+xml"}, {".st", "application/vnd.sailingtracker.track"}, {".svg", "image/svg+xml"}, {".sus", "application/vnd.sus-calendar"}, {".sru", "application/sru+xml"}, {".setpay", "application/set-payment-initiation"}, {".setreg", "application/set-registration-initiation"}, {".sema", "application/vnd.sema"}, {".semd", "application/vnd.semd"}, {".semf", "application/vnd.semf"}, {".see", "application/vnd.seemail"}, {".snf", "application/x-font-snf"}, {".spq", "application/scvp-vp-request"}, {".spp", "application/scvp-vp-response"}, {".scq", "application/scvp-cv-request"}, {".scs", "application/scvp-cv-response"}, {".sdp", "application/sdp"}, {".etx", "text/x-setext"}, {".movie", "video/x-sgi-movie"}, {".ifm", "application/vnd.shana.informed.formdata"}, {".itp", "application/vnd.shana.informed.formtemplate"}, {".iif", "application/vnd.shana.informed.interchange"}, {".ipk", "application/vnd.shana.informed.package"}, {".tfi", "application/thraud+xml"}, {".shar", "application/x-shar"}, {".rgb", "image/x-rgb"}, {".slt", "application/vnd.epson.salt"}, {".aso", "application/vnd.accpac.simply.aso"}, {".imp", "application/vnd.accpac.simply.imp"}, {".twd", "application/vnd.simtech-mindmapper"}, {".csp", "application/vnd.commonspace"}, {".saf", "application/vnd.yamaha.smaf-audio"}, {".mmf", "application/vnd.smaf"}, {".spf", "application/vnd.yamaha.smaf-phrase"}, {".teacher", "application/vnd.smart.teacher"}, {".svd", "application/vnd.svd"}, {".rq", "application/sparql-query"}, {".srx", "application/sparql-results+xml"}, {".gram", "application/srgs"}, {".grxml", "application/srgs+xml"}, {".ssml", "application/ssml+xml"}, {".skp", "application/vnd.koan"}, {".sgml", "text/sgml"}, {".sdc", "application/vnd.stardivision.calc"}, {".sda", "application/vnd.stardivision.draw"}, {".sdd", "application/vnd.stardivision.impress"}, {".smf", "application/vnd.stardivision.math"}, {".sdw", "application/vnd.stardivision.writer"}, {".sgl", "application/vnd.stardivision.writer-global"}, {".sm", "application/vnd.stepmania.stepchart"}, {".sit", "application/x-stuffit"}, {".sitx", "application/x-stuffitx"}, {".sdkm", "application/vnd.solent.sdkm+xml"}, {".xo", "application/vnd.olpc-sugar"}, {".au", "audio/basic"}, {".wqd", "application/vnd.wqd"}, {".sis", "application/vnd.symbian.install"}, {".smi", "application/smil+xml"}, {".xsm", "application/vnd.syncml+xml"}, {".bdm", "application/vnd.syncml.dm+wbxml"}, {".xdm", "application/vnd.syncml.dm+xml"}, {".sv4cpio", "application/x-sv4cpio"}, {".sv4crc", "application/x-sv4crc"}, {".sbml", "application/sbml+xml"}, {".tsv", "text/tab-separated-values"}, {".tiff", "image/tiff"}, {".tao", "application/vnd.tao.intent-module-archive"}, {".tar", "application/x-tar"}, {".tcl", "application/x-tcl"}, {".tex", "application/x-tex"}, {".tfm", "application/x-tex-tfm"}, {".tei", "application/tei+xml"}, {".txt", "text/plain"}, {".dxp", "application/vnd.spotfire.dxp"}, {".sfs", "application/vnd.spotfire.sfs"}, {".tsd", "application/timestamped-data"}, {".tpt", "application/vnd.trid.tpt"}, {".mxs", "application/vnd.triscape.mxs"}, {".t", "text/troff"}, {".tra", "application/vnd.trueapp"}, {".ttf", "application/x-font-ttf"}, {".ttl", "text/turtle"}, {".umj", "application/vnd.umajin"}, {".uoml", "application/vnd.uoml+xml"}, {".unityweb", "application/vnd.unity"}, {".ufd", "application/vnd.ufdl"}, {".uri", "text/uri-list"}, {".utz", "application/vnd.uiq.theme"}, {".ustar", "application/x-ustar"}, {".uu", "text/x-uuencode"}, {".vcs", "text/x-vcalendar"}, {".vcf", "text/x-vcard"}, {".vcd", "application/x-cdlink"}, {".vsf", "application/vnd.vsf"}, {".wrl", "model/vrml"}, {".vcx", "application/vnd.vcx"}, {".mts", "model/vnd.mts"}, {".vtu", "model/vnd.vtu"}, {".vis", "application/vnd.visionary"}, {".viv", "video/vnd.vivo"}, {".ccxml", "application/ccxml+xml,"}, {".vxml", "application/voicexml+xml"}, {".src", "application/x-wais-source"}, {".wbxml", "application/vnd.wap.wbxml"}, {".wbmp", "image/vnd.wap.wbmp"}, {".wav", "audio/x-wav"}, {".davmount", "application/davmount+xml"}, {".woff", "application/x-font-woff"}, {".woff2", "application/x-font-woff"}, {".wspolicy", "application/wspolicy+xml"}, {".webp", "image/webp"}, {".wtb", "application/vnd.webturbo"}, {".wgt", "application/widget"}, {".hlp", "application/winhlp"}, {".wml", "text/vnd.wap.wml"}, {".wmls", "text/vnd.wap.wmlscript"}, {".wmlsc", "application/vnd.wap.wmlscriptc"}, {".wpd", "application/vnd.wordperfect"}, {".stf", "application/vnd.wt.stf"}, {".wsdl", "application/wsdl+xml"}, {".xbm", "image/x-xbitmap"}, {".xpm", "image/x-xpixmap"}, {".xwd", "image/x-xwindowdump"}, {".der", "application/x-x509-ca-cert"}, {".fig", "application/x-xfig"}, {".xhtml", "application/xhtml+xml"}, {".xml", "application/xml"}, {".xdf", "application/xcap-diff+xml"}, {".xenc", "application/xenc+xml"}, {".xer", "application/patch-ops-error+xml"}, {".rl", "application/resource-lists+xml"}, {".rs", "application/rls-services+xml"}, {".rld", "application/resource-lists-diff+xml"}, {".xslt", "application/xslt+xml"}, {".xop", "application/xop+xml"}, {".xpi", "application/x-xpinstall"}, {".xspf", "application/xspf+xml"}, {".xul", "application/vnd.mozilla.xul+xml"}, {".xyz", "chemical/x-xyz"}, {".yaml", "text/yaml"}, {".yang", "application/yang"}, {".yin", "application/yin+xml"}, {".zir", "application/vnd.zul"}, {".zip", "application/zip"}, {".zmm", "application/vnd.handheld-entertainment+xml"}, {".zaz", "application/vnd.zzazz.deck+xml"} }; } public static class BlobExtensions { public static bool ExistsBlob(this BlobContainerClient client, string blobName) { return client.GetBlobs(prefix: blobName.BeforeLast("/") ?? "").Any(b => b.Name == blobName); } } }
// 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; namespace Internal.TypeSystem { // This is the api surface necessary to query the field layout of a type public abstract partial class DefType : TypeDesc { /// <summary> /// Bit flags for layout /// </summary> private class FieldLayoutFlags { /// <summary> /// True if ContainsGCPointers has been computed /// </summary> public const int ComputedContainsGCPointers = 1; /// <summary> /// True if the type contains GC pointers /// </summary> public const int ContainsGCPointers = 2; /// <summary> /// True if the instance type only layout is computed /// </summary> public const int ComputedInstanceTypeLayout = 4; /// <summary> /// True if the static field layout for the static regions have been computed /// </summary> public const int ComputedStaticRegionLayout = 8; /// <summary> /// True if the instance type layout is complete including fields /// </summary> public const int ComputedInstanceTypeFieldsLayout = 0x10; /// <summary> /// True if the static field layout for the static fields have been computed /// </summary> public const int ComputedStaticFieldsLayout = 0x20; /// <summary> /// True if information about the shape of value type has been computed. /// </summary> public const int ComputedValueTypeShapeCharacteristics = 0x40; /// <summary> /// True if <see cref="IsByRefLike"/> has been computed. /// </summary> public const int ComputedIsByRefLike = 0x80; /// <summary> /// True if this is a byref-like type. /// </summary> public const int IsByRefLike = 0x100; } private class StaticBlockInfo { public StaticsBlock NonGcStatics; public StaticsBlock GcStatics; public StaticsBlock ThreadStatics; } ThreadSafeFlags _fieldLayoutFlags; LayoutInt _instanceFieldSize; LayoutInt _instanceFieldAlignment; LayoutInt _instanceByteCountUnaligned; LayoutInt _instanceByteAlignment; // Information about various static blocks is rare, so we keep it out of line. StaticBlockInfo _staticBlockInfo; ValueTypeShapeCharacteristics _valueTypeShapeCharacteristics; /// <summary> /// Does a type transitively have any fields which are GC object pointers /// </summary> public bool ContainsGCPointers { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedContainsGCPointers)) { ComputeTypeContainsGCPointers(); } return _fieldLayoutFlags.HasFlags(FieldLayoutFlags.ContainsGCPointers); } } /// <summary> /// The number of bytes required to hold a field of this type /// </summary> public LayoutInt InstanceFieldSize { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedInstanceTypeLayout)) { ComputeInstanceLayout(InstanceLayoutKind.TypeOnly); } return _instanceFieldSize; } } /// <summary> /// What is the alignment requirement of the fields of this type /// </summary> public LayoutInt InstanceFieldAlignment { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedInstanceTypeLayout)) { ComputeInstanceLayout(InstanceLayoutKind.TypeOnly); } return _instanceFieldAlignment; } } /// <summary> /// The number of bytes required when allocating this type on this GC heap /// </summary> public LayoutInt InstanceByteCount { get { return LayoutInt.AlignUp(InstanceByteCountUnaligned, InstanceByteAlignment); } } /// <summary> /// The number of bytes used by the instance fields of this type and its parent types without padding at the end for alignment/gc. /// </summary> public LayoutInt InstanceByteCountUnaligned { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedInstanceTypeLayout)) { ComputeInstanceLayout(InstanceLayoutKind.TypeOnly); } return _instanceByteCountUnaligned; } } /// <summary> /// The alignment required for instances of this type on the GC heap /// </summary> public LayoutInt InstanceByteAlignment { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedInstanceTypeLayout)) { ComputeInstanceLayout(InstanceLayoutKind.TypeOnly); } return _instanceByteAlignment; } } /// <summary> /// How many bytes must be allocated to represent the non GC visible static fields of this type. /// </summary> public LayoutInt NonGCStaticFieldSize { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.NonGcStatics.Size; } } /// <summary> /// What is the alignment required for allocating the non GC visible static fields of this type. /// </summary> public LayoutInt NonGCStaticFieldAlignment { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.NonGcStatics.LargestAlignment; } } /// <summary> /// How many bytes must be allocated to represent the GC visible static fields of this type. /// </summary> public LayoutInt GCStaticFieldSize { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.GcStatics.Size; } } /// <summary> /// What is the alignment required for allocating the GC visible static fields of this type. /// </summary> public LayoutInt GCStaticFieldAlignment { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.GcStatics.LargestAlignment; } } /// <summary> /// How many bytes must be allocated to represent the (potentially GC visible) thread static /// fields of this type. /// </summary> public LayoutInt ThreadStaticFieldSize { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadStatics.Size; } } /// <summary> /// What is the alignment required for allocating the (potentially GC visible) thread static /// fields of this type. /// </summary> public LayoutInt ThreadStaticFieldAlignment { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticRegionLayout)) { ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizes); } return _staticBlockInfo == null ? LayoutInt.Zero : _staticBlockInfo.ThreadStatics.LargestAlignment; } } /// <summary> /// Gets a value indicating whether the fields of the type satisfy the Homogeneous Float Aggregate classification. /// </summary> public bool IsHfa { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedValueTypeShapeCharacteristics)) { ComputeValueTypeShapeCharacteristics(); } return (_valueTypeShapeCharacteristics & ValueTypeShapeCharacteristics.HomogenousFloatAggregate) != 0; } } /// <summary> /// Get the Homogeneous Float Aggregate element type if this is a HFA type (<see cref="IsHfa"/> is true). /// </summary> public DefType HfaElementType { get { // We are not caching this because this is rare and not worth wasting space in DefType. return this.Context.GetLayoutAlgorithmForType(this).ComputeHomogeneousFloatAggregateElementType(this); } } /// <summary> /// Gets a value indicating whether this is a byref-like type /// (a <code>TypedReference</code>, <code>Span&lt;T&gt;</code>, etc.). /// </summary> public bool IsByRefLike { get { if (!_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedIsByRefLike)) { ComputeIsByRefLike(); } return _fieldLayoutFlags.HasFlags(FieldLayoutFlags.IsByRefLike); } } private void ComputeValueTypeShapeCharacteristics() { _valueTypeShapeCharacteristics = this.Context.GetLayoutAlgorithmForType(this).ComputeValueTypeShapeCharacteristics(this); _fieldLayoutFlags.AddFlags(FieldLayoutFlags.ComputedValueTypeShapeCharacteristics); } public void ComputeInstanceLayout(InstanceLayoutKind layoutKind) { if (_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedInstanceTypeFieldsLayout | FieldLayoutFlags.ComputedInstanceTypeLayout)) return; var computedLayout = this.Context.GetLayoutAlgorithmForType(this).ComputeInstanceLayout(this, layoutKind); _instanceFieldSize = computedLayout.FieldSize; _instanceFieldAlignment = computedLayout.FieldAlignment; _instanceByteCountUnaligned = computedLayout.ByteCountUnaligned; _instanceByteAlignment = computedLayout.ByteCountAlignment; if (computedLayout.Offsets != null) { foreach (var fieldAndOffset in computedLayout.Offsets) { Debug.Assert(fieldAndOffset.Field.OwningType == this); fieldAndOffset.Field.InitializeOffset(fieldAndOffset.Offset); } _fieldLayoutFlags.AddFlags(FieldLayoutFlags.ComputedInstanceTypeFieldsLayout); } _fieldLayoutFlags.AddFlags(FieldLayoutFlags.ComputedInstanceTypeLayout); } public void ComputeStaticFieldLayout(StaticLayoutKind layoutKind) { if (_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedStaticFieldsLayout | FieldLayoutFlags.ComputedStaticRegionLayout)) return; var computedStaticLayout = this.Context.GetLayoutAlgorithmForType(this).ComputeStaticFieldLayout(this, layoutKind); if ((computedStaticLayout.NonGcStatics.Size != LayoutInt.Zero) || (computedStaticLayout.GcStatics.Size != LayoutInt.Zero) || (computedStaticLayout.ThreadStatics.Size != LayoutInt.Zero)) { var staticBlockInfo = new StaticBlockInfo { NonGcStatics = computedStaticLayout.NonGcStatics, GcStatics = computedStaticLayout.GcStatics, ThreadStatics = computedStaticLayout.ThreadStatics }; _staticBlockInfo = staticBlockInfo; } if (computedStaticLayout.Offsets != null) { foreach (var fieldAndOffset in computedStaticLayout.Offsets) { Debug.Assert(fieldAndOffset.Field.OwningType == this); fieldAndOffset.Field.InitializeOffset(fieldAndOffset.Offset); } _fieldLayoutFlags.AddFlags(FieldLayoutFlags.ComputedStaticFieldsLayout); } _fieldLayoutFlags.AddFlags(FieldLayoutFlags.ComputedStaticRegionLayout); } public void ComputeTypeContainsGCPointers() { if (_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedContainsGCPointers)) return; int flagsToAdd = FieldLayoutFlags.ComputedContainsGCPointers; if (!IsValueType && HasBaseType && BaseType.ContainsGCPointers) { _fieldLayoutFlags.AddFlags(flagsToAdd | FieldLayoutFlags.ContainsGCPointers); return; } if (this.Context.GetLayoutAlgorithmForType(this).ComputeContainsGCPointers(this)) { flagsToAdd |= FieldLayoutFlags.ContainsGCPointers; } _fieldLayoutFlags.AddFlags(flagsToAdd); } public void ComputeIsByRefLike() { if (_fieldLayoutFlags.HasFlags(FieldLayoutFlags.ComputedIsByRefLike)) return; int flagsToAdd = FieldLayoutFlags.ComputedIsByRefLike; if (this.Context.GetLayoutAlgorithmForType(this).ComputeIsByRefLike(this)) { flagsToAdd |= FieldLayoutFlags.IsByRefLike; } _fieldLayoutFlags.AddFlags(flagsToAdd); } } }
// 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.Diagnostics; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal class CompiledXpathExpr : XPathExpression { private Query _query; private string _expr; private bool _needContext; internal CompiledXpathExpr(Query query, string expression, bool needContext) { _query = query; _expr = expression; _needContext = needContext; } internal Query QueryTree { get { if (_needContext) { throw XPathException.Create(SR.Xp_NoContext); } return _query; } } public override string Expression { get { return _expr; } } public virtual void CheckErrors() { Debug.Assert(_query != null, "In case of error in XPath we create ErrorXPathExpression"); } public override void AddSort(object expr, IComparer comparer) { // sort makes sense only when we are dealing with a query that // returns a nodeset. Query evalExpr; string query = expr as string; if (query != null) { evalExpr = new QueryBuilder().Build(query, out _needContext); // this will throw if expr is invalid } else { CompiledXpathExpr xpathExpr = expr as CompiledXpathExpr; if (xpathExpr != null) { evalExpr = xpathExpr.QueryTree; } else { throw XPathException.Create(SR.Xp_BadQueryObject); } } SortQuery sortQuery = _query as SortQuery; if (sortQuery == null) { _query = sortQuery = new SortQuery(_query); } sortQuery.AddSort(evalExpr, comparer); } public override void AddSort(object expr, XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType) { AddSort(expr, new XPathComparerHelper(order, caseOrder, lang, dataType)); } public override XPathExpression Clone() { return new CompiledXpathExpr(Query.Clone(_query), _expr, _needContext); } public override void SetContext(XmlNamespaceManager nsManager) { SetContext((IXmlNamespaceResolver)nsManager); } public override void SetContext(IXmlNamespaceResolver nsResolver) { XsltContext xsltContext = nsResolver as XsltContext; if (xsltContext == null) { if (nsResolver == null) { nsResolver = new XmlNamespaceManager(new NameTable()); } xsltContext = new UndefinedXsltContext(nsResolver); } _query.SetXsltContext(xsltContext); _needContext = false; } public override XPathResultType ReturnType { get { return _query.StaticType; } } private class UndefinedXsltContext : XsltContext { private IXmlNamespaceResolver _nsResolver; public UndefinedXsltContext(IXmlNamespaceResolver nsResolver) : base(/*dummy*/false) { _nsResolver = nsResolver; } //----- Namespace support ----- public override string DefaultNamespace { get { return string.Empty; } } public override string LookupNamespace(string prefix) { Debug.Assert(prefix != null); if (prefix.Length == 0) { return string.Empty; } string ns = _nsResolver.LookupNamespace(prefix); if (ns == null) { throw XPathException.Create(SR.XmlUndefinedAlias, prefix); } return ns; } //----- XsltContext support ----- public override IXsltContextVariable ResolveVariable(string prefix, string name) { throw XPathException.Create(SR.Xp_UndefinedXsltContext); } public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes) { throw XPathException.Create(SR.Xp_UndefinedXsltContext); } public override bool Whitespace { get { return false; } } public override bool PreserveWhitespace(XPathNavigator node) { return false; } public override int CompareDocument(string baseUri, string nextbaseUri) { return string.CompareOrdinal(baseUri, nextbaseUri); } } } internal sealed class XPathComparerHelper : IComparer { private XmlSortOrder _order; private XmlCaseOrder _caseOrder; private CultureInfo _cinfo; private XmlDataType _dataType; public XPathComparerHelper(XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType) { if (lang == null) { _cinfo = CultureInfo.CurrentCulture; } else { try { _cinfo = new CultureInfo(lang); } catch (System.ArgumentException) { throw; // Throwing an XsltException would be a breaking change } } if (order == XmlSortOrder.Descending) { if (caseOrder == XmlCaseOrder.LowerFirst) { caseOrder = XmlCaseOrder.UpperFirst; } else if (caseOrder == XmlCaseOrder.UpperFirst) { caseOrder = XmlCaseOrder.LowerFirst; } } _order = order; _caseOrder = caseOrder; _dataType = dataType; } public int Compare(object x, object y) { switch (_dataType) { case XmlDataType.Text: string s1 = Convert.ToString(x, _cinfo); string s2 = Convert.ToString(y, _cinfo); int result = _cinfo.CompareInfo.Compare(s1, s2, _caseOrder != XmlCaseOrder.None ? CompareOptions.IgnoreCase : CompareOptions.None); if (result != 0 || _caseOrder == XmlCaseOrder.None) return (_order == XmlSortOrder.Ascending) ? result : -result; // If we came this far, it means that strings s1 and s2 are // equal to each other when case is ignored. Now it's time to check // and see if they differ in case only and take into account the user // requested case order for sorting purposes. result = _cinfo.CompareInfo.Compare(s1, s2); return (_caseOrder == XmlCaseOrder.LowerFirst) ? result : -result; case XmlDataType.Number: double r1 = XmlConvert.ToXPathDouble(x); double r2 = XmlConvert.ToXPathDouble(y); result = r1.CompareTo(r2); return (_order == XmlSortOrder.Ascending) ? result : -result; default: // dataType doesn't support any other value throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Compare () } // class XPathComparerHelper }
using System; using System.Threading; using System.Threading.Tasks; using EasyNetQ.Interception; using EasyNetQ.Internals; using EasyNetQ.Persistent; using EasyNetQ.Topology; namespace EasyNetQ; /// <summary> /// Represents a result of a pull /// </summary> public interface IPullResult : IDisposable { /// <summary> /// True if a message is available /// </summary> public bool IsAvailable { get; } /// <summary> /// Returns remained messages count if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public ulong MessagesCount { get; } /// <summary> /// Returns received info if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public MessageReceivedInfo ReceivedInfo { get; } } /// <summary> /// Represents a result of a message pull /// </summary> public readonly struct PullResult : IPullResult { private readonly MessageReceivedInfo receivedInfo; private readonly MessageProperties properties; private readonly ReadOnlyMemory<byte> body; private readonly ulong messagesCount; private readonly IDisposable disposable; /// <summary> /// Represents a result when no message is available /// </summary> public static PullResult NotAvailable { get; } = new(false, 0, null, null, null, null); /// <summary> /// Represents a result when a message is available /// </summary> /// <returns></returns> public static PullResult Available( ulong messagesCount, MessageReceivedInfo receivedInfo, MessageProperties properties, in ReadOnlyMemory<byte> body, IDisposable disposable ) { return new PullResult(true, messagesCount, receivedInfo, properties, body, disposable); } private PullResult( bool isAvailable, ulong messagesCount, MessageReceivedInfo receivedInfo, MessageProperties properties, in ReadOnlyMemory<byte> body, IDisposable disposable ) { IsAvailable = isAvailable; this.messagesCount = messagesCount; this.receivedInfo = receivedInfo; this.properties = properties; this.body = body; this.disposable = disposable; } /// <summary> /// True if a message is available /// </summary> public bool IsAvailable { get; } /// <summary> /// Returns remained messages count if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public ulong MessagesCount { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return messagesCount; } } /// <summary> /// Returns received info if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public MessageReceivedInfo ReceivedInfo { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return receivedInfo; } } /// <summary> /// Returns properties if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public MessageProperties Properties { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return properties; } } /// <summary> /// Returns body info if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public ReadOnlyMemory<byte> Body { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return body; } } /// <inheritdoc /> public void Dispose() { disposable?.Dispose(); } } /// <summary> /// Represents a result of a message pull /// </summary> public readonly struct PullResult<T> : IPullResult { private readonly MessageReceivedInfo receivedInfo; private readonly IMessage<T> message; private readonly ulong messagesCount; /// <summary> /// Represents a result when no message is available /// </summary> public static PullResult<T> NotAvailable { get; } = new(false, 0, null, null); /// <summary> /// Represents a result when a message is available /// </summary> /// <returns></returns> public static PullResult<T> Available( ulong messagesCount, MessageReceivedInfo receivedInfo, IMessage<T> message ) { return new PullResult<T>(true, messagesCount, receivedInfo, message); } private PullResult( bool isAvailable, ulong messagesCount, MessageReceivedInfo receivedInfo, IMessage<T> message ) { IsAvailable = isAvailable; this.messagesCount = messagesCount; this.receivedInfo = receivedInfo; this.message = message; } /// <summary> /// True if a message is available /// </summary> public bool IsAvailable { get; } /// <summary> /// Returns remained messages count if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public ulong MessagesCount { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return messagesCount; } } /// <summary> /// Returns received info if the message is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public MessageReceivedInfo ReceivedInfo { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return receivedInfo; } } /// <summary> /// Returns message if it is available /// </summary> /// <exception cref="InvalidOperationException"></exception> public IMessage<T> Message { get { if (!IsAvailable) throw new InvalidOperationException("No message is available"); return message; } } /// <inheritdoc /> public void Dispose() { } } /// <summary> /// Allows to receive messages by pulling them one by one /// </summary> public interface IPullingConsumer<TPullResult> : IDisposable where TPullResult : IPullResult { /// <summary> /// Receives a single message /// </summary> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> Task<TPullResult> PullAsync(CancellationToken cancellationToken = default); /// <summary> /// Acknowledges one or more messages /// </summary> /// <param name="deliveryTag"></param> /// <param name="multiple"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task AckAsync(ulong deliveryTag, bool multiple, CancellationToken cancellationToken = default); /// <summary> /// Rejects one or more messages /// </summary> /// <param name="deliveryTag"></param> /// <param name="multiple"></param> /// <param name="requeue"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task RejectAsync(ulong deliveryTag, bool multiple, bool requeue, CancellationToken cancellationToken = default); } /// <summary> /// Represent pulling consumer options /// </summary> public readonly struct PullingConsumerOptions { /// <summary> /// True if auto ack is enabled for the consumer /// </summary> public bool AutoAck { get; } /// <summary> /// Operations timeout /// </summary> public TimeSpan Timeout { get; } /// <summary> /// Creates PullingConsumerOptions /// </summary> /// <param name="autoAck">The autoAck</param> /// <param name="timeout">The timeout</param> public PullingConsumerOptions(bool autoAck, TimeSpan timeout) { AutoAck = autoAck; Timeout = timeout; } } /// <inheritdoc /> public class PullingConsumer : IPullingConsumer<PullResult> { private readonly IPersistentChannel channel; private readonly IProduceConsumeInterceptor interceptor; private readonly PullingConsumerOptions options; private readonly Queue queue; /// <summary> /// Creates PullingConsumer /// </summary> /// <param name="options">The options</param> /// <param name="queue">The queue</param> /// <param name="channel">The channel</param> /// <param name="interceptor">The produce-consumer interceptor</param> public PullingConsumer( in PullingConsumerOptions options, in Queue queue, IPersistentChannel channel, IProduceConsumeInterceptor interceptor ) { this.queue = queue; this.options = options; this.channel = channel; this.interceptor = interceptor; } /// <inheritdoc /> public async Task<PullResult> PullAsync(CancellationToken cancellationToken = default) { using var cts = cancellationToken.WithTimeout(options.Timeout); var basicGetResult = await channel.InvokeChannelActionAsync( x => x.BasicGet(queue.Name, options.AutoAck), cts.Token ).ConfigureAwait(false); if (basicGetResult == null) return PullResult.NotAvailable; var messagesCount = basicGetResult.MessageCount; var messageProperties = new MessageProperties(); messageProperties.CopyFrom(basicGetResult.BasicProperties); var messageReceivedInfo = new MessageReceivedInfo( "", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, queue.Name ); var message = new ConsumedMessage(messageReceivedInfo, messageProperties, basicGetResult.Body); var interceptedMessage = interceptor.OnConsume(message); return PullResult.Available( messagesCount, interceptedMessage.ReceivedInfo, interceptedMessage.Properties, interceptedMessage.Body, null ); } /// <inheritdoc /> public async Task AckAsync(ulong deliveryTag, bool multiple, CancellationToken cancellationToken = default) { if (options.AutoAck) throw new InvalidOperationException("Cannot ack in auto ack mode"); using var cts = cancellationToken.WithTimeout(options.Timeout); await channel.InvokeChannelActionAsync( x => x.BasicAck(deliveryTag, multiple), cts.Token ).ConfigureAwait(false); } /// <inheritdoc /> public async Task RejectAsync( ulong deliveryTag, bool multiple, bool requeue, CancellationToken cancellationToken = default ) { if (options.AutoAck) throw new InvalidOperationException("Cannot reject in auto ack mode"); using var cts = cancellationToken.WithTimeout(options.Timeout); await channel.InvokeChannelActionAsync( x => x.BasicNack(deliveryTag, multiple, requeue), cts.Token ).ConfigureAwait(false); } /// <inheritdoc /> public void Dispose() { channel.Dispose(); } } /// <inheritdoc /> public class PullingConsumer<T> : IPullingConsumer<PullResult<T>> { private readonly IPullingConsumer<PullResult> consumer; private readonly IMessageSerializationStrategy messageSerializationStrategy; /// <summary> /// Creates PullingConsumer /// </summary> public PullingConsumer( IPullingConsumer<PullResult> consumer, IMessageSerializationStrategy messageSerializationStrategy ) { this.consumer = consumer; this.messageSerializationStrategy = messageSerializationStrategy; } /// <inheritdoc /> public async Task<PullResult<T>> PullAsync(CancellationToken cancellationToken = default) { var pullResult = await consumer.PullAsync(cancellationToken).ConfigureAwait(false); if (!pullResult.IsAvailable) { pullResult.Dispose(); return PullResult<T>.NotAvailable; } var message = messageSerializationStrategy.DeserializeMessage(pullResult.Properties, pullResult.Body); if (typeof(T).IsAssignableFrom(message.MessageType)) return PullResult<T>.Available( pullResult.MessagesCount, pullResult.ReceivedInfo, new Message<T>((T)message.GetBody(), message.Properties) ); throw new EasyNetQException( $"Incorrect message type returned. Expected {typeof(T).Name}, but was {message.MessageType.Name}" ); } /// <inheritdoc /> public Task AckAsync(ulong deliveryTag, bool multiple, CancellationToken cancellationToken = default) { return consumer.AckAsync(deliveryTag, multiple, cancellationToken); } /// <inheritdoc /> public Task RejectAsync( ulong deliveryTag, bool multiple, bool requeue, CancellationToken cancellationToken = default ) { return consumer.RejectAsync(deliveryTag, multiple, requeue, cancellationToken); } /// <inheritdoc /> public void Dispose() { consumer.Dispose(); } }
// 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.Linq; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Analyzer { abstract class InterpreterScope { public readonly InterpreterScope OuterScope; public readonly List<InterpreterScope> Children = new List<InterpreterScope>(); public bool ContainsImportStar; private readonly AnalysisValue _av; private readonly Node _node; private readonly AnalysisDictionary<Node, InterpreterScope> _nodeScopes; private readonly AnalysisDictionary<Node, NodeValue> _nodeValues; private readonly AnalysisDictionary<string, VariableDef> _variables; private readonly AnalysisDictionary<string, HashSet<VariableDef>> _linkedVariables; public InterpreterScope(AnalysisValue av, Node ast, InterpreterScope outerScope) { _av = av; _node = ast; OuterScope = outerScope; _nodeScopes = new AnalysisDictionary<Node, InterpreterScope>(); _nodeValues = new AnalysisDictionary<Node, NodeValue>(); _variables = new AnalysisDictionary<string, VariableDef>(); _linkedVariables = new AnalysisDictionary<string, HashSet<VariableDef>>(); } public InterpreterScope(AnalysisValue av, InterpreterScope outerScope) : this(av, null, outerScope) { } protected InterpreterScope(AnalysisValue av, InterpreterScope cloned, bool isCloned) { Debug.Assert(isCloned); _av = av; Children.AddRange(cloned.Children); _nodeScopes = cloned._nodeScopes; _nodeValues = cloned._nodeValues; _variables = cloned._variables; _linkedVariables = cloned._linkedVariables; } public InterpreterScope GlobalScope { get { for (var scope = this; scope != null; scope = scope.OuterScope) { if (scope.OuterScope == null) { return scope; } } return null; } } public IEnumerable<InterpreterScope> EnumerateTowardsGlobal { get { for (var scope = this; scope != null; scope = scope.OuterScope) { yield return scope; } } } public IEnumerable<InterpreterScope> EnumerateFromGlobal { get { return EnumerateTowardsGlobal.Reverse(); } } /// <summary> /// Gets the index in the file/buffer that the scope actually starts on. This is the index where the colon /// is on for the start of the body if we're a function or class definition. /// </summary> public virtual int GetBodyStart(PythonAst ast) { return GetStart(ast); } /// <summary> /// Gets the index in the file/buffer that this scope starts at. This is the index which includes /// the definition it's self (e.g. def fob(...) or class fob(...)). /// </summary> public virtual int GetStart(PythonAst ast) { if (_node == null) { return 1; } return _node.GetStart(ast).Index; } /// <summary> /// Gets the index in the file/buffer that this scope ends at. /// </summary> public virtual int GetStop(PythonAst ast) { if (_node == null) { return int.MaxValue; } return _node.GetEnd(ast).Index; } public abstract string Name { get; } public Node Node { get { return _node; } } internal IEnumerable<KeyValuePair<string, VariableDef>> AllVariables { get { return _variables; } } internal IEnumerable<KeyValuePair<Node, InterpreterScope>> AllNodeScopes { get { return _nodeScopes; } } internal bool ContainsVariable(string name) { return _variables.ContainsKey(name); } internal VariableDef GetVariable(string name) { return _variables[name]; } internal bool TryGetVariable(string name, out VariableDef value) { return _variables.TryGetValue(name, out value); } internal int VariableCount { get { return _variables.Count; } } /// <summary> /// Assigns a variable in the given scope, creating the variable if necessary, and performing /// any scope specific behavior such as propagating to outer scopes (is instance), updating /// __metaclass__ (class scopes), or enqueueing dependent readers (modules). /// /// Returns true if a new type has been signed to the variable, false if the variable /// is left unchanged. /// </summary> public virtual bool AssignVariable(string name, Node location, AnalysisUnit unit, IAnalysisSet values) { var vars = CreateVariable(location, unit, name, false); return AssignVariableWorker(location, unit, values, vars); } /// <summary> /// Handles the base assignment case for assign to a variable, minus variable creation. /// </summary> protected static bool AssignVariableWorker(Node location, AnalysisUnit unit, IAnalysisSet values, VariableDef vars) { vars.AddAssignment(location, unit); vars.MakeUnionStrongerIfMoreThan(unit.ProjectState.Limits.AssignedTypes, values); return vars.AddTypes(unit, values); } public VariableDef AddLocatedVariable(string name, Node location, AnalysisUnit unit, ParameterKind paramKind = ParameterKind.Normal) { VariableDef value; if (!TryGetVariable(name, out value)) { VariableDef def; switch (paramKind) { case ParameterKind.List: def = new ListParameterVariableDef(unit, location); break; case ParameterKind.Dictionary: def = new DictParameterVariableDef(unit, location); break; default: def = new LocatedVariableDef(unit.DeclaringModule.ProjectEntry, location); break; } return AddVariable(name, def); } else if (!(value is LocatedVariableDef)) { VariableDef def; switch (paramKind) { case ParameterKind.List: def = new ListParameterVariableDef(unit, location, value); break; case ParameterKind.Dictionary: def = new DictParameterVariableDef(unit, location, value); break; default: def = new LocatedVariableDef(unit.DeclaringModule.ProjectEntry, location, value); break; } return AddVariable(name, def); } else { ((LocatedVariableDef)value).Node = location; ((LocatedVariableDef)value).DeclaringVersion = unit.ProjectEntry.AnalysisVersion; } return value; } public void SetVariable(Node node, AnalysisUnit unit, string name, IAnalysisSet value, bool addRef = true) { var variable = CreateVariable(node, unit, name, false); variable.AddTypes(unit, value); if (addRef) { variable.AddAssignment(node, unit); } } public virtual VariableDef GetVariable(Node node, AnalysisUnit unit, string name, bool addRef = true) { VariableDef res; if (!_variables.TryGetValue(name, out res)) { return null; } if (addRef) { res.AddReference(node, unit); } return res; } public virtual IEnumerable<KeyValuePair<string, VariableDef>> GetAllMergedVariables() { return _variables; } public virtual IEnumerable<VariableDef> GetMergedVariables(string name) { VariableDef res; if (_variables.TryGetValue(name, out res) && res != null) { yield return res; } } public virtual IAnalysisSet GetMergedVariableTypes(string name) { var res = AnalysisSet.Empty; foreach (var val in GetMergedVariables(name)) { res = res.Union(val.Types); } return res; } public virtual IEnumerable<AnalysisValue> GetMergedAnalysisValues() { yield return AnalysisValue; } public virtual VariableDef CreateVariable(Node node, AnalysisUnit unit, string name, bool addRef = true) { var res = GetVariable(node, unit, name, addRef); if (res == null) { res = AddVariable(name); if (addRef) { res.AddReference(node, unit); } } return res; } public VariableDef CreateEphemeralVariable(Node node, AnalysisUnit unit, string name, bool addRef = true) { var res = GetVariable(node, unit, name, addRef); if (res == null) { res = AddVariable(name, new EphemeralVariableDef()); if (addRef) { res.AddReference(node, unit); } } return res; } public virtual VariableDef AddVariable(string name, VariableDef variable = null) { return _variables[name] = variable ?? new VariableDef(); } internal virtual bool RemoveVariable(string name) { return _variables.Remove(name); } internal bool RemoveVariable(string name, out VariableDef value) { return _variables.TryGetValue(name, out value) && _variables.Remove(name); } internal virtual void ClearVariables() { _variables.Clear(); } public virtual InterpreterScope AddNodeScope(Node node, InterpreterScope scope) { return _nodeScopes[node] = scope; } internal virtual bool RemoveNodeScope(Node node) { return _nodeScopes.Remove(node); } internal virtual void ClearNodeScopes() { _nodeScopes.Clear(); } public virtual IAnalysisSet AddNodeValue(Node node, NodeValueKind kind, IAnalysisSet variable) { NodeValue next; _nodeValues.TryGetValue(node, out next); #if DEBUG var tmp = next; while (tmp != null) { Debug.Assert(tmp.Kind != kind); tmp = tmp.Next; } #endif _nodeValues[node] = new NodeValue(kind, variable, next); return variable; } internal virtual bool RemoveNodeValue(Node node) { return _nodeValues.Remove(node); } internal virtual void ClearNodeValues() { _nodeValues.Clear(); } public virtual bool VisibleToChildren { get { return true; } } public AnalysisValue AnalysisValue { get { return _av; } } public void ClearLinkedVariables() { _linkedVariables.Clear(); } internal bool AddLinkedVariable(string name, VariableDef variable) { HashSet<VariableDef> links; if (!_linkedVariables.TryGetValue(name, out links) || links == null) { _linkedVariables[name] = links = new HashSet<VariableDef>(); } lock (links) { return links.Add(variable); } } internal IEnumerable<VariableDef> GetLinkedVariables(string name) { HashSet<VariableDef> links; _linkedVariables.TryGetValue(name, out links); if (links == null) { return Enumerable.Empty<VariableDef>(); } return links.AsLockedEnumerable(); } internal void AddReferenceToLinkedVariables(Node node, AnalysisUnit unit, string name) { foreach (var linkedVar in GetLinkedVariables(name)) { linkedVar.AddReference(node, unit); } } internal bool TryGetNodeValue(Node node, NodeValueKind kind, out IAnalysisSet variable) { foreach (var s in EnumerateTowardsGlobal) { NodeValue value; if (s._nodeValues.TryGetValue(node, out value)) { while (value != null) { if (value.Kind == kind) { variable = value.Variable; return true; } value = value.Next; } } } variable = null; return false; } internal bool TryGetNodeScope(Node node, out InterpreterScope scope) { foreach (var s in EnumerateTowardsGlobal) { if (s._nodeScopes.TryGetValue(node, out scope)) { return true; } } scope = null; return false; } /// <summary> /// Cached node variables so that we don't continually create new entries for basic nodes such /// as sequences, lambdas, etc... /// </summary> public IAnalysisSet GetOrMakeNodeValue(Node node, NodeValueKind kind, Func<Node, IAnalysisSet> maker) { IAnalysisSet result; if (!TryGetNodeValue(node, kind, out result)) { result = maker(node); AddNodeValue(node, kind, result); } return result; } } class NodeValue { public readonly IAnalysisSet Variable; public readonly NodeValueKind Kind; public NodeValue Next; public NodeValue(NodeValueKind kind, IAnalysisSet variable, NodeValue value) { Kind = kind; Variable = variable; Next = value; } } enum NodeValueKind { None, Set, DictLiteral, ListComprehension, LambdaFunction, Sequence, Range, ListOfString, StrDict, Iterator, Super, PartialFunction, Wraps, SpecializedInstance, Dictionary, } }