context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Drawing; using System.Reflection; using System.Windows.Forms; namespace MDXInfo.Util.Script { // GListBox class public class IntellisenseListBox : ListBox { private ImageList imageList; public ImageList ImageList { get { return imageList; } set { imageList = value; } } public IntellisenseListBox() { // Set owner draw mode this.DrawMode = DrawMode.OwnerDrawFixed; this.ItemHeight = 16; this.Font = new Font(FontFamily.GenericSansSerif, 7f); this.Click += new EventHandler(IntellisenseListBox_Click); this.DoubleClick += new EventHandler(IntellisenseListBox_DoubleClick); this.Cursor = Cursors.Default; this.BorderStyle = BorderStyle.FixedSingle; } void IntellisenseListBox_DoubleClick(object sender, EventArgs e) { ((ScriptEditorControl)Parent).ConfirmIntellisenseBox(); } void IntellisenseListBox_Click(object sender, EventArgs e) { Parent.Focus(); } public void Populate(Type type) { this.Items.Clear(); ArrayList typeItems = new ArrayList(); MemberInfo[] memberInfo = type.GetMembers(); for (int i = 0; i < memberInfo.Length; i++) { if (memberInfo[i].ReflectedType.IsVisible & !memberInfo[i].ReflectedType.IsSpecialName) { if (memberInfo[i].MemberType == MemberTypes.Method) { // filter out reflected property accessor methods if (!memberInfo[i].Name.StartsWith("get_") && !memberInfo[i].Name.StartsWith("set_") && !memberInfo[i].Name.StartsWith("add_") && !memberInfo[i].Name.StartsWith("remove_") && !memberInfo[i].Name.StartsWith("op_")) { string methodParameters = "("; ParameterInfo[] parameterInfo = ((MethodInfo)memberInfo[i]).GetParameters(); for (int p = 0; p < parameterInfo.Length; p++) { methodParameters += parameterInfo[p].ParameterType.Name + " " + parameterInfo[p].Name; if (p < parameterInfo.Length - 1) { methodParameters += ", "; } } methodParameters += ")"; typeItems.Add(new IntellisenseListBoxItem(memberInfo[i].Name + methodParameters, memberInfo[i].Name + (parameterInfo.Length == 0 ? "()" : "("), 2)); } } else if (memberInfo[i].MemberType == MemberTypes.Property) { typeItems.Add(new IntellisenseListBoxItem(memberInfo[i].Name, memberInfo[i].Name, 3)); } else if (memberInfo[i].MemberType == MemberTypes.Event) { typeItems.Add(new IntellisenseListBoxItem(memberInfo[i].Name, memberInfo[i].Name, 4)); } } } typeItems.Sort(); this.Items.AddRange(typeItems.ToArray()); } protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e) { e.DrawBackground(); e.DrawFocusRectangle(); IntellisenseListBoxItem item; Rectangle bounds = e.Bounds; try { Size imageSize = imageList.ImageSize; item = (IntellisenseListBoxItem)Items[e.Index]; if (item.ImageIndex != -1) { imageList.Draw(e.Graphics, bounds.Left, bounds.Top, item.ImageIndex); e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), bounds.Left + imageSize.Width + 2, bounds.Top); } else { e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); } } catch { if (e.Index != -1) { e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); } else { e.Graphics.DrawString(Text, e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); } } base.OnDrawItem(e); } }//End of GListBox class // GListBoxItem class public class IntellisenseListBoxItem : IComparable { public int CompareTo(object obj) { if (obj != null) { if (obj is IntellisenseListBoxItem) { IntellisenseListBoxItem item = (IntellisenseListBoxItem)obj; return (this.Text.CompareTo(item.Text)); } else { return 0; } } return 0; } private string text; private string tag = string.Empty; public string Tag { get { if (tag != string.Empty) { return tag; } else { return text; } } set { tag = value; } } private int imageIndex; // properties public string Text { get { return text; } set { text = value; } } public int ImageIndex { get { return imageIndex; } set { imageIndex = value; } } //constructor public IntellisenseListBoxItem(string text, int index) { this.text = text; imageIndex = index; } //constructor public IntellisenseListBoxItem(string text, string tag, int index) { this.tag = tag; this.text = text; imageIndex = index; } public IntellisenseListBoxItem(string text) : this(text, -1) { } public IntellisenseListBoxItem() : this("Unnamed item") { } public override string ToString() { return Tag; } }//End of GListBoxItem class }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using Aspose.HTML.Live.Demos.UI.Config; using Aspose.HTML.Live.Demos.UI.Controllers; namespace Aspose.HTML.Live.Demos.UI.Models { public class ViewModel { public int MaximumUploadFiles { get; set; } /// <summary> /// Name of the product (e.g., words) /// </summary> public string Product { get; set; } public BaseController Controller; /// <summary> /// Product + AppName, e.g. wordsMerger /// </summary> public string ProductAppName { get; set; } private AsposeHTMLContext _atcContext; public AsposeHTMLContext AsposePageContext { get { if (_atcContext == null) _atcContext = new AsposeHTMLContext(HttpContext.Current); return _atcContext; } } private Dictionary<string, string> _resources; public Dictionary<string, string> Resources { get { if (_resources == null) _resources = AsposePageContext.Resources; return _resources; } set { _resources = value; } } public string UIBasePath => Configuration.AsposeHTMLLiveDemosPath; public string PageProductTitle => Resources["Aspose" + TitleCase(Product)]; /// <summary> /// The name of the app (e.g., Conversion, Merger) /// </summary> public string AppName { get; set; } /// <summary> /// The full address of the application without query string (e.g., https://products.aspose.app/words/conversion) /// </summary> public string AppURL { get; set; } /// <summary> /// File extension without dot received by "fileformat" value in RouteData (e.g. docx) /// </summary> public string Extension { get; set; } /// <summary> /// File extension without dot received by "fileformat" value in RouteData (e.g. docx) /// </summary> public string Extension2 { get; set; } /// <summary> /// Redirect to main app, if there is no ExtensionInfoModel for auto generated models /// </summary> public bool RedirectToMainApp { get; set; } /// <summary> /// Name of the partial View of controls (e.g. UnlockControls) /// </summary> public string ControlsView { get; set; } /// <summary> /// Is canonical page opened (/all) /// </summary> public bool IsCanonical; public string AnotherFileText { get; set; } public string UploadButtonText { get; set; } public string ViewerButtonText { get; set; } public bool ShowViewerButton { get; set; } public string SuccessMessage { get; set; } /// <summary> /// List of app features for ul-list. E.g. Resources[app + "LiFeature1"] /// </summary> public List<string> AppFeatures { get; set; } public string Title { get; set; } public string TitleSub { get; set; } public string PageTitle { get => Controller.ViewBag.PageTitle; set => Controller.ViewBag.PageTitle = value; } public string MetaDescription { get => Controller.ViewBag.MetaDescription; set => Controller.ViewBag.MetaDescription = value; } public string MetaKeywords { get => Controller.ViewBag.MetaKeywords; set => Controller.ViewBag.MetaKeywords = value; } /// <summary> /// If the application doesn't need to upload several files (e.g. Viewer, Editor) /// </summary> public bool UploadAndRedirect { get; set; } protected string TitleCase(string value) => new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(value); /// <summary> /// e.g., .doc|.docx|.dot|.dotx|.rtf|.odt|.ott|.txt|.html|.xhtml|.mhtml /// </summary> public string ExtensionsString { get; set; } #region SaveAs private bool _saveAsComponent; public bool SaveAsComponent { get => _saveAsComponent; set { _saveAsComponent = value; Controller.ViewBag.SaveAsComponent = value; if (_saveAsComponent) { var sokey1 = $"{Product}{AppName}SaveAsOptions"; var sokey2 = $"{Product}SaveAsOptions"; if (Resources.ContainsKey(sokey1)) SaveAsOptions = Resources[sokey1].Split(','); else if (Resources.ContainsKey(sokey2)) { SaveAsOptions = Resources[sokey2].Split(','); } var lifeaturekey = Product + "SaveAsLiFeature"; if (AppFeatures != null && Resources.ContainsKey(lifeaturekey)) AppFeatures.Add(Resources[lifeaturekey]); } } } public string SaveAsOptionsList { get { string list = ""; if (SaveAsOptions != null) { foreach (var extensin in SaveAsOptions) { if (list == "") { list = extensin.ToUpper(); } else { list = list + ", " + extensin.ToUpper(); } } } return list; } } /// <summary> /// FileFormats in UpperCase /// </summary> public string[] SaveAsOptions { get; set; } /// <summary> /// Original file format SaveAs option for multiple files uploading /// </summary> public bool SaveAsOriginal { get; set; } #endregion /// <summary> /// The possibility of changing the order of uploaded files. It is actual for Merger App. /// </summary> public bool UseSorting { get; set; } public string DropOrUploadFileLabel { get; set; } #region ViewSections public bool ShowExtensionInfo => ExtensionInfoModel != null; public ExtensionInfoModel ExtensionInfoModel { get; set; } public bool HowTo => HowToModel != null; public HowToModel HowToModel { get; set; } #endregion public string JSOptions => new JSOptions(this).ToString(); public ViewModel(BaseController controller, string app) { Controller = controller; Resources = controller.Resources; AppName = Resources.ContainsKey($"{app}APPName") ? Resources[$"{app}APPName"] : app; Product = controller.Product; var url = controller.Request.Url.AbsoluteUri; AppURL = url.Substring(0, (url.IndexOf("?") > 0 ? url.IndexOf("?") : url.Length)); ProductAppName = Product + app; UploadButtonText = GetFromResources(ProductAppName + "Button", app + "Button"); ViewerButtonText = GetFromResources(app + "Viewer", "ViewDocument"); SuccessMessage = GetFromResources(app + "SuccessMessage"); AnotherFileText = GetFromResources(app + "AnotherFile"); IsCanonical = true; HowToModel = new HowToModel(this); SetTitles(); SetAppFeatures(app); ShowViewerButton = true; SaveAsOriginal = true; SaveAsComponent = false; SetExtensionsString(); } private void SetTitles() { PageTitle = Resources[ProductAppName + "PageTitle"]; MetaDescription = Resources[ProductAppName + "MetaDescription"]; MetaKeywords = ""; Title = Resources[ProductAppName + "Title"]; TitleSub = Resources[ProductAppName + "SubTitle"]; Controller.ViewBag.CanonicalTag = null; } private void SetAppFeatures(string app) { AppFeatures = new List<string>(); var i = 1; while (Resources.ContainsKey($"{ProductAppName}LiFeature{i}")) AppFeatures.Add(Resources[$"{ProductAppName}LiFeature{i++}"]); // Stop other developers to add unnecessary features. if (AppFeatures.Count == 0) { i = 1; while (Resources.ContainsKey($"{app}LiFeature{i}")) { if (!Resources[$"{app}LiFeature{i}"].Contains("Instantly download") || AppFeatures.Count == 0) AppFeatures.Add(Resources[$"{app}LiFeature{i}"]); i++; } } } private string GetFromResources(string key, string defaultKey = null) { if (Resources.ContainsKey(key)) return Resources[key]; if (!string.IsNullOrEmpty(defaultKey) && Resources.ContainsKey(defaultKey)) return Resources[defaultKey]; return ""; } private void SetExtensionsString() { if (!ShowExtensionInfo) { var key1 = $"{Product}{AppName}ValidationExpression"; var key2 = $"{Product}ValidationExpression"; ExtensionsString = Resources.ContainsKey(key1) ? Resources[key1] : Resources[key2]; } else { switch (Extension) { case "doc": case "docx": ExtensionsString = ".docx|.doc"; break; case "html": case "htm": case "mhtml": case "mht": ExtensionsString = ".htm|.html|.mht|.mhtml"; break; default: ExtensionsString = $".{Extension}"; break; } if (AppName == "Comparison" && !string.IsNullOrEmpty(Extension2)) ExtensionsString += $"|.{Extension2}"; } } } }
/* * 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 log4net; using OpenMetaverse; using OpenSim.Framework; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Reflection; namespace OpenSim.Data.MSSQL { /// <summary> /// A MSSQL Interface for the Asset server /// </summary> public class MSSQLAssetData : AssetDataBase { private const string _migrationStore = "AssetStore"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private long m_ticksToEpoch; /// <summary> /// Database manager /// </summary> private MSSQLManager m_database; private string m_connectionString; #region IPlugin Members override public void Dispose() { } /// <summary> /// <para>Initialises asset interface</para> /// </summary> // [Obsolete("Cannot be default-initialized!")] override public void Initialise() { m_log.Info("[MSSQLAssetData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } /// <summary> /// Initialises asset interface /// </summary> /// <para> /// a string instead of file, if someone writes the support /// </para> /// <param name="connectionString">connect string</param> override public void Initialise(string connectionString) { m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks; m_database = new MSSQLManager(connectionString); m_connectionString = connectionString; //New migration to check for DB changes m_database.CheckMigration(_migrationStore); } /// <summary> /// Database provider version. /// </summary> override public string Version { get { return m_database.getVersion(); } } /// <summary> /// The name of this DB provider. /// </summary> override public string Name { get { return "MSSQL Asset storage engine"; } } #endregion #region IAssetDataPlugin Members /// <summary> /// Fetch Asset from m_database /// </summary> /// <param name="assetID">the asset UUID</param> /// <returns></returns> override public AssetBase GetAsset(UUID assetID) { string sql = "SELECT * FROM assets WHERE id = @id"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("id", assetID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { AssetBase asset = new AssetBase( DBGuid.FromDB(reader["id"]), (string)reader["name"], Convert.ToSByte(reader["assetType"]), reader["creatorid"].ToString() ); // Region Main asset.Description = (string)reader["description"]; asset.Local = Convert.ToBoolean(reader["local"]); asset.Temporary = Convert.ToBoolean(reader["temporary"]); asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"])); asset.Data = (byte[])reader["data"]; return asset; } return null; // throw new Exception("No rows to return"); } } } /// <summary> /// Create asset in m_database /// </summary> /// <param name="asset">the asset</param> override public void StoreAsset(AssetBase asset) { string sql = @"IF EXISTS(SELECT * FROM assets WHERE id=@id) UPDATE assets set name = @name, description = @description, assetType = @assetType, local = @local, temporary = @temporary, creatorid = @creatorid, data = @data WHERE id=@id AND asset_flags<>0 ELSE INSERT INTO assets ([id], [name], [description], [assetType], [local], [temporary], [create_time], [access_time], [creatorid], [asset_flags], [data]) VALUES (@id, @name, @description, @assetType, @local, @temporary, @create_time, @access_time, @creatorid, @asset_flags, @data)"; string assetName = asset.Name; if (asset.Name.Length > AssetBase.MAX_ASSET_NAME) { assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME); m_log.WarnFormat( "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Name, asset.ID, asset.Name.Length, assetName.Length); } string assetDescription = asset.Description; if (asset.Description.Length > AssetBase.MAX_ASSET_DESC) { assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC); m_log.WarnFormat( "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Description, asset.ID, asset.Description.Length, assetDescription.Length); } using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand command = new SqlCommand(sql, conn)) { int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000); command.Parameters.Add(m_database.CreateParameter("id", asset.FullID)); command.Parameters.Add(m_database.CreateParameter("name", assetName)); command.Parameters.Add(m_database.CreateParameter("description", assetDescription)); command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type)); command.Parameters.Add(m_database.CreateParameter("local", asset.Local)); command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary)); command.Parameters.Add(m_database.CreateParameter("access_time", now)); command.Parameters.Add(m_database.CreateParameter("create_time", now)); command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags)); command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID)); command.Parameters.Add(m_database.CreateParameter("data", asset.Data)); conn.Open(); try { command.ExecuteNonQuery(); } catch(Exception e) { m_log.Error("[ASSET DB]: Error storing item :" + e.Message); } } } // Commented out since currently unused - this probably should be called in GetAsset() // private void UpdateAccessTime(AssetBase asset) // { // using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id")) // { // int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000); // cmd.Parameters.AddWithValue("@id", asset.FullID.ToString()); // cmd.Parameters.AddWithValue("@access_time", now); // try // { // cmd.ExecuteNonQuery(); // } // catch (Exception e) // { // m_log.Error(e.ToString()); // } // } // } /// <summary> /// Check if the assets exist in the database. /// </summary> /// <param name="uuids">The assets' IDs</param> /// <returns>For each asset: true if it exists, false otherwise</returns> public override bool[] AssetsExist(UUID[] uuids) { if (uuids.Length == 0) return new bool[0]; HashSet<UUID> exist = new HashSet<UUID>(); string ids = "'" + string.Join("','", uuids) + "'"; string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids); using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { UUID id = DBGuid.FromDB(reader["id"]); exist.Add(id); } } } bool[] results = new bool[uuids.Length]; for (int i = 0; i < uuids.Length; i++) results[i] = exist.Contains(uuids[i]); return results; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); string sql = @"WITH OrderedAssets AS ( SELECT id, name, description, assetType, temporary, creatorid, RowNumber = ROW_NUMBER() OVER (ORDER BY id) FROM assets ) SELECT * FROM OrderedAssets WHERE RowNumber BETWEEN @start AND @stop;"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("start", start)); cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { AssetMetadata metadata = new AssetMetadata(); metadata.FullID = DBGuid.FromDB(reader["id"]); metadata.Name = (string)reader["name"]; metadata.Description = (string)reader["description"]; metadata.Type = Convert.ToSByte(reader["assetType"]); metadata.Temporary = Convert.ToBoolean(reader["temporary"]); metadata.CreatorID = (string)reader["creatorid"]; retList.Add(metadata); } } } return retList; } public override bool Delete(string id) { return false; } #endregion } }
/// Refly License /// /// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org /// /// This software is provided 'as-is', without any express or implied warranty. /// In no event will the authors be held liable for any damages arising from /// the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, /// including commercial applications, and to alter it and redistribute it /// freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; /// you must not claim that you wrote the original software. /// If you use this software in a product, an acknowledgment in the product /// documentation would be appreciated but is not required. /// /// 2. Altered source versions must be plainly marked as such, /// and must not be misrepresented as being the original software. /// ///3. This notice may not be removed or altered from any source distribution. using System; namespace Refly.CodeDom.Collections { using Refly.CodeDom; /// <summary> /// A collection of elements of type ITypeDeclaration /// </summary> public class TypeDeclarationCollection: System.Collections.CollectionBase { /// <summary> /// Initializes a new empty instance of the TypeDeclarationCollection class. /// </summary> public TypeDeclarationCollection() { // empty } /// <summary> /// Initializes a new instance of the TypeDeclarationCollection class, containing elements /// copied from an array. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the new TypeDeclarationCollection. /// </param> public TypeDeclarationCollection(ITypeDeclaration[] items) { this.AddRange(items); } /// <summary> /// Initializes a new instance of the TypeDeclarationCollection class, containing elements /// copied from another instance of TypeDeclarationCollection /// </summary> /// <param name="items"> /// The TypeDeclarationCollection whose elements are to be added to the new TypeDeclarationCollection. /// </param> public TypeDeclarationCollection(TypeDeclarationCollection items) { this.AddRange(items); } /// <summary> /// Adds the elements of an array to the end of this TypeDeclarationCollection. /// </summary> /// <param name="items"> /// The array whose elements are to be added to the end of this TypeDeclarationCollection. /// </param> public virtual void AddRange(ITypeDeclaration[] items) { foreach (ITypeDeclaration item in items) { this.List.Add(item); } } /// <summary> /// Adds the elements of another TypeDeclarationCollection to the end of this TypeDeclarationCollection. /// </summary> /// <param name="items"> /// The TypeDeclarationCollection whose elements are to be added to the end of this TypeDeclarationCollection. /// </param> public virtual void AddRange(TypeDeclarationCollection items) { foreach (ITypeDeclaration item in items) { this.List.Add(item); } } /// <summary> /// Adds an instance of type ITypeDeclaration to the end of this TypeDeclarationCollection. /// </summary> /// <param name="value"> /// The ITypeDeclaration to be added to the end of this TypeDeclarationCollection. /// </param> public virtual void Add(ITypeDeclaration value) { this.List.Add(value); } public virtual void Add(Type value) { this.List.Add(new TypeTypeDeclaration(value)); } /// <summary> /// Determines whether a specfic ITypeDeclaration value is in this TypeDeclarationCollection. /// </summary> /// <param name="value"> /// The ITypeDeclaration value to locate in this TypeDeclarationCollection. /// </param> /// <returns> /// true if value is found in this TypeDeclarationCollection; /// false otherwise. /// </returns> public virtual bool Contains(ITypeDeclaration value) { return this.List.Contains(value); } /// <summary> /// Return the zero-based index of the first occurrence of a specific value /// in this TypeDeclarationCollection /// </summary> /// <param name="value"> /// The ITypeDeclaration value to locate in the TypeDeclarationCollection. /// </param> /// <returns> /// The zero-based index of the first occurrence of the _ELEMENT value if found; /// -1 otherwise. /// </returns> public virtual int IndexOf(ITypeDeclaration value) { return this.List.IndexOf(value); } /// <summary> /// Inserts an element into the TypeDeclarationCollection at the specified index /// </summary> /// <param name="index"> /// The index at which the ITypeDeclaration is to be inserted. /// </param> /// <param name="value"> /// The ITypeDeclaration to insert. /// </param> public virtual void Insert(int index, ITypeDeclaration value) { this.List.Insert(index, value); } /// <summary> /// Gets or sets the ITypeDeclaration at the given index in this TypeDeclarationCollection. /// </summary> public virtual ITypeDeclaration this[int index] { get { return (ITypeDeclaration) this.List[index]; } set { this.List[index] = value; } } /// <summary> /// Removes the first occurrence of a specific ITypeDeclaration from this TypeDeclarationCollection. /// </summary> /// <param name="value"> /// The ITypeDeclaration value to remove from this TypeDeclarationCollection. /// </param> public virtual void Remove(ITypeDeclaration value) { this.List.Remove(value); } /// <summary> /// Type-specific enumeration class, used by TypeDeclarationCollection.GetEnumerator. /// </summary> public class Enumerator: System.Collections.IEnumerator { private System.Collections.IEnumerator wrapped; public Enumerator(TypeDeclarationCollection collection) { this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator(); } public ITypeDeclaration Current { get { return (ITypeDeclaration) (this.wrapped.Current); } } object System.Collections.IEnumerator.Current { get { return (ITypeDeclaration) (this.wrapped.Current); } } public bool MoveNext() { return this.wrapped.MoveNext(); } public void Reset() { this.wrapped.Reset(); } } /// <summary> /// Returns an enumerator that can iterate through the elements of this TypeDeclarationCollection. /// </summary> /// <returns> /// An object that implements System.Collections.IEnumerator. /// </returns> public new virtual TypeDeclarationCollection.Enumerator GetEnumerator() { return new TypeDeclarationCollection.Enumerator(this); } } }
using System; using NUnit.Framework; using Bieb.Domain.CustomDataTypes; namespace Bieb.Tests.Domain { [TestFixture] public class UncertainDateTests { [Test] public void Can_Be_Constructed_Without_Any_Info() { var date = new UncertainDate(); Assert.That(date.Day, Is.Null); Assert.That(date.Month, Is.Null); Assert.That(date.Year, Is.Null); } [Test] public void Can_Be_Constructed_With_Only_Year_Known() { var date = new UncertainDate(1999); Assert.That(date.Year, Is.Not.Null); Assert.That(date.Year.Value, Is.EqualTo(1999)); Assert.That(date.Month, Is.Null); Assert.That(date.Day, Is.Null); } [Test] public void Can_Be_Constructed_With_Full_Date_Info() { var date = new UncertainDate(1999, 11, 23); Assert.That(date.Year, Is.Not.Null); Assert.That(date.Month, Is.Not.Null); Assert.That(date.Day, Is.Not.Null); Assert.That(date.Year.Value, Is.EqualTo(1999)); Assert.That(date.Month.Value, Is.EqualTo(11)); Assert.That(date.Day.Value, Is.EqualTo(23)); } [Test] public void Can_Be_Constructed_With_One_Year_Span() { var from = new DateTime(1999, 1, 1); var until = new DateTime(1999, 12, 31); var date = new UncertainDate(from, until); Assert.That(date.Year, Is.Not.Null); Assert.That(date.Year.Value, Is.EqualTo(1999)); Assert.That(date.Month, Is.Null); Assert.That(date.Day, Is.Null); } [Test] public void Can_Be_Constructed_With_One_Month_Span() { var from = new DateTime(1999, 6, 1); var until = new DateTime(1999, 6, 30); var date = new UncertainDate(from, until); Assert.That(date.Year, Is.Not.Null); Assert.That(date.Year.Value, Is.EqualTo(1999)); Assert.That(date.Month, Is.Not.Null); Assert.That(date.Month.Value, Is.EqualTo(6)); Assert.That(date.Day, Is.Null); } [Test] public void Completely_Uncertain_Date_Gives_Question_Mark_On_ToString() { var date = new UncertainDate(); Assert.That(date.ToString(), Is.EqualTo("?")); } [Test] public void Only_Year_Known_Gives_Year_On_ToString() { var date = new UncertainDate(1998); Assert.That(date.ToString(), Is.EqualTo("1998")); } [Test] [SetCulture("en-US")] public void Only_Year_And_Month_Known_Gives_Localized_Monthname_Plus_Year_On_ToString() { var date = new UncertainDate(1998, 1); Assert.That(date.ToString(), Is.EqualTo("January 1998")); } [Test] [SetCulture("en-US")] public void Known_Date_Gives_Localized_DateTime_ShortDateString_On_ToString() { var someDateTime = new DateTime(1992, 4, 6); var date = new UncertainDate(someDateTime, someDateTime); Assert.That(date.ToString(), Is.EqualTo(someDateTime.ToShortDateString())); } [Test] public void Construct_From_Certain_Dates_Gives_Back_Certain_Dates() { var someDateTime = new DateTime(1780, 4, 20); var uncertainDate = new UncertainDate(someDateTime, someDateTime); var fromDate = uncertainDate.FromDate; var toDate = uncertainDate.UntilDate; Assert.That(someDateTime, Is.EqualTo(fromDate)); Assert.That(someDateTime, Is.EqualTo(toDate)); } [Test] public void Uncertain_Date_With_Only_Year_Will_Give_Back_To_And_From_Spanning_One_Year() { const int year = 1950; var uncertainDate = new UncertainDate(year, null, null); var fromDate = uncertainDate.FromDate; var toDate = uncertainDate.UntilDate; Assert.That(fromDate.HasValue); Assert.That(fromDate.Value.Year, Is.EqualTo(year)); Assert.That(fromDate.Value.Month, Is.EqualTo(1)); Assert.That(fromDate.Value.Day, Is.EqualTo(1)); Assert.That(toDate.HasValue); Assert.That(toDate.Value.Year, Is.EqualTo(year)); Assert.That(toDate.Value.Month, Is.EqualTo(12)); Assert.That(toDate.Value.Day, Is.EqualTo(31)); } [Test] public void Can_Create_Leap_Year_Uncertain_Date_For_February_Without_Day() { const int leapyear = 1600; const int february = 2; var uncertainDate = new UncertainDate(leapyear, february, null); var fromDate = uncertainDate.FromDate; var toDate = uncertainDate.UntilDate; Assert.That(fromDate.HasValue); Assert.That(fromDate.Value.Year, Is.EqualTo(leapyear)); Assert.That(fromDate.Value.Month, Is.EqualTo(february)); Assert.That(fromDate.Value.Day, Is.EqualTo(1)); Assert.That(toDate.HasValue); Assert.That(toDate.Value.Year, Is.EqualTo(leapyear)); Assert.That(toDate.Value.Month, Is.EqualTo(february)); Assert.That(toDate.Value.Day, Is.EqualTo(29)); } [Test] public void Null_Year_Is_Automatically_Uknown_FromDate() { var date = new UncertainDate(null, 12, 25); Assert.That(date.FromDate, Is.Null); } [Test] public void Null_Year_Is_Automatically_Uknown_UntilDate() { var date = new UncertainDate(null, 12, 25); Assert.That(date.UntilDate, Is.Null); } [Test] public void Is_Default_Completely_Unknown() { var date = new UncertainDate(); Assert.That(date.IsCompletelyUnknown, Is.True); } [Test] public void Is_Not_Completely_Unknown_If_Year_Is_Set() { var date = new UncertainDate(1990); Assert.That(date.IsCompletelyUnknown, Is.False); } [Test] public void Is_Not_Completely_Unknown_If_Month_Is_Set() { var date = new UncertainDate { Month = 12 }; Assert.That(date.IsCompletelyUnknown, Is.False); } [Test] public void Is_Not_Completely_Unknown_If_Day_Is_Set() { var date = new UncertainDate { Day = 12 }; Assert.That(date.IsCompletelyUnknown, Is.False); } } }
#region License /* Copyright (c) 2006 Leslie Sanford * * 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 #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Threading; using System.Timers; using Sanford.Collections; namespace Sanford.Threading { /// <summary> /// Provides functionality for timestamped delegate invocation. /// </summary> public partial class DelegateScheduler : IDisposable, IComponent { #region DelegateScheduler Members #region Fields /// <summary> /// A constant value representing an unlimited number of delegate invocations. /// </summary> public const int Infinite = -1; // Default polling interval. private const int DefaultPollingInterval = 10; // For queuing the delegates in priority order. private PriorityQueue queue = new PriorityQueue(); // Used for timing events for polling the delegate queue. private System.Timers.Timer timer = new System.Timers.Timer(DefaultPollingInterval); // For storing tasks when the scheduler isn't running. private List<Task> tasks = new List<Task>(); // A value indicating whether the DelegateScheduler is running. private bool running = false; // A value indicating whether the DelegateScheduler has been disposed. private bool disposed = false; private ISite site = null; #endregion #region Events /// <summary> /// Raised when a delegate is invoked. /// </summary> public event EventHandler<InvokeCompletedEventArgs> InvokeCompleted; #endregion #region Construction /// <summary> /// Initializes a new instance of the DelegateScheduler class. /// </summary> public DelegateScheduler() { Initialize(); } /// <summary> /// Initializes a new instance of the DelegateScheduler class with the /// specified IContainer. /// </summary> public DelegateScheduler(IContainer container) { /// /// Required for Windows.Forms Class Composition Designer support /// container.Add(this); Initialize(); } // Initializes the DelegateScheduler. private void Initialize() { timer.Elapsed += new ElapsedEventHandler(HandleElapsed); } ~DelegateScheduler() { Dispose(false); } #endregion #region Methods protected virtual void Dispose(bool disposing) { if(disposing) { Stop(); timer.Dispose(); Clear(); disposed = true; OnDisposed(EventArgs.Empty); GC.SuppressFinalize(this); } } /// <summary> /// Adds a delegate to the DelegateScheduler. /// </summary> /// <param name="count"> /// The number of times the delegate should be invoked. /// </param> /// <param name="millisecondsTimeout"> /// The time in milliseconds between delegate invocation. /// </param> /// <param name="method"> /// </param> /// The delegate to invoke. /// <param name="args"> /// The arguments to pass to the delegate when it is invoked. /// </param> /// <returns> /// A Task object representing the scheduled task. /// </returns> /// <exception cref="ObjectDisposedException"> /// If the DelegateScheduler has already been disposed. /// </exception> /// <remarks> /// If an unlimited count is desired, pass the DelegateScheduler.Infinity /// constant as the count argument. /// </remarks> public Task Add( int count, int millisecondsTimeout, Delegate method, params object[] args) { #region Require if(disposed) { throw new ObjectDisposedException("DelegateScheduler"); } #endregion Task t = new Task(count, millisecondsTimeout, method, args); lock(queue.SyncRoot) { // Only add the task to the DelegateScheduler if the count // is greater than zero or set to Infinite. if(count > 0 || count == DelegateScheduler.Infinite) { if(IsRunning) { queue.Enqueue(t); } else { tasks.Add(t); } } } return t; } /// <summary> /// Removes the specified Task. /// </summary> /// <param name="task"> /// The Task to be removed. /// </param> /// <exception cref="ObjectDisposedException"> /// If the DelegateScheduler has already been disposed. /// </exception> public void Remove(Task task) { #region Require if(disposed) { throw new ObjectDisposedException("DelegateScheduler"); } #endregion #region Guard if(task == null) { return; } #endregion lock(queue.SyncRoot) { if(IsRunning) { queue.Remove(task); } else { tasks.Remove(task); } } } /// <summary> /// Starts the DelegateScheduler. /// </summary> /// <exception cref="ObjectDisposedException"> /// If the DelegateScheduler has already been disposed. /// </exception> public void Start() { #region Require if(disposed) { throw new ObjectDisposedException(this.GetType().Name); } #endregion #region Guard if(IsRunning) { return; } #endregion lock(queue.SyncRoot) { Task t; while(tasks.Count > 0) { t = tasks[tasks.Count - 1]; tasks.RemoveAt(tasks.Count - 1); t.ResetNextTimeout(); queue.Enqueue(t); } running = true; timer.Start(); } } /// <summary> /// Stops the DelegateScheduler. /// </summary> /// <exception cref="ObjectDisposedException"> /// If the DelegateScheduler has already been disposed. /// </exception> public void Stop() { #region Require if(disposed) { throw new ObjectDisposedException(this.GetType().Name); } #endregion #region Guard if(!IsRunning) { return; } #endregion lock(queue.SyncRoot) { // While there are still tasks left in the queue. while(queue.Count > 0) { // Remove task from queue and add it to the Task list // to be used again next time the DelegateScheduler is run. tasks.Add((Task)queue.Dequeue()); } timer.Stop(); running = false; } } /// <summary> /// Clears the DelegateScheduler of all tasks. /// </summary> /// <exception cref="ObjectDisposedException"> /// If the DelegateScheduler has already been disposed. /// </exception> public void Clear() { #region Require if(disposed) { throw new ObjectDisposedException(this.GetType().Name); } #endregion lock(queue.SyncRoot) { queue.Clear(); tasks.Clear(); } } // Responds to the timer's Elapsed event by running any tasks that are due. private void HandleElapsed(object sender, ElapsedEventArgs e) { Debug.WriteLine("Signal time: " + e.SignalTime.ToString()); lock(queue.SyncRoot) { #region Guard if(queue.Count == 0) { return; } #endregion // Take a look at the first task in the queue to see if it's // time to run it. Task tk = (Task)queue.Peek(); // The return value from the delegate that will be invoked. object returnValue; // While there are still tasks in the queue and it is time // to run one or more of them. while(queue.Count > 0 && tk.NextTimeout <= e.SignalTime) { // Remove task from queue. queue.Dequeue(); // While it's time for the task to run. while((tk.Count == Infinite || tk.Count > 0) && tk.NextTimeout <= e.SignalTime) { try { Debug.WriteLine("Invoking delegate."); Debug.WriteLine("Next timeout: " + tk.NextTimeout.ToString()); // Invoke delegate. returnValue = tk.Invoke(e.SignalTime); OnInvokeCompleted( new InvokeCompletedEventArgs( tk.Method, tk.GetArgs(), returnValue, null)); } catch(Exception ex) { OnInvokeCompleted( new InvokeCompletedEventArgs( tk.Method, tk.GetArgs(), null, ex)); } } // If this task should run again. if(tk.Count == Infinite || tk.Count > 0) { // Enqueue task back into priority queue. queue.Enqueue(tk); } // If there are still tasks in the queue. if(queue.Count > 0) { // Take a look at the next task to see if it is // time to run. tk = (Task)queue.Peek(); } } } } // Raises the Disposed event. protected virtual void OnDisposed(EventArgs e) { EventHandler handler = Disposed; if(handler != null) { handler(this, e); } } // Raises the InvokeCompleted event. protected virtual void OnInvokeCompleted(InvokeCompletedEventArgs e) { EventHandler<InvokeCompletedEventArgs> handler = InvokeCompleted; if(handler != null) { handler(this, e); } } #endregion #region Properties /// <summary> /// Gets or sets the interval in milliseconds in which the /// DelegateScheduler polls its queue of delegates in order to /// determine when they should run. /// </summary> public double PollingInterval { get { #region Require if(disposed) { throw new ObjectDisposedException("PriorityQueue"); } #endregion return timer.Interval; } set { #region Require if(disposed) { throw new ObjectDisposedException("PriorityQueue"); } #endregion timer.Interval = value; } } /// <summary> /// Gets a value indicating whether the DelegateScheduler is running. /// </summary> public bool IsRunning { get { return running; } } /// <summary> /// Gets or sets the object used to marshal event-handler calls and delegate invocations. /// </summary> public ISynchronizeInvoke SynchronizingObject { get { return timer.SynchronizingObject; } set { timer.SynchronizingObject = value; } } #endregion #endregion #region IComponent Members public event System.EventHandler Disposed; public ISite Site { get { return site; } set { site = value; } } #endregion #region IDisposable Members public void Dispose() { #region Guard if(disposed) { return; } #endregion Dispose(true); } #endregion } }
namespace AutoMapper { using System; using Internal; using Mappers; using QueryableExtensions; /// <summary> /// Main entry point for AutoMapper, for both creating maps and performing maps. /// </summary> public static class Mapper { private static readonly Func<ConfigurationStore> _configurationInit = () => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers); private static ILazy<ConfigurationStore> _configuration = LazyFactory.Create(_configurationInit); private static readonly Func<IMappingEngine> _mappingEngineInit = () => new MappingEngine(_configuration.Value); private static ILazy<IMappingEngine> _mappingEngine = LazyFactory.Create(_mappingEngineInit); /// <summary> /// When set, destination can have null values. Defaults to true. /// This does not affect simple types, only complex ones. /// </summary> public static bool AllowNullDestinationValues { get { return Configuration.AllowNullDestinationValues; } set { Configuration.AllowNullDestinationValues = value; } } /// <summary> /// Execute a mapping from the source object to a new destination object. /// The source type is inferred from the source object. /// </summary> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TDestination>(object source) { return Engine.Map<TDestination>(source); } /// <summary> /// Execute a mapping from the source object to a new destination object with supplied mapping options. /// </summary> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts) { return Engine.Map<TDestination>(source, opts); } /// <summary> /// Execute a mapping from the source object to a new destination object. /// </summary> /// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TSource, TDestination>(TSource source) { return Engine.Map<TSource, TDestination>(source); } /// <summary> /// Execute a mapping from the source object to the existing destination object. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Dsetination type</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination) { return Engine.Map(source, destination); } /// <summary> /// Execute a mapping from the source object to the existing destination object with supplied mapping options. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="opts">Mapping options</param> /// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts) { return Engine.Map(source, destination, opts); } /// <summary> /// Execute a mapping from the source object to a new destination object with supplied mapping options. /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type to create</typeparam> /// <param name="source">Source object to map from</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts) { return Engine.Map(source, opts); } /// <summary> /// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to create</param> /// <returns>Mapped destination object</returns> public static object Map(object source, Type sourceType, Type destinationType) { return Engine.Map(source, sourceType, destinationType); } /// <summary> /// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects and supplied mapping options. /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to create</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object</returns> public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { return Engine.Map(source, sourceType, destinationType, opts); } /// <summary> /// Execute a mapping from the source object to existing destination object with explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static object Map(object source, object destination, Type sourceType, Type destinationType) { return Engine.Map(source, destination, sourceType, destinationType); } /// <summary> /// Execute a mapping from the source object to existing destination object with supplied mapping options and explicit <see cref="System.Type"/> objects /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <param name="opts">Mapping options</param> /// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns> public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { return Engine.Map(source, destination, sourceType, destinationType, opts); } /// <summary> /// Create a map between the <typeparamref name="TSource"/> and <typeparamref name="TDestination"/> types and execute the map /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type to use</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination DynamicMap<TSource, TDestination>(TSource source) { return Engine.DynamicMap<TSource, TDestination>(source); } /// <summary> /// Create a map between the <typeparamref name="TSource"/> and <typeparamref name="TDestination"/> types and execute the map to the existing destination object /// </summary> /// <typeparam name="TSource">Source type to use</typeparam> /// <typeparam name="TDestination">Destination type to use</typeparam> /// <param name="source">Source object to map from</param> /// <param name="destination">Destination object to map into</param> public static void DynamicMap<TSource, TDestination>(TSource source, TDestination destination) { Engine.DynamicMap(source, destination); } /// <summary> /// Create a map between the <paramref name="source"/> object and <typeparamref name="TDestination"/> types and execute the map. /// Source type is inferred from the source object . /// </summary> /// <typeparam name="TDestination">Destination type to use</typeparam> /// <param name="source">Source object to map from</param> /// <returns>Mapped destination object</returns> public static TDestination DynamicMap<TDestination>(object source) { return Engine.DynamicMap<TDestination>(source); } /// <summary> /// Create a map between the <paramref name="sourceType"/> and <paramref name="destinationType"/> types and execute the map. /// Use this method when the source and destination types are not known until runtime. /// </summary> /// <param name="source">Source object to map from</param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> /// <returns>Mapped destination object</returns> public static object DynamicMap(object source, Type sourceType, Type destinationType) { return Engine.DynamicMap(source, sourceType, destinationType); } /// <summary> /// Create a map between the <paramref name="sourceType"/> and <paramref name="destinationType"/> types and execute the map to the existing destination object. /// Use this method when the source and destination types are not known until runtime. /// </summary> /// <param name="source">Source object to map from</param> /// <param name="destination"></param> /// <param name="sourceType">Source type to use</param> /// <param name="destinationType">Destination type to use</param> public static void DynamicMap(object source, object destination, Type sourceType, Type destinationType) { Engine.DynamicMap(source, destination, sourceType, destinationType); } /// <summary> /// Initializes the mapper with the supplied configuration. Runtime optimization complete after this method is called. /// This is the preferred means to configure AutoMapper. /// </summary> /// <param name="action">Initialization callback</param> public static void Initialize(Action<IConfiguration> action) { Reset(); action(Configuration); Configuration.Seal(); } /// <summary> /// Creates a mapping configuration from the <typeparamref name="TSource"/> type to the <typeparamref name="TDestination"/> type /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <returns>Mapping expression for more configuration options</returns> public static IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>() { return Configuration.CreateMap<TSource, TDestination>(); } /// <summary> /// Creates a mapping configuration from the <typeparamref name="TSource"/> type to the <typeparamref name="TDestination"/> type. /// Specify the member list to validate against during configuration validation. /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="memberList">Member list to validate</param> /// <returns>Mapping expression for more configuration options</returns> public static IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(MemberList memberList) { return Configuration.CreateMap<TSource, TDestination>(memberList); } /// <summary> /// Create a mapping configuration from the source type to the destination type. /// Use this method when the source and destination type are known at runtime and not compile time. /// </summary> /// <param name="sourceType">Source type</param> /// <param name="destinationType">Destination type</param> /// <returns>Mapping expression for more configuration options</returns> public static IMappingExpression CreateMap(Type sourceType, Type destinationType) { return Configuration.CreateMap(sourceType, destinationType); } /// <summary> /// Creates a mapping configuration from the source type to the destination type. /// Specify the member list to validate against during configuration validation. /// </summary> /// <param name="sourceType">Source type</param> /// <param name="destinationType">Destination type</param> /// <param name="memberList">Member list to validate</param> /// <returns>Mapping expression for more configuration options</returns> public static IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList) { return Configuration.CreateMap(sourceType, destinationType, memberList); } /// <summary> /// Create a named profile for grouped mapping configuration /// </summary> /// <param name="profileName">Profile name</param> /// <returns>Profile configuration options</returns> public static IProfileExpression CreateProfile(string profileName) { return Configuration.CreateProfile(profileName); } /// <summary> /// Create a named profile for grouped mapping configuration, and configure the profile /// </summary> /// <param name="profileName">Profile name</param> /// <param name="profileConfiguration">Profile configuration callback</param> public static void CreateProfile(string profileName, Action<IProfileExpression> profileConfiguration) { Configuration.CreateProfile(profileName, profileConfiguration); } /// <summary> /// Add an existing profile /// </summary> /// <param name="profile">Profile to add</param> public static void AddProfile(Profile profile) { Configuration.AddProfile(profile); } /// <summary> /// Add an existing profile type. Profile will be instantiated and added to the configuration. /// </summary> /// <typeparam name="TProfile">Profile type</typeparam> public static void AddProfile<TProfile>() where TProfile : Profile, new() { Configuration.AddProfile<TProfile>(); } /// <summary> /// Find the <see cref="TypeMap"/> for the configured source and destination type /// </summary> /// <param name="sourceType">Configured source type</param> /// <param name="destinationType">Configured destination type</param> /// <returns>Type map configuration</returns> public static TypeMap FindTypeMapFor(Type sourceType, Type destinationType) { return ConfigurationProvider.FindTypeMapFor(sourceType, destinationType); } /// <summary> /// Find the <see cref="TypeMap"/> for the configured source and destination type /// </summary> /// <typeparam name="TSource">Configured source type</typeparam> /// <typeparam name="TDestination">Configured destination type</typeparam> /// <returns>Type map configuration</returns> public static TypeMap FindTypeMapFor<TSource, TDestination>() { return ConfigurationProvider.FindTypeMapFor(typeof (TSource), typeof (TDestination)); } /// <summary> /// Get all configured type maps created /// </summary> /// <returns>All configured type maps</returns> public static TypeMap[] GetAllTypeMaps() { return ConfigurationProvider.GetAllTypeMaps(); } /// <summary> /// Dry run all configured type maps and throw <see cref="AutoMapperConfigurationException"/> for each problem /// </summary> public static void AssertConfigurationIsValid() { ConfigurationProvider.AssertConfigurationIsValid(); } /// <summary> /// Dry run single type map /// </summary> /// <param name="typeMap">Type map to check</param> public static void AssertConfigurationIsValid(TypeMap typeMap) { ConfigurationProvider.AssertConfigurationIsValid(typeMap); } /// <summary> /// Dry run all type maps in given profile /// </summary> /// <param name="profileName">Profile name of type maps to test</param> public static void AssertConfigurationIsValid(string profileName) { ConfigurationProvider.AssertConfigurationIsValid(profileName); } /// <summary> /// Dry run all type maps in given profile /// </summary> /// <typeparam name="TProfile">Profile type</typeparam> public static void AssertConfigurationIsValid<TProfile>() where TProfile : Profile, new() { ConfigurationProvider.AssertConfigurationIsValid<TProfile>(); } /// <summary> /// Clear out all existing configuration /// </summary> public static void Reset() { MapperRegistry.Reset(); _configuration = LazyFactory.Create(_configurationInit); _mappingEngine = LazyFactory.Create(_mappingEngineInit); } /// <summary> /// Mapping engine used to perform mappings /// </summary> public static IMappingEngine Engine => _mappingEngine.Value; /// <summary> /// Store for all configuration /// </summary> public static IConfiguration Configuration => (IConfiguration) ConfigurationProvider; private static IConfigurationProvider ConfigurationProvider => _configuration.Value; /// <summary> /// Globally ignore all members starting with a prefix /// </summary> /// <param name="startingwith">Prefix of members to ignore. Call this before all other maps created.</param> public static void AddGlobalIgnore(string startingwith) { Configuration.AddGlobalIgnore(startingwith); } } }
namespace ZetaResourceEditor.UI.Main.RightContent { partial class GroupFilesUserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if ( disposing && (components != null) ) { components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GroupFilesUserControl)); this.mainTabControl = new ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabControl(); this.imageCollection1 = new DevExpress.Utils.ImageCollection(this.components); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.barDockControl1 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl2 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl3 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl4 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl5 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl6 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl7 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl8 = new DevExpress.XtraBars.BarDockControl(); this.optionsPopupMenu = new DevExpress.XtraBars.PopupMenu(this.components); this.buttonSave = new DevExpress.XtraBars.BarButtonItem(); this.buttonSaveAll = new DevExpress.XtraBars.BarButtonItem(); this.buttonOpenFolder = new DevExpress.XtraBars.BarButtonItem(); this.buttonClose = new DevExpress.XtraBars.BarButtonItem(); this.buttonCloseAllButThis = new DevExpress.XtraBars.BarButtonItem(); this.buttonCloseAll = new DevExpress.XtraBars.BarButtonItem(); this.barManager = new DevExpress.XtraBars.BarManager(this.components); ((System.ComponentModel.ISupportInitialize)(this.mainTabControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imageCollection1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.optionsPopupMenu)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager)).BeginInit(); this.SuspendLayout(); // // mainTabControl // this.mainTabControl.AppearancePage.Header.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.mainTabControl.AppearancePage.Header.Options.UseFont = true; this.mainTabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.mainTabControl.Images = this.imageCollection1; this.mainTabControl.Location = new System.Drawing.Point(0, 0); this.mainTabControl.Name = "mainTabControl"; this.mainTabControl.Size = new System.Drawing.Size(150, 150); this.mainTabControl.TabIndex = 0; this.mainTabControl.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mainTabControl_MouseUp); // // imageCollection1 // this.imageCollection1.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("imageCollection1.ImageStream"))); this.imageCollection1.Images.SetKeyName(0, "project"); this.imageCollection1.Images.SetKeyName(1, "projectfolder"); this.imageCollection1.Images.SetKeyName(2, "filegroup"); // // barDockControlTop // this.barDockControlTop.CausesValidation = false; this.barDockControlTop.Location = new System.Drawing.Point(0, 0); this.barDockControlTop.Size = new System.Drawing.Size(0, 0); // // barDockControlBottom // this.barDockControlBottom.CausesValidation = false; this.barDockControlBottom.Location = new System.Drawing.Point(0, 0); this.barDockControlBottom.Size = new System.Drawing.Size(0, 0); // // barDockControlLeft // this.barDockControlLeft.CausesValidation = false; this.barDockControlLeft.Location = new System.Drawing.Point(0, 0); this.barDockControlLeft.Size = new System.Drawing.Size(0, 0); // // barDockControlRight // this.barDockControlRight.CausesValidation = false; this.barDockControlRight.Location = new System.Drawing.Point(0, 0); this.barDockControlRight.Size = new System.Drawing.Size(0, 0); // // barDockControl1 // this.barDockControl1.CausesValidation = false; this.barDockControl1.Location = new System.Drawing.Point(0, 0); this.barDockControl1.Size = new System.Drawing.Size(0, 0); // // barDockControl2 // this.barDockControl2.CausesValidation = false; this.barDockControl2.Location = new System.Drawing.Point(0, 0); this.barDockControl2.Size = new System.Drawing.Size(0, 0); // // barDockControl3 // this.barDockControl3.CausesValidation = false; this.barDockControl3.Location = new System.Drawing.Point(0, 0); this.barDockControl3.Size = new System.Drawing.Size(0, 0); // // barDockControl4 // this.barDockControl4.CausesValidation = false; this.barDockControl4.Location = new System.Drawing.Point(0, 0); this.barDockControl4.Size = new System.Drawing.Size(0, 0); // // barDockControl5 // this.barDockControl5.CausesValidation = false; this.barDockControl5.Dock = System.Windows.Forms.DockStyle.Top; this.barDockControl5.Location = new System.Drawing.Point(0, 0); this.barDockControl5.Size = new System.Drawing.Size(150, 0); // // barDockControl6 // this.barDockControl6.CausesValidation = false; this.barDockControl6.Dock = System.Windows.Forms.DockStyle.Bottom; this.barDockControl6.Location = new System.Drawing.Point(0, 150); this.barDockControl6.Size = new System.Drawing.Size(150, 0); // // barDockControl7 // this.barDockControl7.CausesValidation = false; this.barDockControl7.Dock = System.Windows.Forms.DockStyle.Left; this.barDockControl7.Location = new System.Drawing.Point(0, 0); this.barDockControl7.Size = new System.Drawing.Size(0, 150); // // barDockControl8 // this.barDockControl8.CausesValidation = false; this.barDockControl8.Dock = System.Windows.Forms.DockStyle.Right; this.barDockControl8.Location = new System.Drawing.Point(150, 0); this.barDockControl8.Size = new System.Drawing.Size(0, 150); // // optionsPopupMenu // this.optionsPopupMenu.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.buttonSave), new DevExpress.XtraBars.LinkPersistInfo(this.buttonSaveAll), new DevExpress.XtraBars.LinkPersistInfo(this.buttonOpenFolder, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonClose, true), new DevExpress.XtraBars.LinkPersistInfo(this.buttonCloseAllButThis), new DevExpress.XtraBars.LinkPersistInfo(this.buttonCloseAll)}); this.optionsPopupMenu.Manager = this.barManager; this.optionsPopupMenu.Name = "optionsPopupMenu"; this.optionsPopupMenu.BeforePopup += new System.ComponentModel.CancelEventHandler(this.optionsPopupMenu_BeforePopup); // // buttonSave // this.buttonSave.Caption = "Save"; this.buttonSave.Glyph = ((System.Drawing.Image)(resources.GetObject("buttonSave.Glyph"))); this.buttonSave.Id = 3; this.buttonSave.Name = "buttonSave"; this.buttonSave.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonSave_ItemClick); // // buttonSaveAll // this.buttonSaveAll.Caption = "Save all"; this.buttonSaveAll.Glyph = ((System.Drawing.Image)(resources.GetObject("buttonSaveAll.Glyph"))); this.buttonSaveAll.Id = 4; this.buttonSaveAll.Name = "buttonSaveAll"; this.buttonSaveAll.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonSaveAll_ItemClick); // // buttonOpenFolder // this.buttonOpenFolder.Caption = "Open folder"; this.buttonOpenFolder.Glyph = ((System.Drawing.Image)(resources.GetObject("buttonOpenFolder.Glyph"))); this.buttonOpenFolder.Id = 5; this.buttonOpenFolder.Name = "buttonOpenFolder"; this.buttonOpenFolder.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonOpenFolder_ItemClick); // // buttonClose // this.buttonClose.Caption = "Close"; this.buttonClose.Id = 6; this.buttonClose.Name = "buttonClose"; this.buttonClose.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonClose_ItemClick); // // buttonCloseAllButThis // this.buttonCloseAllButThis.Caption = "Close all but this"; this.buttonCloseAllButThis.Id = 7; this.buttonCloseAllButThis.Name = "buttonCloseAllButThis"; this.buttonCloseAllButThis.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonCloseAllButThis_ItemClick); // // buttonCloseAll // this.buttonCloseAll.Caption = "Close all"; this.buttonCloseAll.Id = 8; this.buttonCloseAll.Name = "buttonCloseAll"; this.buttonCloseAll.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.buttonCloseAll_ItemClick); // // barManager // this.barManager.DockControls.Add(this.barDockControl5); this.barManager.DockControls.Add(this.barDockControl6); this.barManager.DockControls.Add(this.barDockControl7); this.barManager.DockControls.Add(this.barDockControl8); this.barManager.Form = this; this.barManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.buttonSave, this.buttonSaveAll, this.buttonOpenFolder, this.buttonClose, this.buttonCloseAllButThis, this.buttonCloseAll}); this.barManager.MaxItemId = 9; // // GroupFilesUserControl // this.Appearance.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.Appearance.Options.UseFont = true; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.Controls.Add(this.mainTabControl); this.Controls.Add(this.barDockControl7); this.Controls.Add(this.barDockControl8); this.Controls.Add(this.barDockControl6); this.Controls.Add(this.barDockControl5); this.Name = "GroupFilesUserControl"; ((System.ComponentModel.ISupportInitialize)(this.mainTabControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imageCollection1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.optionsPopupMenu)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ExtendedControlsLibrary.Skinning.CustomTabControl.MyXtraTabControl mainTabControl; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.BarDockControl barDockControl1; private DevExpress.XtraBars.BarDockControl barDockControl2; private DevExpress.XtraBars.BarDockControl barDockControl3; private DevExpress.XtraBars.BarDockControl barDockControl4; private DevExpress.XtraBars.BarDockControl barDockControl5; private DevExpress.XtraBars.BarDockControl barDockControl6; private DevExpress.XtraBars.BarDockControl barDockControl7; private DevExpress.XtraBars.BarDockControl barDockControl8; private DevExpress.XtraBars.PopupMenu optionsPopupMenu; private DevExpress.XtraBars.BarManager barManager; private DevExpress.XtraBars.BarButtonItem buttonSave; private DevExpress.XtraBars.BarButtonItem buttonSaveAll; private DevExpress.XtraBars.BarButtonItem buttonOpenFolder; private DevExpress.XtraBars.BarButtonItem buttonClose; private DevExpress.XtraBars.BarButtonItem buttonCloseAllButThis; private DevExpress.XtraBars.BarButtonItem buttonCloseAll; private DevExpress.Utils.ImageCollection imageCollection1; } }
#region using declarations using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Net.NetworkInformation; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using DigitallyImported.Components; using DigitallyImported.Configuration.Properties; using DigitallyImported.Controls.Windows; using DigitallyImported.Player; using P = DigitallyImported.Resources.Properties; #endregion // using DigitallyImported.Client.PlaylistService; namespace DigitallyImported.Client.Controls { /// <summary> /// </summary> public partial class ContentControl<TChannel, TTrack> : UserControl where TChannel : UserControl, IChannel, new() where TTrack : UserControl, ITrack, new() { // value types private const string serviceOfflineMessage = "DI.fm playlist service is currently offline."; private readonly string _eventsUrl = string.Format("{0}{1}/{2}/{3}", "http://", P.Resources.DIHomePage, "calendar", Settings.Default.CalendarFormat.ToLower()); private readonly RefreshCounter _refreshCounter = new RefreshCounter(); // reference types private TChannel _channel; // views private ChannelView<TChannel, TTrack> _channelView; private EventView<Event> _eventView; private bool _isFirstRun = true; // players private PlayerLoader _playerLoader; private HistoryForm _trackHistory; /// <summary> /// </summary> public ContentControl() { InitializeComponent(); } protected override void OnPaint(PaintEventArgs e) { } private void ContentControl_Load(object sender, EventArgs e) { _channelView = new ChannelView<TChannel, TTrack>(); _eventView = new EventView<Event>(); // check network status UpdateNetworkStatus(NetworkInterface.GetIsNetworkAvailable()); Task.Factory.StartNew(BindEvents); // local properties RefreshPlaylistButton.Image = P.Resources.icon_repeat; ViewEventsSplitButton.Image = P.Resources.icon_calendar; ViewPlaylistsSplitButton.Image = P.Resources.icon_web; SortPlaylistSplitButton.Image = P.Resources.icon_sort; PlayerTypeSplitButton.Image = P.Resources.icon_sound.ToBitmap(); OptionsButton.Image = P.Resources.icon_options; ExceptionStatusMessage.Image = P.Resources.icon_warning; MainNotifyIcon.Icon = P.Resources.DIIconOld; // SWITCH DYNAMICALLY BASED ON CHANNEL LISTENING TO MainNotifyIcon.ContextMenuStrip = ChannelsContextMenu; MainNotifyIcon.Text = P.Resources.ApplicationTitle; RefreshCounterLabel.Text = P.Resources.PlaylistRefreshText; _refreshCounter.Stop(); ViewPlaylistsSplitButton.DropDown = PlaylistsContextMenu; SortPlaylistSplitButton.DropDown = SortContextMenu; PlayerTypeSplitButton.DropDown = PlayersContextMenu; PlayerTypeSplitButton.Text = Components.Utilities.SplitName(Settings.Default.PlayerType); FeedbackButton.ToolTipText = P.Resources.SupportPageUrl; // memory counter //System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); //t.Interval = 1000; //t.Start(); //t.Tick += (s, ea) => //{ // MemoryStatus.Text = string.Format("{0} {1}", ((long)Process.GetCurrentProcess(). / 1024).ToString(), "KB"); //}; // end } /// <summary> /// </summary> protected virtual void BindEvents() { // BIND GLOBAL EVENTS Channel.ChannelChanged += ChannelChanged; RefreshCounter.CounterRefreshed += RefreshPlaylist; Settings.Default.SettingsSaving += (sender, e) => { if (Parent != null && !e.Cancel) RefreshPlaylist(sender, e); }; NetworkChange.NetworkAvailabilityChanged += (sender, e) => BeginInvoke(new WaitCallback(UpdateNetworkStatus), e.IsAvailable); if (ParentForm != null) { ParentForm.FormClosing += (sender, e) => { if (!e.Cancel) _channelView.Save(); }; ParentForm.Resize += (sender, e) => { if (!_isFirstRun) UpdateVisualCues(); }; MainNotifyIcon.MouseDoubleClick += (sender, e) => { if (e.Button == MouseButtons.Left) ParentForm.WindowState = FormWindowState.Normal; }; } // player isn't installed? PlayerLoader.PlayerNotInstalledException += (sender, e) => MessageBox.Show(e.Exception.Message); // testing custom border PlaylistPanel.Paint += (s, pea) => { // ControlPaint.DrawBorder(pea.Graphics, pea.ClipRectangle, Color.Gray, ButtonBorderStyle.Solid); }; } /// <summary> /// </summary> /// <param name="state"> </param> protected virtual void UpdateNetworkStatus(object state) { if (state == null) throw new ArgumentNullException("state"); if ((bool) state) { ConnectionStatusLabel.Text = P.Resources.NetworkOnline; ConnectionStatusLabel.ToolTipText = P.Resources.NetworkAvailable; ConnectionStatusLabel.Image = P.Resources.icon_connected.ToBitmap(); Enabled = true; } else { ConnectionStatusLabel.Text = P.Resources.NetworkOffline; ConnectionStatusLabel.ToolTipText = P.Resources.NetworkUnavailable; ConnectionStatusLabel.Image = P.Resources.icon_disconnected.ToBitmap(); Enabled = false; // DON"T DISABLE THE ENTIRE F'ING THING...and do this from the base form class. } } private void ChannelChanged(object sender, ChannelChangedEventArgs<IChannel> e) { SetTrackText(e.RefreshedContent.CurrentTrack); foreach (var control in PlaylistPanel.Controls.OfType<TChannel>()) { if (control.Equals(e.RefreshedContent)) { _channel = e.RefreshedContent as TChannel; UpdateVisualCues(); } else { (control).IsSelected = false; } } } private void RefreshPlaylist(object sender, EventArgs e) { RefreshPlaylistButton.Enabled = false; PlaylistRefreshProgress.Visible = true; PlaylistRefreshProgress.Enabled = false; ExceptionStatusMessage.Visible = false; PlaylistPanel.Enabled = false; if (!NetworkInterface.GetIsNetworkAvailable()) return; try { if (!RefreshPlaylistWorker.IsBusy) RefreshPlaylistWorker.RunWorkerAsync(); if (!RefreshEventlistWorker.IsBusy) RefreshEventlistWorker.RunWorkerAsync(); // OFFLOAD ELSEWHERE } catch (Exception exc) { RefreshPlaylistButton.Enabled = true; PlaylistRefreshProgress.Visible = false; ExceptionStatusMessage.Visible = true; ExceptionStatusMessage.ToolTipText = exc.ToString(); Trace.WriteLine(exc.ToString()); } } private ChannelCollection<TChannel> RefreshPlaylistAsync(BackgroundWorker worker, DoWorkEventArgs e) { if (worker == null) throw new ArgumentNullException("worker"); var channels = new ChannelCollection<TChannel>(); int percentageComplete = 0; worker.ReportProgress(0); worker.ReportProgress(50); worker.ReportProgress(100); try { channels = _channelView.GetView(false); } catch (XmlException) { DISiteUnavailable(); } return channels; } private EventCollection<Event> RefreshEventlistAsync(BackgroundWorker worker, DoWorkEventArgs e) { if (worker == null) throw new ArgumentNullException("worker"); var events = new EventCollection<Event>(); worker.ReportProgress(0); try { events = _eventView.GetView(false); } catch (XmlException) { DISiteUnavailable(); } return events; } private void RefreshPlaylistWorker_DoWork(object sender, DoWorkEventArgs e) { var bw = sender as BackgroundWorker; e.Result = RefreshPlaylistAsync(bw, e); } private void RefreshEventlistWorker_DoWork(object sender, DoWorkEventArgs e) { var bw = sender as BackgroundWorker; e.Result = RefreshEventlistAsync(bw, e); } private void RefreshPlaylistWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { PlaylistRefreshProgress.Value = e.ProgressPercentage; } private void RefreshEventlistWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // TODO, implement } private void RefreshPlaylistWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var channels = e.Result as ChannelCollection<TChannel>; PlaylistPanel.Channels = channels != null && channels.Count > 0 ? channels : _channelView.GetView(false); ChannelsContextMenu.Channels = PlaylistPanel.Channels; ViewChannelSplitButton.DropDown = ChannelsContextMenu; BindChannelPlaylistPanel(); // PlaylistPanel.RefreshPlaylist(sender, e); if (channels.Count == 0) return; if (_isFirstRun) { // IF NULL, GENERATE RANDOM NUMBER AND PLAY THAT CHANNEL INDEX if (channels != null) _channel = channels[Settings.Default.SelectedChannelName] ?? channels[new Random().Next(channels.Count > 0 ? channels.Count : 0)]; _playerLoader = new PlayerLoader(_channel); _isFirstRun = false; _refreshCounter.CounterTick += (s, ea) => { RefreshCounterLabel.Text = string.Format("{0} {1}", "Refreshing in", _refreshCounter.Value); }; _refreshCounter.Start(); } UpdateVisualCues(); // fucking around w/ opacity if (ParentForm != null) ParentForm.Opacity = Settings.Default.FormOpacityValue; } private void RefreshEventlistWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Result != null) EventsContextMenu.Events = (EventCollection<Event>) e.Result; ViewEventsSplitButton.DropDown = EventsContextMenu; ViewEventsSplitButton.Enabled = true; ViewEventsSplitButton.ToolTipText = _eventsUrl; } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { var about = new AboutForm(); about.Show(this); } private void OptionsToolStripMenuItem_Click(object sender, EventArgs e) { var admin = new AdminForm(); var result = admin.ShowDialog(); } private void ViewChannelSplitButton_ButtonClick(object sender, EventArgs e) { Parallel.Invoke(() => { if (_channel != null) Components.Utilities.StartProcess(_channel.ChannelInfoUrl.AbsoluteUri); }); } private void ViewSitesSplitButton_ButtonClick(object sender, EventArgs e) { if (ViewPlaylistsSplitButton.Tag != null) { Parallel.Invoke( () => Components.Utilities.StartProcess(((Uri) ViewPlaylistsSplitButton.Tag).AbsoluteUri)); } } private void ViewChannel_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { _channel = ChannelsContextMenu.Channels[e.ClickedItem.Text.Replace(" ", "").ToLower().Trim()]; // _channel.IsSelected = true; // TESTING for (var index = 0; index < PlaylistPanel.Controls.Count; index++) { var control = PlaylistPanel.Controls[index]; if (!(control is TChannel)) continue; var c = (TChannel) control; if (_channel != null && c.Equals(_channel)) { // PlayerLoader.Load(_channel); THIS WILL PLAY THE SELECTED CHANNEL AUTOMATICALLY _channel.IsSelected = true; } else { c.IsSelected = false; } } if (_channel == null) return; ViewChannelSplitButton.Text = _channel.ChannelName; // ViewChannelSplitButton.ToolTipText = _channel.ChannelInfoUrl.AbsoluteUri; ViewChannelSplitButton.Image = _channel.SiteIcon.ToBitmap(); } private void ViewChannelSplitButton_TextChanged(object sender, EventArgs e) { if (_channel != null) ViewChannelSplitButton.ToolTipText = _channel.ChannelInfoUrl.AbsoluteUri; } private void ViewEventsSplitButton_ButtonClick(object sender, EventArgs e) { Parallel.Invoke(() => Components.Utilities.StartProcess(_eventsUrl)); } // powerful pattern private void PlaylistsMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { PlaylistsContextMenu.Close(ToolStripDropDownCloseReason.ItemClicked); var playlist = e.ClickedItem as PlaylistList; if (playlist == null) return; _channelView.PlaylistTypes = playlist.PlaylistType; // temporary, i don't like this...not intuitive to have to select Custom as the playlist type if (playlist.PlaylistType == StationType.Custom) { var ff = new FavoritesForm<TChannel, TTrack>(_channelView); var result = ff.ShowDialog(); } else { if (PlaylistPanel != null) PlaylistPanel.Channels = _channelView.GetView(true); if (InvokeRequired) { Invoke((Action) (() => { BindChannelPlaylistPanel(); UpdateVisualCues(); if (ViewPlaylistsSplitButton == null) return; ViewPlaylistsSplitButton.Text = playlist.Name; ViewPlaylistsSplitButton.Image = playlist.Image; ViewPlaylistsSplitButton.Tag = playlist.SiteUri; // HACK ViewPlaylistsSplitButton.ToolTipText = playlist.SiteUri.AbsoluteUri; })); } else { BindChannelPlaylistPanel(); UpdateVisualCues(); if (ViewPlaylistsSplitButton != null) { ViewPlaylistsSplitButton.Text = playlist.Name; ViewPlaylistsSplitButton.Image = playlist.Image; ViewPlaylistsSplitButton.Tag = playlist.SiteUri; // HACK ViewPlaylistsSplitButton.ToolTipText = playlist.SiteUri.AbsoluteUri; } } } } private void SortPlaylist_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (_channelView != null) { _channelView.SortBy = SortContextMenu.SortBy; if (PlaylistPanel != null) { PlaylistPanel.Channels = _channelView.Channels; PlaylistPanel.Refresh(); } } BeginInvoke((Action) (() => { if (SortPlaylistSplitButton != null) SortPlaylistSplitButton.Text = e.ClickedItem.Text; // SortPlaylist_Click(sender, e); })); UpdateVisualCues(); } // implement private void SortPlaylist_ButtonClick(object sender, EventArgs e) { } private void PlayerType_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { BeginInvoke((Action) (() => { if (PlayerTypeSplitButton != null) PlayerTypeSplitButton.Text = e.ClickedItem.Text; if (_playerLoader != null) _playerLoader.PlayerType = DigitallyImported.Controls.Utilities.ParseEnum<PlayerType>(e.ClickedItem.Name); })); } /// <summary> /// </summary> protected internal void UpdateVisualCues() { if (PlaylistPanel != null) { PlaylistPanel.Enabled = true; if (PlaylistPanel.Channels.Count > 0) { if (_channel != null) _channel = PlaylistPanel.Channels[_channel.Name] ?? PlaylistPanel.Channels[ new Random().Next(PlaylistPanel.Channels.Count > 0 ? PlaylistPanel.Channels.Count : 0) ]; if (_channel != null) _channel.IsSelected = true; } ConnectionStatusLabel.Text = string.Format("{0} {1}", PlaylistPanel.Channels.Count, "channels loaded"); } ViewChannelSplitButton.Text = _channel.ChannelName; ViewChannelSplitButton.Image = _channel.SiteIcon.ToBitmap(); ViewPlaylistsSplitButton.Text = DigitallyImported.Controls.Utilities.GetPlaylistTypes<StationType>(Settings.Default.PlaylistTypes). ToString(); ViewPlaylistsSplitButton.Image = _channel.SiteIcon.ToBitmap(); //MainNotifyIcon.Icon = _channel.SiteIcon; if (ParentForm != null) ParentForm.Icon = _channel.SiteIcon; // do all of these need to be here? RefreshPlaylistButton.Text = "Refresh Playlist"; PlaylistRefreshProgress.Visible = false; RefreshPlaylistButton.Enabled = true; ViewChannelSplitButton.Enabled = true; ViewPlaylistsSplitButton.Enabled = true; SortPlaylistSplitButton.Enabled = true; PlayerTypeSplitButton.Enabled = true; SetTrackText(_channel.CurrentTrack); } // this method is a performance sucking machine private void BindChannelPlaylistPanel() { // if (PlaylistPanel.Controls.Count == 0 || !_channelView.IsViewSet) if (PlaylistPanel.Controls.Count == PlaylistPanel.Channels.Count) return; PlaylistPanel.Controls.Clear(); PlaylistPanel.Controls.AddRange(PlaylistPanel.Channels.ToArray()); // subscribe to the TrackChanged events here: // this will run EVERY TIME PLAYLIST IS REFRESHED...very expensive, so move elsewhere // PlaylistPanel.Channels.ForEach(delegate(TChannel channel) Parallel.ForEach<IChannel>(PlaylistPanel.Channels, channel => { channel.TrackChanged -= (s, ee) => { GC.Collect(); GC.WaitForPendingFinalizers(); }; channel.TrackChanged += (s, ee) => Invoke((Action) (() => { // first change the title of the window if ( ee.RefreshedContent.TrackTitle.Equals(_channel.CurrentTrack.TrackTitle, StringComparison. CurrentCultureIgnoreCase) && _channel.IsSelected) SetTrackText(ee.RefreshedContent); // show some toast to the user if (!Settings.Default.ShowUserToast) return; var toast = new ChannelToastForm<IChannel>(ee.RefreshedContent.ParentChannel) { TitleText = ee.RefreshedContent.ParentChannel.ChannelName, BodyText = string.Format("Track changed to {0}", ee.RefreshedContent.TrackTitle), ForeColor = Color.Black }; toast.Notify(); })); channel.Tracks[0].ee -= (s, ee) => { GC.Collect(); GC.WaitForPendingFinalizers(); }; channel.Tracks[0].ee += (s, ee) => Invoke((Action) (() => { var toast = new CommentToastForm<IChannel>(ee.RefreshedContent.ParentChannel) { TitleText = ee.RefreshedContent.ParentChannel.ChannelName, BodyText = string.Format("{0} new comments for track {1}", ee.NewComments, ee.RefreshedContent.TrackTitle), ForeColor = Color.Black }; toast.Notify(); })); }); foreach (var control in PlaylistPanel.Controls) { if (!(control is TChannel)) continue; ((Channel) control).PlaylistHistoryClicked -= (sender, e) => { }; ((Channel) control).PlaylistHistoryClicked += (sender, e) => { var channel = sender as TChannel; if (channel == null) return; if (_trackHistory == null) { _trackHistory = new HistoryForm(channel); _trackHistory.Show(); } else { _trackHistory.Channel = channel; _trackHistory.Show(); } _trackHistory.Activate(); // _trackHistory.Location = this.PointToScreen(this.PlaylistPanel.Controls[((Control)c).Name].Location); }; } } private void SetTrackText(ITrack track) { if (track == null) throw new ArgumentNullException("track"); var displayText = string.Format("{0} {1} {2}", track.ParentChannel.ChannelName, P.Resources.ColonSeparator, track.TrackTitle); MainNotifyIcon.Text = (displayText.Length > 63) ? displayText.Remove(63) : displayText; if (ParentForm != null) ParentForm.Text = displayText; } private void ExitApplication(object sender, EventArgs e) { Dispose(); Application.Exit(); } /// <summary> /// </summary> /// <param name="keyData"> </param> /// <returns> </returns> protected override bool ProcessDialogKey(Keys keyData) { if (!keyData.Equals(Keys.F5)) return false; RefreshPlaylistButton.PerformClick(); return true; } private void FeedbackButton_Click(object sender, EventArgs e) { Components.Utilities.StartProcess(P.Resources.SupportPageUrl); } private void DISiteUnavailable() { if (InvokeRequired) { BeginInvoke((Action) (() => { ConnectionStatusLabel.Visible = false; PlaylistRefreshProgress.Visible = false; ExceptionStatusMessage.Visible = true; ExceptionStatusMessage.Text = serviceOfflineMessage; })); } else { ConnectionStatusLabel.Visible = false; PlaylistRefreshProgress.Visible = false; ExceptionStatusMessage.Visible = true; ExceptionStatusMessage.Text = serviceOfflineMessage; } } } }
using Mvc.Datatables.Reflection; using System; using System.Collections.Generic; namespace Mvc.Datatables.Processing { public static class TypeFilters { private static readonly Func<string, Type, object> ParseValue = (input, t) => t.IsEnum ? Enum.Parse(t, input) : Convert.ChangeType(input, t); internal static string FilterMethod(string q, List<object> parametersForLinqQuery, Type type) { Func<string, string, string> makeClause = (method, query) => { parametersForLinqQuery.Add(ParseValue(query, type)); var indexOfParameter = parametersForLinqQuery.Count - 1; return string.Format("{0}(@{1})", method, indexOfParameter); }; if (q.StartsWith("^")) { if (q.EndsWith("$")) { parametersForLinqQuery.Add(ParseValue(q.Substring(1, q.Length - 2), type)); var indexOfParameter = parametersForLinqQuery.Count - 1; return string.Format("Equals((object)@{0})", indexOfParameter); } return makeClause("StartsWith", q.Substring(1)); } else { if (q.EndsWith("$")) { return makeClause("EndsWith", q.Substring(0, q.Length - 1)); } return makeClause("Contains", q); } } public static string NumericFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query.StartsWith("^")) query = query.TrimStart('^'); if (query.EndsWith("$")) query = query.TrimEnd('$'); if (query == "~") return string.Empty; if (query.Contains("~")) { var parts = query.Split('~'); var clause = null as string; try { parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[0])); clause = string.Format("{0} >= @{1}", columnname, parametersForLinqQuery.Count - 1); } catch (FormatException) { } try { parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[1])); if (clause != null) clause += " and "; clause += string.Format("{0} <= @{1}", columnname, parametersForLinqQuery.Count - 1); } catch (FormatException) { } return clause ?? "true"; } else { try { parametersForLinqQuery.Add(ChangeType(propertyInfo, query)); return string.Format("{0} == @{1}", columnname, parametersForLinqQuery.Count - 1); } catch (FormatException) { } return null; } } private static object ChangeType(DataTablesPropertyInfo propertyInfo, string query) { if (propertyInfo.PropertyInfo.PropertyType.IsGenericType && propertyInfo.Type.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type u = Nullable.GetUnderlyingType(propertyInfo.Type); return Convert.ChangeType(query, u); } else { return Convert.ChangeType(query, propertyInfo.Type); } } public static string DateTimeOffsetFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query == "~") return string.Empty; if (query.Contains("~")) { var parts = query.Split('~'); var filterString = null as string; DateTimeOffset start, end; if (DateTimeOffset.TryParse(parts[0] ?? "", out start)) { filterString = columnname + " >= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(start); } if (DateTimeOffset.TryParse(parts[1] ?? "", out end)) { filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(end); } return filterString ?? ""; } else { return string.Format("{1}.ToLocalTime().ToString(\"g\").{0}", FilterMethod(query, parametersForLinqQuery, propertyInfo.Type), columnname); } } public static string DateTimeFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query == "~") return string.Empty; if (query.Contains("~")) { var parts = query.Split('~'); var filterString = null as string; DateTime start, end; if (DateTime.TryParse(parts[0] ?? "", out start)) { filterString = columnname + " >= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(start); } if (DateTime.TryParse(parts[1] ?? "", out end)) { filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(end); } return filterString ?? ""; } else { return string.Format("{1}.ToLocalTime().ToString(\"g\").{0}", FilterMethod(query, parametersForLinqQuery, propertyInfo.Type), columnname); } } public static string BoolFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query != null) query = query.TrimStart('^').TrimEnd('$'); var lowerCaseQuery = query.ToLowerInvariant(); if (lowerCaseQuery == "false" || lowerCaseQuery == "true") { if (query.ToLower() == "true") return columnname + " == true"; return columnname + " == false"; } if (propertyInfo.Type == typeof(bool?)) { if (lowerCaseQuery == "null") return columnname + " == null"; } return null; } public static string StringFilter(string q, string columnname, DataTablesPropertyInfo columntype, List<object> parametersforlinqquery) { if (q == ".*") return ""; if (q.StartsWith("^")) { if (q.EndsWith("$")) { parametersforlinqquery.Add(q.Substring(1, q.Length - 2)); var parameterArg = "@" + (parametersforlinqquery.Count - 1); return string.Format("{0} == {1}", columnname, parameterArg); } else { parametersforlinqquery.Add(q.Substring(1)); var parameterArg = "@" + (parametersforlinqquery.Count - 1); return string.Format("({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1})))", columnname, parameterArg); } } else { parametersforlinqquery.Add(q); var parameterArg = "@" + (parametersforlinqquery.Count - 1); //return string.Format("{0} == {1}", columnname, parameterArg); return string.Format( "({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1}) || {0}.Contains({1})))", columnname, parameterArg); } } public static string EnumFilter(string q, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (q.StartsWith("^")) q = q.Substring(1); if (q.EndsWith("$")) q = q.Substring(0, q.Length - 1); parametersForLinqQuery.Add(ParseValue(q, propertyInfo.Type)); return columnname + " == @" + (parametersForLinqQuery.Count - 1); } } }
namespace android.widget { [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.ExpandableListAdapter_))] public interface ExpandableListAdapter : global::MonoJavaBridge.IJavaObject { bool isEmpty(); void registerDataSetObserver(android.database.DataSetObserver arg0); void unregisterDataSetObserver(android.database.DataSetObserver arg0); long getGroupId(int arg0); bool areAllItemsEnabled(); bool hasStableIds(); int getGroupCount(); int getChildrenCount(int arg0); global::java.lang.Object getGroup(int arg0); global::java.lang.Object getChild(int arg0, int arg1); long getChildId(int arg0, int arg1); global::android.view.View getGroupView(int arg0, bool arg1, android.view.View arg2, android.view.ViewGroup arg3); global::android.view.View getChildView(int arg0, int arg1, bool arg2, android.view.View arg3, android.view.ViewGroup arg4); bool isChildSelectable(int arg0, int arg1); void onGroupExpanded(int arg0); void onGroupCollapsed(int arg0); long getCombinedChildId(long arg0, long arg1); long getCombinedGroupId(long arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.ExpandableListAdapter))] public sealed partial class ExpandableListAdapter_ : java.lang.Object, ExpandableListAdapter { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ExpandableListAdapter_() { InitJNI(); } internal ExpandableListAdapter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _isEmpty11211; bool android.widget.ExpandableListAdapter.isEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._isEmpty11211); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._isEmpty11211); } internal static global::MonoJavaBridge.MethodId _registerDataSetObserver11212; void android.widget.ExpandableListAdapter.registerDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._registerDataSetObserver11212, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._registerDataSetObserver11212, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterDataSetObserver11213; void android.widget.ExpandableListAdapter.unregisterDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._unregisterDataSetObserver11213, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._unregisterDataSetObserver11213, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGroupId11214; long android.widget.ExpandableListAdapter.getGroupId(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getGroupId11214, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getGroupId11214, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _areAllItemsEnabled11215; bool android.widget.ExpandableListAdapter.areAllItemsEnabled() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._areAllItemsEnabled11215); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._areAllItemsEnabled11215); } internal static global::MonoJavaBridge.MethodId _hasStableIds11216; bool android.widget.ExpandableListAdapter.hasStableIds() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._hasStableIds11216); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._hasStableIds11216); } internal static global::MonoJavaBridge.MethodId _getGroupCount11217; int android.widget.ExpandableListAdapter.getGroupCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getGroupCount11217); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getGroupCount11217); } internal static global::MonoJavaBridge.MethodId _getChildrenCount11218; int android.widget.ExpandableListAdapter.getChildrenCount(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getChildrenCount11218, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getChildrenCount11218, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getGroup11219; global::java.lang.Object android.widget.ExpandableListAdapter.getGroup(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getGroup11219, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getGroup11219, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getChild11220; global::java.lang.Object android.widget.ExpandableListAdapter.getChild(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getChild11220, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getChild11220, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getChildId11221; long android.widget.ExpandableListAdapter.getChildId(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getChildId11221, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getChildId11221, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getGroupView11222; global::android.view.View android.widget.ExpandableListAdapter.getGroupView(int arg0, bool arg1, android.view.View arg2, android.view.ViewGroup arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getGroupView11222, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getGroupView11222, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _getChildView11223; global::android.view.View android.widget.ExpandableListAdapter.getChildView(int arg0, int arg1, bool arg2, android.view.View arg3, android.view.ViewGroup arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getChildView11223, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getChildView11223, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _isChildSelectable11224; bool android.widget.ExpandableListAdapter.isChildSelectable(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._isChildSelectable11224, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._isChildSelectable11224, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onGroupExpanded11225; void android.widget.ExpandableListAdapter.onGroupExpanded(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._onGroupExpanded11225, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._onGroupExpanded11225, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onGroupCollapsed11226; void android.widget.ExpandableListAdapter.onGroupCollapsed(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._onGroupCollapsed11226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._onGroupCollapsed11226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCombinedChildId11227; long android.widget.ExpandableListAdapter.getCombinedChildId(long arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getCombinedChildId11227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getCombinedChildId11227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getCombinedGroupId11228; long android.widget.ExpandableListAdapter.getCombinedGroupId(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_._getCombinedGroupId11228, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.ExpandableListAdapter_.staticClass, global::android.widget.ExpandableListAdapter_._getCombinedGroupId11228, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListAdapter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListAdapter")); global::android.widget.ExpandableListAdapter_._isEmpty11211 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "isEmpty", "()Z"); global::android.widget.ExpandableListAdapter_._registerDataSetObserver11212 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "registerDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.widget.ExpandableListAdapter_._unregisterDataSetObserver11213 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "unregisterDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.widget.ExpandableListAdapter_._getGroupId11214 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getGroupId", "(I)J"); global::android.widget.ExpandableListAdapter_._areAllItemsEnabled11215 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "areAllItemsEnabled", "()Z"); global::android.widget.ExpandableListAdapter_._hasStableIds11216 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "hasStableIds", "()Z"); global::android.widget.ExpandableListAdapter_._getGroupCount11217 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getGroupCount", "()I"); global::android.widget.ExpandableListAdapter_._getChildrenCount11218 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getChildrenCount", "(I)I"); global::android.widget.ExpandableListAdapter_._getGroup11219 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getGroup", "(I)Ljava/lang/Object;"); global::android.widget.ExpandableListAdapter_._getChild11220 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getChild", "(II)Ljava/lang/Object;"); global::android.widget.ExpandableListAdapter_._getChildId11221 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getChildId", "(II)J"); global::android.widget.ExpandableListAdapter_._getGroupView11222 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getGroupView", "(IZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.ExpandableListAdapter_._getChildView11223 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getChildView", "(IIZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.ExpandableListAdapter_._isChildSelectable11224 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "isChildSelectable", "(II)Z"); global::android.widget.ExpandableListAdapter_._onGroupExpanded11225 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "onGroupExpanded", "(I)V"); global::android.widget.ExpandableListAdapter_._onGroupCollapsed11226 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "onGroupCollapsed", "(I)V"); global::android.widget.ExpandableListAdapter_._getCombinedChildId11227 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getCombinedChildId", "(JJ)J"); global::android.widget.ExpandableListAdapter_._getCombinedGroupId11228 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListAdapter_.staticClass, "getCombinedGroupId", "(J)J"); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PublicIPAddressesOperations. /// </summary> public static partial class PublicIPAddressesOperationsExtensions { /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> public static void Delete(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName) { operations.DeleteAsync(resourceGroupName, publicIpAddressName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified public IP address in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> public static PublicIPAddress Get(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, publicIpAddressName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified public IP address in a specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PublicIPAddress> GetAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address operation. /// </param> public static PublicIPAddress CreateOrUpdate(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, publicIpAddressName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PublicIPAddress> CreateOrUpdateAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<PublicIPAddress> ListAll(this IPublicIPAddressesOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PublicIPAddress>> ListAllAsync(this IPublicIPAddressesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<PublicIPAddress> List(this IPublicIPAddressesOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PublicIPAddress>> ListAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> public static void BeginDelete(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName) { operations.BeginDeleteAsync(resourceGroupName, publicIpAddressName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address operation. /// </param> public static PublicIPAddress BeginCreateOrUpdate(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, publicIpAddressName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PublicIPAddress> BeginCreateOrUpdateAsync(this IPublicIPAddressesOperations operations, string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<PublicIPAddress> ListAllNext(this IPublicIPAddressesOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PublicIPAddress>> ListAllNextAsync(this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<PublicIPAddress> ListNext(this IPublicIPAddressesOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PublicIPAddress>> ListNextAsync(this IPublicIPAddressesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * PolicyLevel.cs - Implementation of the * "System.Security.Policy.PolicyLevel" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Policy { #if CONFIG_POLICY_OBJECTS using System.Collections; [Serializable] public sealed class PolicyLevel { // Internal state. private ArrayList fullTrustAssemblies; private String label; private ArrayList namedPermissionSets; private CodeGroup rootCodeGroup; private String storeLocation; // Constructor. internal PolicyLevel(String label) { this.label = label; fullTrustAssemblies = new ArrayList(); namedPermissionSets = new ArrayList(); rootCodeGroup = DefaultRootCodeGroup(); } // Properties. public IList FullTrustAssemblies { get { return new ArrayList(fullTrustAssemblies); } } public String Label { get { return label; } } public IList NamedPermissionSets { get { ArrayList list = new ArrayList(); foreach(NamedPermissionSet pSet in namedPermissionSets) { list.Add(pSet.Copy()); } return list; } } public CodeGroup RootCodeGroup { get { return rootCodeGroup; } set { if(value == null) { throw new ArgumentNullException("value"); } rootCodeGroup = value.Copy(); } } public String StoreLocation { get { return storeLocation; } } // Add an entry to the "full trust assembly" list. public void AddFullTrustAssembly(StrongName sn) { if(sn == null) { throw new ArgumentNullException("sn"); } AddFullTrustAssembly (new StrongNameMembershipCondition (sn.PublicKey, sn.Name, sn.Version)); } public void AddFullTrustAssembly(StrongNameMembershipCondition snMC) { if(snMC == null) { throw new ArgumentNullException("snMC"); } if(fullTrustAssemblies.Contains(snMC)) { throw new ArgumentException (_("Security_FullTrustPresent")); } fullTrustAssemblies.Add(snMC); } #if CONFIG_PERMISSIONS // Add an entry to the "named permission sets" list. public void AddNamedPermissionSet(NamedPermissionSet permSet) { if(permSet == null) { throw new ArgumentNullException("permSet"); } namedPermissionSets.Add(permSet); } // Change a named permission set. public NamedPermissionSet ChangeNamedPermissionSet (String name, PermissionSet pSet) { // Validate the parameters. if(name == null) { throw new ArgumentNullException("name"); } if(pSet == null) { throw new ArgumentNullException("pSet"); } // Find the existing permission set with this name. NamedPermissionSet current = GetNamedPermissionSet(name); if(current == null) { throw new ArgumentException (_("Security_PermissionSetNotFound")); } // Make a copy of the previous permission set. NamedPermissionSet prev = (NamedPermissionSet)(current.Copy()); // Clear the permission set and recreate it from "pSet". current.CopyFrom(pSet); // Return the previsou permission set. return prev; } // Get a specific named permission set. public NamedPermissionSet GetNamedPermissionSet(String name) { if(name == null) { throw new ArgumentNullException("name"); } foreach(NamedPermissionSet set in namedPermissionSets) { if(set.Name == name) { return set; } } return null; } // Remove a named permission set. public NamedPermissionSet RemoveNamedPermissionSet (NamedPermissionSet permSet) { if(permSet == null) { throw new ArgumentNullException("permSet"); } return RemoveNamedPermissionSet(permSet.Name); } public NamedPermissionSet RemoveNamedPermissionSet(String name) { // Validate the parameter. if(name == null) { throw new ArgumentNullException("name"); } // Find the existing permission set with this name. NamedPermissionSet current = GetNamedPermissionSet(name); if(current == null) { throw new ArgumentException (_("Security_PermissionSetNotFound")); } // Remove the permission set from the list. namedPermissionSets.Remove(current); // Return the permission set that was removed. return current; } #endif // CONFIG_PERMISSIONS // Create a policy level object for the current application domain. public static PolicyLevel CreateAppDomainLevel() { return new PolicyLevel("AppDomain"); } // Load policy information from an XML element. [TODO] public void FromXml(SecurityElement e) { // TODO } // Recover the last backed-up policy configuration. public void Recover() { // Nothing to do here: we don't support backups. } // Remove an entry from the "full trust assembly" list. public void RemoveFullTrustAssembly(StrongName sn) { if(sn == null) { throw new ArgumentNullException("sn"); } RemoveFullTrustAssembly (new StrongNameMembershipCondition (sn.PublicKey, sn.Name, sn.Version)); } public void RemoveFullTrustAssembly(StrongNameMembershipCondition snMC) { if(snMC == null) { throw new ArgumentNullException("snMC"); } if(fullTrustAssemblies.Contains(snMC)) { fullTrustAssemblies.Remove(snMC); } else { throw new ArgumentException (_("Security_FullTrustNotPresent")); } } // Create the default root code group. private CodeGroup DefaultRootCodeGroup() { UnionCodeGroup group = new UnionCodeGroup (new AllMembershipCondition(), null); group.Name = "All_Code"; group.Description = _("Security_RootGroupDescription"); return group; } // Reset to the default state. public void Reset() { fullTrustAssemblies.Clear(); namedPermissionSets.Clear(); rootCodeGroup = DefaultRootCodeGroup(); } // Resolve policy information based on supplied evidence. [TODO] public PolicyStatement Resolve(Evidence evidence) { if(evidence == null) { throw new ArgumentNullException("evidence"); } // TODO return null; } public CodeGroup ResolveMatchingCodeGroups(Evidence evidence) { if(evidence == null) { throw new ArgumentNullException("evidence"); } return RootCodeGroup.ResolveMatchingCodeGroups(evidence); } // Convert this object into an XML element. [TODO] public SecurityElement ToXml() { // TODO return null; } }; // class PolicyLevel #endif // CONFIG_POLICY_OBJECTS }; // namespace System.Security.Policy
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Razor.Editor; using Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Test.Framework; using Microsoft.AspNet.Razor.Text; using Xunit; namespace Microsoft.AspNet.Razor.Test.Parser.Html { public class HtmlUrlAttributeTest : CsHtmlMarkupParserTestBase { [Fact] public void SimpleUrlInAttributeInMarkupBlock() { ParseBlockTest("<a href='~/Foo/Bar/Baz' />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 2, 0, 2), new LocationTagged<string>("'", 22, 0, 22)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo/Bar/Baz") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" />").Accepts(AcceptedCharacters.None))); } [Fact] public void SimpleUrlInAttributeInMarkupDocument() { ParseDocumentTest("<a href='~/Foo/Bar/Baz' />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 2, 0, 2), new LocationTagged<string>("'", 22, 0, 22)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo/Bar/Baz") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" />"))); } [Fact] public void SimpleUrlInAttributeInMarkupSection() { ParseDocumentTest("@section Foo { <a href='~/Foo/Bar/Baz' /> }", new MarkupBlock( Factory.EmptyHtml(), new SectionBlock(new SectionCodeGenerator("Foo"), Factory.CodeTransition(), Factory.MetaCode("section Foo {") .AutoCompleteWith(null, atEndOfSpan: true) .Accepts(AcceptedCharacters.Any), new MarkupBlock( Factory.Markup(" <a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 17, 0, 17), new LocationTagged<string>("'", 37, 0, 37)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo/Bar/Baz") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 24, 0, 24), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 24, 0, 24))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" /> ")), Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), Factory.EmptyHtml())); } [Fact] public void UrlWithExpressionsInAttributeInMarkupBlock() { ParseBlockTest("<a href='~/Foo/@id/Baz' />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 2, 0, 2), new LocationTagged<string>("'", 22, 0, 22)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo/") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))), new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), 15, 0, 15), new ExpressionBlock( Factory.CodeTransition().Accepts(AcceptedCharacters.None), Factory.Code("id") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace))), Factory.Markup("/Baz") .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 18, 0, 18), new LocationTagged<string>("/Baz", 18, 0, 18))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" />").Accepts(AcceptedCharacters.None))); } [Fact] public void UrlWithExpressionsInAttributeInMarkupDocument() { ParseDocumentTest("<a href='~/Foo/@id/Baz' />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 2, 0, 2), new LocationTagged<string>("'", 22, 0, 22)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo/") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))), new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), 15, 0, 15), new ExpressionBlock( Factory.CodeTransition().Accepts(AcceptedCharacters.None), Factory.Code("id") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace))), Factory.Markup("/Baz") .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 18, 0, 18), new LocationTagged<string>("/Baz", 18, 0, 18))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" />"))); } [Fact] public void UrlWithExpressionsInAttributeInMarkupSection() { ParseDocumentTest("@section Foo { <a href='~/Foo/@id/Baz' /> }", new MarkupBlock( Factory.EmptyHtml(), new SectionBlock(new SectionCodeGenerator("Foo"), Factory.CodeTransition(), Factory.MetaCode("section Foo {") .AutoCompleteWith(null, atEndOfSpan: true), new MarkupBlock( Factory.Markup(" <a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 17, 0, 17), new LocationTagged<string>("'", 37, 0, 37)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo/") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 24, 0, 24), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 24, 0, 24))), new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 30, 0, 30), 30, 0, 30), new ExpressionBlock( Factory.CodeTransition().Accepts(AcceptedCharacters.None), Factory.Code("id") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace))), Factory.Markup("/Baz") .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 33, 0, 33), new LocationTagged<string>("/Baz", 33, 0, 33))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" /> ")), Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), Factory.EmptyHtml())); } [Fact] public void UrlWithComplexCharactersInAttributeInMarkupBlock() { ParseBlockTest("<a href='~/Foo+Bar:Baz(Biz),Boz' />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 2, 0, 2), new LocationTagged<string>("'", 31, 0, 31)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo+Bar:Baz(Biz),Boz") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" />").Accepts(AcceptedCharacters.None))); } [Fact] public void UrlWithComplexCharactersInAttributeInMarkupDocument() { ParseDocumentTest("<a href='~/Foo+Bar:Baz(Biz),Boz' />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href='", 2, 0, 2), new LocationTagged<string>("'", 31, 0, 31)), Factory.Markup(" href='").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo+Bar:Baz(Biz),Boz") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" />"))); } [Fact] public void UrlInUnquotedAttributeValueInMarkupBlock() { ParseBlockTest("<a href=~/Foo+Bar:Baz(Biz),Boz/@id/Boz />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href=", 2, 0, 2), new LocationTagged<string>(String.Empty, 38, 0, 38)), Factory.Markup(" href=").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo+Bar:Baz(Biz),Boz/") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 8, 0, 8), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 8, 0, 8))), new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 31, 0, 31), 31, 0, 31), new ExpressionBlock( Factory.CodeTransition() .Accepts(AcceptedCharacters.None), Factory.Code("id") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace))), Factory.Markup("/Boz").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 34, 0, 34), new LocationTagged<string>("/Boz", 34, 0, 34)))), Factory.Markup(" />").Accepts(AcceptedCharacters.None))); } [Fact] public void UrlInUnquotedAttributeValueInMarkupDocument() { ParseDocumentTest("<a href=~/Foo+Bar:Baz(Biz),Boz/@id/Boz />", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href=", 2, 0, 2), new LocationTagged<string>(String.Empty, 38, 0, 38)), Factory.Markup(" href=").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo+Bar:Baz(Biz),Boz/") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 8, 0, 8), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 8, 0, 8))), new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 31, 0, 31), 31, 0, 31), new ExpressionBlock( Factory.CodeTransition() .Accepts(AcceptedCharacters.None), Factory.Code("id") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace))), Factory.Markup("/Boz").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 34, 0, 34), new LocationTagged<string>("/Boz", 34, 0, 34)))), Factory.Markup(" />"))); } [Fact] public void UrlInUnquotedAttributeValueInMarkupSection() { ParseDocumentTest("@section Foo { <a href=~/Foo+Bar:Baz(Biz),Boz/@id/Boz /> }", new MarkupBlock( Factory.EmptyHtml(), new SectionBlock(new SectionCodeGenerator("Foo"), Factory.CodeTransition(), Factory.MetaCode("section Foo {") .AutoCompleteWith(null, atEndOfSpan: true), new MarkupBlock( Factory.Markup(" <a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href=", 17, 0, 17), new LocationTagged<string>(String.Empty, 53, 0, 53)), Factory.Markup(" href=").With(SpanCodeGenerator.Null), Factory.Markup("~/Foo+Bar:Baz(Biz),Boz/") .WithEditorHints(EditorHints.VirtualPath) .With(new LiteralAttributeCodeGenerator( new LocationTagged<string>(String.Empty, 23, 0, 23), new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 23, 0, 23))), new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 46, 0, 46), 46, 0, 46), new ExpressionBlock( Factory.CodeTransition() .Accepts(AcceptedCharacters.None), Factory.Code("id") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace))), Factory.Markup("/Boz").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 49, 0, 49), new LocationTagged<string>("/Boz", 49, 0, 49)))), Factory.Markup(" /> ")), Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), Factory.EmptyHtml())); } } }
using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using NUnit.Framework; using UnityEngine.TestTools; using Firebase.Firestore; using static Tests.TestAsserts; namespace Tests { // Tests for mutation operations of Firestore: set, update, mutating fieldValue, etc. public class MutationTests : FirestoreIntegrationTests { [UnityTest] public IEnumerator TestDeleteDocument() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "f1", "v1" }, }; yield return AwaitSuccess(doc.SetAsync(data)); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); DocumentSnapshot snap = getTask.Result; Assert.That(snap.Exists, "Written document should exist"); var deleteTask = doc.DeleteAsync(); yield return AwaitSuccess(deleteTask); getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); snap = getTask.Result; Assert.That(!snap.Exists, "Deleted document should not exist"); Assert.That(snap.ToDictionary(), Is.Null); } [UnityTest] public IEnumerator TestWriteDocument() { DocumentReference doc = TestDocument(); Dictionary<string, object> data = TestData(); yield return AwaitSuccess(doc.SetAsync(data)); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); DocumentSnapshot snap = getTask.Result; Assert.That(snap.ToDictionary(), Is.EquivalentTo(data)); } [UnityTest] public IEnumerator TestWriteDocumentViaCollection() { var addTask = TestCollection().AddAsync(TestData()); yield return AwaitSuccess(addTask); var getTask = addTask.Result.GetSnapshotAsync(); yield return AwaitSuccess(getTask); DocumentSnapshot snap = getTask.Result; Assert.That(snap.ToDictionary(), Is.EquivalentTo(TestData())); } [UnityTest] public IEnumerator TestWriteInvalidDocumentFails() { var collectionWithInvalidName = TestCollection().Document("__badpath__").Collection("sub"); var addTask = collectionWithInvalidName.AddAsync(TestData()); yield return AwaitFaults(addTask); } [UnityTest] public IEnumerator TestWriteDocumentWithIntegersSaveAsLongs() { DocumentReference doc = db.Collection("col2").Document(); var data = new Dictionary<string, object> { { "f1", 2 }, { "map", new Dictionary<string, object> { { "nested f3", 4 }, } }, }; var expected = new Dictionary<string, object> { { "f1", 2L }, { "map", new Dictionary<string, object> { { "nested f3", 4L }, } }, }; yield return AwaitSuccess(doc.SetAsync(data)); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); var actual = getTask.Result.ToDictionary(); Assert.That(actual, Is.EquivalentTo(expected)); } [UnityTest] public IEnumerator TestUpdateDocument() { DocumentReference doc = TestDocument(); var data = TestData(); var updateData = new Dictionary<string, object> { { "name", "foo" }, { "metadata.createdAt", 42L } }; var expected = TestData(); expected["name"] = "foo"; ((Dictionary<string, object>)expected["metadata"])["createdAt"] = 42L; yield return AwaitSuccess(doc.SetAsync(data)); yield return AwaitSuccess(doc.UpdateAsync(updateData)); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); DocumentSnapshot snap = getTask.Result; var actual = snap.ToDictionary(); Assert.That(actual, Is.EquivalentTo(expected)); } [UnityTest] // See b/174676322 for why this test is added. public IEnumerator TestMultipleDeletesInOneUpdate() { DocumentReference doc = TestDocument(); var setTask = doc.SetAsync(new Dictionary<string, object> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" }, { "key4", "value4" }, { "key5", "value5" }, }); yield return AwaitSuccess(setTask); var updateTask = doc.UpdateAsync(new Dictionary<string, object> { { "key1", FieldValue.Delete }, { "key3", FieldValue.Delete }, { "key5", FieldValue.Delete }, }); yield return AwaitSuccess(updateTask); var getTask = doc.GetSnapshotAsync(Source.Cache); yield return AwaitSuccess(getTask); DocumentSnapshot snapshot = getTask.Result; var expected = new Dictionary<string, object> { { "key2", "value2" }, { "key4", "value4" }, }; Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(expected)); } [UnityTest] public IEnumerator TestUpdateFieldInDocument() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "f1", "v1" }, { "f2", "v2" }, }; yield return AwaitSuccess(doc.SetAsync(data)); yield return AwaitSuccess(doc.UpdateAsync("f2", "v2b")); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); var actual = getTask.Result.ToDictionary(); var expected = new Dictionary<string, object> { { "f1", "v1" }, { "f2", "v2b" }, }; Assert.That(actual, Is.EquivalentTo(expected)); } [UnityTest] public IEnumerator TestCreateViaArrayUnion() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L) } }; yield return AwaitSuccess(doc.SetAsync(data)); yield return AssertExpectedDocument( doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 2L } } }); } [UnityTest] public IEnumerator TestAppendViaUpdateArrayUnion() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L) } }; yield return AwaitSuccess(doc.SetAsync(data)); data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 4L) } }; yield return AwaitSuccess(doc.UpdateAsync(data)); yield return AssertExpectedDocument( doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 2L, 4L } } }); } [UnityTest] public IEnumerator TestAppendViaSetMergeArrayUnion() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L) } }; yield return AwaitSuccess(doc.SetAsync(data)); data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(2L, 3L) } }; yield return AwaitSuccess(doc.SetAsync(data, SetOptions.MergeAll)); yield return AssertExpectedDocument( doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 2L, 3L } } }); } [UnityTest] public IEnumerator TestAppendObjectViaUpdateArrayUnion() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L) } }; yield return AwaitSuccess(doc.SetAsync(data)); data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, new Dictionary<string, object> { { "a", "value" } }) } }; AwaitSuccess(doc.UpdateAsync(data)); yield return AssertExpectedDocument(doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 2L, new Dictionary<string, object> { { "a", "value" } } } } }); } [UnityTest] public IEnumerator TestRemoveViaUpdateArrayRemove() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L) } }; yield return AwaitSuccess(doc.SetAsync(data)); data = new Dictionary<string, object> { { "array", FieldValue.ArrayRemove(1L, 4L) } }; AwaitSuccess(doc.UpdateAsync(data)); yield return AssertExpectedDocument( doc, new Dictionary<string, object> { { "array", new List<object> { 2L } } }); } [UnityTest] public IEnumerator TestRemoveViaSetMergeArrayRemove() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L, 3L) } }; yield return AwaitSuccess(doc.SetAsync(data)); data = new Dictionary<string, object> { { "array", FieldValue.ArrayRemove(1L, 3L) } }; AwaitSuccess(doc.SetAsync(data, SetOptions.MergeAll)); yield return AssertExpectedDocument( doc, new Dictionary<string, object> { { "array", new List<object> { 2L } } }); } [UnityTest] public IEnumerator TestRemoveObjectsViaUpdateArrayRemove() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, new Dictionary<string, object> { { "a", "value" } }, 3L) } }; yield return AwaitSuccess(doc.SetAsync(data)); data = new Dictionary<string, object> { { "array", FieldValue.ArrayRemove(new Dictionary<string, object> { { "a", "value" } }) } }; AwaitSuccess(doc.UpdateAsync(data)); yield return AssertExpectedDocument( doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 3L } } }); } [UnityTest] public IEnumerator TestUpdateFieldPath() { DocumentReference doc = TestDocument(); var data = new Dictionary<string, object> { { "f1", "v1" }, { "f2", new Dictionary<string, object> { { "a", new Dictionary<string, object> { { "b", new Dictionary<string, object> { { "c", "v2" }, } }, } }, } }, }; var updateData = new Dictionary<FieldPath, object> { { new FieldPath("f2", "a", "b", "c"), "v2b" }, { new FieldPath("f2", "x", "y", "z"), "v3" }, }; var expected = new Dictionary<string, object> { { "f1", "v1" }, { "f2", new Dictionary<string, object> { { "a", new Dictionary<string, object> { { "b", new Dictionary<string, object> { { "c", "v2b" }, } }, } }, { "x", new Dictionary<string, object> { { "y", new Dictionary<string, object> { { "z", "v3" }, } }, } }, } }, }; yield return AwaitSuccess(doc.SetAsync(data)); yield return AwaitSuccess(doc.UpdateAsync(updateData)); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); var actual = getTask.Result.ToDictionary(); Assert.That(actual, Is.EquivalentTo(expected)); } [UnityTest] public IEnumerator TestSetOptions() { DocumentReference doc = TestDocument(); var initialData = new Dictionary<string, object> { { "field1", "value1" }, }; var set1 = new Dictionary<string, object> { { "field2", "value2" } }; var setOptions1 = SetOptions.MergeAll; var set2 = new Dictionary<string, object> { { "field3", "value3" }, { "not-field4", "not-value4" } }; var setOptions2 = SetOptions.MergeFields("field3"); var set3 = new Dictionary<string, object> { { "field4", "value4" }, { "not-field5", "not-value5" } }; var setOptions3 = SetOptions.MergeFields(new FieldPath("field4")); var expected = new Dictionary<string, object> { { "field1", "value1" }, { "field2", "value2" }, { "field3", "value3" }, { "field4", "value4" }, }; yield return AwaitSuccess(doc.SetAsync(initialData)); yield return AwaitSuccess(doc.SetAsync(set1, setOptions1)); yield return AwaitSuccess( doc.Firestore.StartBatch().Set(doc, set2, setOptions2).CommitAsync()); yield return AwaitSuccess(db.RunTransactionAsync(transaction => { transaction.Set(doc, set3, setOptions3); return Task.CompletedTask; })); var getTask = doc.GetSnapshotAsync(); yield return AwaitSuccess(getTask); Assert.That(getTask.Result.ToDictionary(), Is.EquivalentTo(expected)); } } }
/* * Naiad ver. 0.5 * 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.Linq; using System.Text; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.DataStructures; using Microsoft.Research.Naiad.Diagnostics; namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.CollectionTrace { /// <summary> /// Interface for a collection trace, which is a mapping from key indices (of type int) /// to times (interned, of type int) to records (of time R), to weights (of type int). /// /// Typically the key indices are obtained from a Operator.KeyIndices structure, which /// indicates which offsets in some internal data structure are used for the unprocessed, /// processed, etc. regions of the collection trace. /// /// Typically the time indices are obtained from a LatticeInternTable object associated with /// the enclosing operator. /// </summary> /// <typeparam name="R">Record type</typeparam> internal interface CollectionTrace<R> where R : IEquatable<R> { /// <summary> /// Introduces the given record with the given weight at a particular (key, time). /// /// After executing this method, the keyIndex may have changed. /// </summary> /// <param name="keyIndex">The index for the key to update.</param> /// <param name="record">The record to introduce.</param> /// <param name="weight">The weight of the record to introduce.</param> /// <param name="timeIndex">The index for the time to update.</param> void Introduce(ref int keyIndex, R record, Int64 weight, int timeIndex); /// <summary> /// Introduces a batch of records from a source region in this collection trace (typically /// corresponding to an unprocessed trace or a workspace) to a destination region. /// /// After executing this method, the destKeyIndex and sourceKeyIndex may have changed. /// </summary> /// <param name="destkeyIndex">The index for the destination, which will be updated.</param> /// <param name="sourceKeyIndex">The index for the source for the the update.</param> /// <param name="delete">If true, this will free the storage associated with the sourceKeyIndex.</param> void IntroduceFrom(ref int destkeyIndex, ref int sourceKeyIndex, bool delete = true); /// <summary> /// Updates dA[t] to be the negation of all strictly prior differences, where A is the given /// key region. /// /// After executing this method, the keyIndex may have changed. /// </summary> /// <param name="keyIndex">The index for the key to update.</param> /// <param name="timeIndex">The index for the time to update.</param> void SubtractStrictlyPriorDifferences(ref int keyIndex, int timeIndex); /// <summary> /// Sets the state associated with the given key to zero. /// /// After executing this method, the keyIndex may have changed. /// </summary> /// <param name="keyIndex">The index for the key to update.</param> void ZeroState(ref int keyIndex); /// <summary> /// Returns true if the state associated with the given key is zero. /// /// After executing this method, the keyIndex may have changed. /// </summary> /// <param name="keyIndex">The index for the key to interrogate.</param> /// <returns>True if the state associated with the given key is zero, otherwise false.</returns> bool IsZero(ref int keyIndex); /// <summary> /// Enumerates the entire collection for the given key at the given time, and stores it in the /// given list. /// </summary> /// <param name="keyIndex">The key to enumerate.</param> /// <param name="timeIndex">The time at which to enumerate the collection.</param> /// <param name="toFill">The list that will be populated with records in the collection.</param> void EnumerateCollectionAt(int keyIndex, int timeIndex, NaiadList<Weighted<R>> toFill); /// <summary> /// Enumerates the difference for the given key at the given time, and stores it in the given list. /// </summary> /// <param name="keyIndex">The key to enumerate.</param> /// <param name="timeIndex">The time at which to enumerate the difference.</param> /// <param name="toFill">The list that will be populated with records in the difference.</param> void EnumerateDifferenceAt(int keyIndex, int timeIndex, NaiadList<Weighted<R>> toFill); /// <summary> /// Enumerates the set of times at which the given key changes, and stores it in the given list. /// </summary> /// <param name="keyIndex">The key to enumerate.</param> /// <param name="timelist">The list that will be populated with the times at which the given key changes.</param> void EnumerateTimes(int keyIndex, NaiadList<int> timelist); /// <summary> /// Updates the state associated with the given key to reflect times that may have been advanced (with a view to compacting their state). /// </summary> /// <param name="keyIndex">The index for the key to update.</param> void EnsureStateIsCurrentWRTAdvancedTimes(ref int keyIndex); /// <summary> /// Called when the collection trace is released. Currently unused. /// </summary> void Release(); /// <summary> /// Applies eager compaction to the collection trace. /// </summary> void Compact(); } internal interface CollectionTraceCheckpointable<R> : CollectionTrace<R> where R : IEquatable<R> { void Checkpoint(NaiadWriter writer); void Restore(NaiadReader reader); } /// <summary> /// Represents a collection trace for a collection that is constant with respect to time. /// </summary> /// <typeparam name="R">The type of records stored in this trace.</typeparam> internal class CollectionTraceImmutable<R> : CollectionTraceCheckpointable<R> where R : IEquatable<R> { private class SpinedList<T> { public T[][] spine; public int Count; public void Add(T element) { if (spine[this.Count >> 16] == null) { spine[this.Count >> 16] = new T[1 << 16]; //Console.Error.WriteLine("Allocated spine[{0}]", this.Count >> 16); } spine[this.Count >> 16][this.Count % (1 << 16)] = element; this.Count++; } public T ElementAt(int index) { return spine[index >> 16][index & 0xFFFF]; } public SpinedList() { spine = new T[1 << 16][]; } } bool debug = false; private List<int> heads; // index in links of the last element with the associated key. private SpinedList<Microsoft.Research.Naiad.Pair<R, int>> links; // chain of links forming linked lists for each key. //List<List<R>> list; private int[] offsets; private R[] data; public void Introduce(ref int keyIndex, R from, Int64 weight, int timeIndex) { if (heads != null) { if (keyIndex == 0) { keyIndex = heads.Count; heads.Add(-1); } if (weight < 0) Logging.Error("Subtracting records from Immutable collection (Consolidate first?)"); for (int i = 0; i < weight; i++) { links.Add(new Microsoft.Research.Naiad.Pair<R, int>(from, heads[keyIndex])); heads[keyIndex] = links.Count - 1; } } else Logging.Error("Adding records to Immutable collection after compacting it"); } public void IntroduceFrom(ref int thisKeyIndex, ref int thatKeyIndex, bool delete = true) { if (thatKeyIndex == 0) return; if (heads != null) { if (thisKeyIndex == 0 && delete) { thisKeyIndex = thatKeyIndex; thatKeyIndex = 0; } else { int index = heads[thatKeyIndex]; while (index != -1) { Introduce(ref thisKeyIndex, links.ElementAt(index).First, 1, 0); index = links.ElementAt(index).Second; } if (delete) ZeroState(ref thatKeyIndex); } } else Logging.Error("Adding records to Immutable collection after compacting it"); } public void SubtractStrictlyPriorDifferences(ref int keyIndex, int timeIndex) { // no strictly prior differences to subtract. } public void ZeroState(ref int keyIndex) { if (keyIndex == 0) return; if (heads != null) { heads[keyIndex] = -1; keyIndex = 0; } else Logging.Error("Zeroing parts of Immutable collection after compacting it"); } public bool IsZero(ref int keyIndex) { return keyIndex == 0; } public void EnumerateCollectionAt(int keyIndex, int timeIndex, NaiadList<Weighted<R>> toFill) { toFill.Clear(); if (keyIndex != 0) { if (heads != null) { int index = heads[keyIndex]; while (index != -1) { toFill.Add(links.ElementAt(index).First.ToWeighted(1)); index = links.ElementAt(index).Second; } } else { for (int i = offsets[keyIndex - 1]; i < offsets[keyIndex]; i++) toFill.Add(data[i].ToWeighted(1)); } } } public void EnumerateDifferenceAt(int keyIndex, int timeIndex, NaiadList<Weighted<R>> toFill) { toFill.Clear(); if (keyIndex != 0) { if (heads != null) { int index = heads[keyIndex]; while (index != -1) { toFill.Add(links.ElementAt(index).First.ToWeighted(1)); index = links.ElementAt(index).Second; } } else { for (int i = offsets[keyIndex - 1]; i < offsets[keyIndex]; i++) toFill.Add(data[i].ToWeighted(1)); } } } public void EnumerateTimes(int keyIndex, NaiadList<int> timelist) { if (keyIndex != 0) { var present = false; for (int i = 0; i < timelist.Count; i++) if (timelist.Array[i] == 0) present = true; //timelist.Clear(); if (!present) timelist.Add(0); } } public void EnsureStateIsCurrentWRTAdvancedTimes(ref int state) { } public void Release() { } public void Compact() { if (heads != null) { if (debug) Console.Error.WriteLine("Compacting ImmutableTrace"); var counts = new int[heads.Count]; for (int i = 0; i < heads.Count; i++) { int index = heads[i]; while (index != -1) { counts[i]++; index = links.ElementAt(index).Second; } } offsets = new int[heads.Count]; for (int i = 1; i < offsets.Length; i++) offsets[i] = offsets[i - 1] + counts[i]; var pos = 0; data = new R[offsets[offsets.Length - 1]]; for (int i = 1; i < offsets.Length; i++) { int index = heads[i]; while (index != -1) { data[pos++] = links.ElementAt(index).First; index = links.ElementAt(index).Second; } } if (debug) Console.Error.WriteLine("Trace compacted; {0} elements to {1} elements", links.Count, data.Length); Console.Error.WriteLine("Trace compacted; {0} elements to {1} elements", links.Count, data.Length); heads = null; links = null; counts = null; } } /* Checkpoint format: * BOOL isMutable * if (isMutable) * INT headsLength * INT*headsLength heads * INT linksLength * PAIR<R,INT>*linksLength links * else * INT offsetsLength * INT*offsetsLength offsets * INT dataLength * R*dataLength data */ public void Checkpoint(NaiadWriter writer) { writer.Write(heads != null); // Is mutable flag if (heads != null) { // Still mutable writer.Write(heads.Count); foreach (int head in heads) writer.Write(head); writer.Write(links.Count); for (int i = 0; i < links.Count; i++) writer.Write(links.ElementAt(i)); } else { // Immutable writer.Write(offsets.Length); for (int i = 0; i < offsets.Length; ++i) writer.Write(offsets[i]); writer.Write(data.Length); for (int i = 0; i < data.Length; ++i) writer.Write(data[i]); } } public void Restore(NaiadReader reader) { bool isMutable = reader.Read<bool>(); if (isMutable) { int headsCount = reader.Read<int>(); this.heads = new List<int>(headsCount); for (int i = 0; i < headsCount; ++i) this.heads.Add(reader.Read<int>()); int linksCount = reader.Read<int>(); //this.links = new List<Naiad.Pair<R, int>>(linksCount); this.links = new SpinedList<Microsoft.Research.Naiad.Pair<R, int>>(); for (int i = 0; i < linksCount; ++i) this.links.Add(reader.Read<Microsoft.Research.Naiad.Pair<R, int>>()); } else { int offsetsLength = reader.Read<int>(); offsets = new int[offsetsLength]; for (int i = 0; i < offsets.Length; ++i) offsets[i] = reader.Read<int>(); int dataLength = reader.Read<int>(); data = new R[dataLength]; for (int i = 0; i < data.Length; ++i) data[i] = reader.Read<R>(); } } public bool Stateful { get { return true; } } public CollectionTraceImmutable() { if (debug) Console.Error.WriteLine("Allocated ImmutableTrace"); heads = new List<int>(); links = new SpinedList<Microsoft.Research.Naiad.Pair<R, int>>();// new List<Naiad.Pair<R, int>>(); heads.Add(-1); } } internal class CollectionTraceImmutableNoHeap<R> : CollectionTraceCheckpointable<R> where R : IEquatable<R> { public void Introduce(ref int keyIndex, R record, long weight, int timeIndex) { keyIndex += (int) weight; } public void IntroduceFrom(ref int destkeyIndex, ref int sourceKeyIndex, bool delete = true) { destkeyIndex += sourceKeyIndex; if (delete) sourceKeyIndex = 0; } public void SubtractStrictlyPriorDifferences(ref int keyIndex, int timeIndex) { } public void ZeroState(ref int keyIndex) { keyIndex = 0; } public bool IsZero(ref int keyIndex) { return keyIndex == 0; } public void EnumerateCollectionAt(int keyIndex, int timeIndex, NaiadList<Weighted<R>> toFill) { toFill.Clear(); if (keyIndex != 0) toFill.Add(default(R).ToWeighted(keyIndex)); } public void EnumerateDifferenceAt(int keyIndex, int timeIndex, NaiadList<Weighted<R>> toFill) { toFill.Clear(); if (keyIndex != 0) toFill.Add(default(R).ToWeighted(keyIndex)); } public void EnumerateTimes(int keyIndex, NaiadList<int> timelist) { if (keyIndex != 0) { var present = false; for (int i = 0; i < timelist.Count; i++) if (timelist.Array[i] == 0) present = true; if (!present) timelist.Add(0); } } public void EnsureStateIsCurrentWRTAdvancedTimes(ref int keyIndex) { } public void Release() { } public void Compact() { } public void Checkpoint(NaiadWriter writer) { throw new NotImplementedException(); } public void Restore(NaiadReader reader) { throw new NotImplementedException(); } public bool Stateful { get { return true; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace NearestStation.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
namespace XMLEditor { partial class frmMain { /// <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.mnuMain = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.quitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xSDToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFile = new System.Windows.Forms.SaveFileDialog(); this.viewWindow1 = new GuiLabs.Editor.UI.ViewWindow(); this.mnuMain.SuspendLayout(); this.SuspendLayout(); // // mnuMain // this.mnuMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.xSDToolStripMenuItem, this.aboutToolStripMenuItem}); this.mnuMain.Location = new System.Drawing.Point(0, 0); this.mnuMain.Name = "mnuMain"; this.mnuMain.Padding = new System.Windows.Forms.Padding(8, 2, 0, 2); this.mnuMain.Size = new System.Drawing.Size(968, 28); this.mnuMain.TabIndex = 0; this.mnuMain.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.toolStripSeparator1, this.openToolStripMenuItem, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.toolStripSeparator2, this.quitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(44, 24); this.fileToolStripMenuItem.Text = "&File"; // // newToolStripMenuItem // this.newToolStripMenuItem.Enabled = false; this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.Size = new System.Drawing.Size(135, 24); this.newToolStripMenuItem.Text = "&New"; this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(132, 6); // // openToolStripMenuItem // this.openToolStripMenuItem.Enabled = false; this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.Size = new System.Drawing.Size(135, 24); this.openToolStripMenuItem.Text = "&Open"; // // saveToolStripMenuItem // this.saveToolStripMenuItem.Enabled = false; this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.Size = new System.Drawing.Size(135, 24); this.saveToolStripMenuItem.Text = "&Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(135, 24); this.saveAsToolStripMenuItem.Text = "Save &As.."; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(132, 6); // // quitToolStripMenuItem // this.quitToolStripMenuItem.Name = "quitToolStripMenuItem"; this.quitToolStripMenuItem.Size = new System.Drawing.Size(135, 24); this.quitToolStripMenuItem.Text = "&Quit"; this.quitToolStripMenuItem.Click += new System.EventHandler(this.quitToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.undoToolStripMenuItem, this.redoToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(47, 24); this.editToolStripMenuItem.Text = "&Edit"; this.editToolStripMenuItem.Click += new System.EventHandler(this.editToolStripMenuItem_Click); // // undoToolStripMenuItem // this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; this.undoToolStripMenuItem.Size = new System.Drawing.Size(114, 24); this.undoToolStripMenuItem.Text = "&Undo"; this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click); // // redoToolStripMenuItem // this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; this.redoToolStripMenuItem.Size = new System.Drawing.Size(114, 24); this.redoToolStripMenuItem.Text = "&Redo"; this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click); // // xSDToolStripMenuItem // this.xSDToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.importToolStripMenuItem}); this.xSDToolStripMenuItem.Enabled = false; this.xSDToolStripMenuItem.Name = "xSDToolStripMenuItem"; this.xSDToolStripMenuItem.Size = new System.Drawing.Size(49, 24); this.xSDToolStripMenuItem.Text = "&XSD"; // // importToolStripMenuItem // this.importToolStripMenuItem.Name = "importToolStripMenuItem"; this.importToolStripMenuItem.Size = new System.Drawing.Size(123, 24); this.importToolStripMenuItem.Text = "&Import"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(62, 24); this.aboutToolStripMenuItem.Text = "&About"; // // saveFile // this.saveFile.DefaultExt = "xml"; this.saveFile.DereferenceLinks = false; this.saveFile.Filter = "*.xml|*xml"; this.saveFile.Title = "Save File As.."; // // viewWindow1 // this.viewWindow1.Dock = System.Windows.Forms.DockStyle.Fill; this.viewWindow1.Location = new System.Drawing.Point(0, 28); this.viewWindow1.Name = "viewWindow1"; this.viewWindow1.ShouldRedrawOnWindowPaint = true; this.viewWindow1.ShowScrollbars = true; this.viewWindow1.Size = new System.Drawing.Size(968, 459); this.viewWindow1.TabIndex = 1; // // frmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(968, 487); this.Controls.Add(this.viewWindow1); this.Controls.Add(this.mnuMain); this.MainMenuStrip = this.mnuMain; this.Margin = new System.Windows.Forms.Padding(4); this.Name = "frmMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Experimental XML Editor"; this.mnuMain.ResumeLayout(false); this.mnuMain.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip mnuMain; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem quitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem xSDToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem importToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem; private System.Windows.Forms.SaveFileDialog saveFile; private GuiLabs.Editor.UI.ViewWindow viewWindow1; } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Data; using System.Data.SqlClient; using log4net.Appender; using log4net.Core; namespace SampleAppendersApp.Appender { /// <summary> /// Simple database appender /// </summary> /// <remarks> /// <para> /// This database appender is very simple and does not support a configurable /// data schema. The schema supported is hardcoded into the appender. /// Also by not extending the AppenderSkeleton base class this appender /// avoids the serializable locking that it enforces. /// </para> /// <para> /// This appender can be subclassed to change the database connection /// type, or the database schema supported. /// </para> /// <para> /// To change the database connection type the <see cref="GetConnection"/> /// method must be overridden. /// </para> /// <para> /// To change the database schema supported by the appender the <see cref="InitializeCommand"/> /// and <see cref="SetCommandValues"/> methods must be overridden. /// </para> /// </remarks> public class FastDbAppender : IAppender, IBulkAppender, IOptionHandler { private string m_name; private string m_connectionString; public string Name { get { return m_name; } set { m_name = value; } } public string ConnectionString { get { return m_connectionString; } set { m_connectionString = value; } } public virtual void ActivateOptions() { } public virtual void Close() { } public virtual void DoAppend(LoggingEvent loggingEvent) { using(IDbConnection connection = GetConnection()) { if (connection.State == ConnectionState.Closed) { // Open the connection for each event, this takes advantage // of the builtin connection pooling connection.Open(); } using(IDbCommand command = connection.CreateCommand()) { InitializeCommand(command); SetCommandValues(command, loggingEvent); command.ExecuteNonQuery(); } } } public virtual void DoAppend(LoggingEvent[] loggingEvents) { using(IDbConnection connection = GetConnection()) { // Open the connection for each event, this takes advantage // of the builtin connection pooling connection.Open(); using(IDbCommand command = connection.CreateCommand()) { InitializeCommand(command); foreach(LoggingEvent loggingEvent in loggingEvents) { SetCommandValues(command, loggingEvent); command.ExecuteNonQuery(); } } } } /// <summary> /// Create the connection object /// </summary> /// <returns>the connection</returns> /// <remarks> /// <para> /// This implementation returns a <see cref="SqlConnection"/>. /// To change the connection subclass this appender and /// return a different connection type. /// </para> /// </remarks> virtual protected IDbConnection GetConnection() { return new SqlConnection(m_connectionString); } /// <summary> /// Initialize the command object supplied /// </summary> /// <param name="command">the command to initialize</param> /// <remarks> /// <para> /// This method must setup the database command and the /// parameters. /// </para> /// </remarks> virtual protected void InitializeCommand(IDbCommand command) { command.CommandType = CommandType.Text; command.CommandText = "INSERT INTO [LogTable] ([Time],[Logger],[Level],[Thread],[Message]) VALUES (@Time,@Logger,@Level,@Thread,@Message)"; IDbDataParameter param; // @Time param = command.CreateParameter(); param.ParameterName = "@Time"; param.DbType = DbType.DateTime; command.Parameters.Add(param); // @Logger param = command.CreateParameter(); param.ParameterName = "@Logger"; param.DbType = DbType.String; command.Parameters.Add(param); // @Level param = command.CreateParameter(); param.ParameterName = "@Level"; param.DbType = DbType.String; command.Parameters.Add(param); // @Thread param = command.CreateParameter(); param.ParameterName = "@Thread"; param.DbType = DbType.String; command.Parameters.Add(param); // @Message param = command.CreateParameter(); param.ParameterName = "@Message"; param.DbType = DbType.String; command.Parameters.Add(param); } /// <summary> /// Set the values for the command parameters /// </summary> /// <param name="command">the command to update</param> /// <param name="loggingEvent">the current logging event to retrieve the values from</param> /// <remarks> /// <para> /// Set the values of the parameters created by the /// <see cref="InitializeCommand"/> method. /// </para> /// </remarks> virtual protected void SetCommandValues(IDbCommand command, LoggingEvent loggingEvent) { ((IDbDataParameter)command.Parameters["@Time"]).Value = loggingEvent.TimeStamp; ((IDbDataParameter)command.Parameters["@Logger"]).Value = loggingEvent.LoggerName; ((IDbDataParameter)command.Parameters["@Level"]).Value = loggingEvent.Level.Name; ((IDbDataParameter)command.Parameters["@Thread"]).Value = loggingEvent.ThreadName; ((IDbDataParameter)command.Parameters["@Message"]).Value = loggingEvent.RenderedMessage; } } }
// 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.Reflection; using System.Diagnostics; using System.Collections.Concurrent; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.MethodInfos; using Internal.Reflection.Core.Execution; // // It is common practice for app code to compare Type objects using reference equality with the expectation that reference equality // is equivalent to semantic equality. To support this, all RuntimeTypeObject objects are interned using weak references. // // This assumption is baked into the codebase in these places: // // - RuntimeTypeInfo.Equals(object) implements itself as Object.ReferenceEquals(this, obj) // // - RuntimeTypeInfo.GetHashCode() is implemented in a flavor-specific manner (We can't use Object.GetHashCode() // because we don't want the hash value to change if a type is collected and resurrected later.) // // This assumption is actualized as follows: // // - RuntimeTypeInfo classes hide their constructor. The only way to instantiate a RuntimeTypeInfo // is through its public static factory method which ensures the interning and are collected in this one // file for easy auditing and to help ensure that they all operate in a consistent manner. // // - The TypeUnifier extension class provides a more friendly interface to the rest of the codebase. // namespace System.Reflection.Runtime.General { internal static partial class TypeUnifier { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType) { return elementType.GetArrayType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank) { return elementType.GetMultiDimArrayType(rank, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType) { return targetType.GetByRefType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType) { return targetType.GetPointerType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments) { return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetTypeForRuntimeTypeHandle(this RuntimeTypeHandle typeHandle) { Type type = Type.GetTypeFromHandle(typeHandle); return type.CastToRuntimeTypeInfo(); } //====================================================================================================== // This next group services the Type.GetTypeFromHandle() path. Since we already have a RuntimeTypeHandle // in that case, we pass it in as an extra argument as an optimization (otherwise, the unifier will // waste cycles looking up the handle again from the mapping tables.) //====================================================================================================== [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: false, rank: 1, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: true, rank: rank, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimePointerTypeInfo.GetPointerTypeInfo(targetType, precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeByRefTypeInfo.GetByRefTypeInfo(targetType, precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeConstructedGenericTypeInfo.GetRuntimeConstructedGenericTypeInfo(genericTypeDefinition, genericTypeArguments, precomputedTypeHandle); } } } namespace System.Reflection.Runtime.TypeInfos { //----------------------------------------------------------------------------------------------------------- // TypeInfos for type definitions (i.e. "Foo" and "Foo<>" but not "Foo<int>") that aren't opted into metadata. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeNoMetadataNamedTypeInfo { internal static RuntimeNoMetadataNamedTypeInfo GetRuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { RuntimeNoMetadataNamedTypeInfo type; if (isGenericTypeDefinition) type = GenericNoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); else type = NoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); type.EstablishDebugName(); return type; } private sealed class NoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo> { protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false); } public static readonly NoMetadataNamedTypeTable Table = new NoMetadataNamedTypeTable(); } private sealed class GenericNoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo> { protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true); } public static readonly GenericNoMetadataNamedTypeTable Table = new GenericNoMetadataNamedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos that represent type definitions (i.e. Foo or Foo<>) or constructed generic types (Foo<int>) // that can never be reflection-enabled due to the framework Reflection block. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeBlockedTypeInfo { internal static RuntimeBlockedTypeInfo GetRuntimeBlockedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { RuntimeBlockedTypeInfo type; if (isGenericTypeDefinition) type = GenericBlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); else type = BlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); type.EstablishDebugName(); return type; } private sealed class BlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo> { protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false); } public static readonly BlockedTypeTable Table = new BlockedTypeTable(); } private sealed class GenericBlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo> { protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true); } public static readonly GenericBlockedTypeTable Table = new GenericBlockedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Sz and multi-dim Array types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeArrayTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimeArrayTypeInfo GetArrayTypeInfo(RuntimeTypeInfo elementType, bool multiDim, int rank, RuntimeTypeHandle precomputedTypeHandle) { Debug.Assert(multiDim || rank == 1); RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType, multiDim, rank) : precomputedTypeHandle; UnificationKey key = new UnificationKey(elementType, typeHandle); RuntimeArrayTypeInfo type; if (!multiDim) type = ArrayTypeTable.Table.GetOrAdd(key); else type = TypeTableForMultiDimArrayTypeTables.Table.GetOrAdd(rank).GetOrAdd(key); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType, bool multiDim, int rank) { Debug.Assert(multiDim || rank == 1); RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!multiDim) { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetArrayTypeForElementType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); } else { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetMultiDimArrayTypeForElementType(elementTypeHandle, rank, out typeHandle)) return default(RuntimeTypeHandle); } return typeHandle; } private sealed class ArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo> { protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key) { ValidateElementType(key.ElementType, key.TypeHandle, multiDim: false, rank: 1); return new RuntimeArrayTypeInfo(key, multiDim: false, rank: 1); } public static readonly ArrayTypeTable Table = new ArrayTypeTable(); } private sealed class MultiDimArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo> { public MultiDimArrayTypeTable(int rank) { _rank = rank; } protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key) { ValidateElementType(key.ElementType, key.TypeHandle, multiDim: true, rank: _rank); return new RuntimeArrayTypeInfo(key, multiDim: true, rank: _rank); } private readonly int _rank; } // // For the hopefully rare case of multidim arrays, we have a dictionary of dictionaries. // private sealed class TypeTableForMultiDimArrayTypeTables : ConcurrentUnifier<int, MultiDimArrayTypeTable> { protected sealed override MultiDimArrayTypeTable Factory(int rank) { Debug.Assert(rank > 0); return new MultiDimArrayTypeTable(rank); } public static readonly TypeTableForMultiDimArrayTypeTables Table = new TypeTableForMultiDimArrayTypeTables(); } private static void ValidateElementType(RuntimeTypeInfo elementType, RuntimeTypeHandle typeHandle, bool multiDim, int rank) { Debug.Assert(multiDim || rank == 1); if (elementType.IsByRef) throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); if (elementType.IsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. if (typeHandle.IsNull() && !elementType.ContainsGenericParameters && !(elementType is RuntimeCLSIDTypeInfo)) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingArrayTypeException(elementType, multiDim, rank); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for ByRef types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeByRefTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimeByRefTypeInfo GetByRefTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle; RuntimeByRefTypeInfo type = ByRefTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle)); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType) { RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetByRefTypeForTargetType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class ByRefTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeByRefTypeInfo> { protected sealed override RuntimeByRefTypeInfo Factory(UnificationKey key) { if (key.ElementType.IsByRef) throw new TypeLoadException(SR.Format(SR.CannotCreateByRefOfByRef, key.ElementType)); return new RuntimeByRefTypeInfo(key); } public static readonly ByRefTypeTable Table = new ByRefTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Pointer types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimePointerTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimePointerTypeInfo GetPointerTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle; RuntimePointerTypeInfo type = PointerTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle)); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType) { RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetPointerTypeForTargetType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class PointerTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimePointerTypeInfo> { protected sealed override RuntimePointerTypeInfo Factory(UnificationKey key) { if (key.ElementType.IsByRef) throw new TypeLoadException(SR.Format(SR.CannotCreatePointerOfByRef, key.ElementType)); return new RuntimePointerTypeInfo(key); } public static readonly PointerTypeTable Table = new PointerTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Constructed generic types ("Foo<int>") //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeConstructedGenericTypeInfo : RuntimeTypeInfo, IKeyedItem<RuntimeConstructedGenericTypeInfo.UnificationKey> { internal static RuntimeConstructedGenericTypeInfo GetRuntimeConstructedGenericTypeInfo(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(genericTypeDefinition, genericTypeArguments) : precomputedTypeHandle; UnificationKey key = new UnificationKey(genericTypeDefinition, genericTypeArguments, typeHandle); RuntimeConstructedGenericTypeInfo typeInfo = ConstructedGenericTypeTable.Table.GetOrAdd(key); typeInfo.EstablishDebugName(); return typeInfo; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments) { RuntimeTypeHandle genericTypeDefinitionHandle = genericTypeDefinition.InternalTypeHandleIfAvailable; if (genericTypeDefinitionHandle.IsNull()) return default(RuntimeTypeHandle); if (ReflectionCoreExecution.ExecutionEnvironment.IsReflectionBlocked(genericTypeDefinitionHandle)) return default(RuntimeTypeHandle); int count = genericTypeArguments.Length; RuntimeTypeHandle[] genericTypeArgumentHandles = new RuntimeTypeHandle[count]; for (int i = 0; i < count; i++) { RuntimeTypeHandle genericTypeArgumentHandle = genericTypeArguments[i].InternalTypeHandleIfAvailable; if (genericTypeArgumentHandle.IsNull()) return default(RuntimeTypeHandle); genericTypeArgumentHandles[i] = genericTypeArgumentHandle; } RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class ConstructedGenericTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeConstructedGenericTypeInfo> { protected sealed override RuntimeConstructedGenericTypeInfo Factory(UnificationKey key) { bool atLeastOneOpenType = false; foreach (RuntimeTypeInfo genericTypeArgument in key.GenericTypeArguments) { if (genericTypeArgument.IsByRef || genericTypeArgument.IsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidTypeArgument, genericTypeArgument)); if (genericTypeArgument.ContainsGenericParameters) atLeastOneOpenType = true; } // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. if (key.TypeHandle.IsNull() && !atLeastOneOpenType) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingConstructedGenericTypeException(key.GenericTypeDefinition, key.GenericTypeArguments.CloneTypeArray()); return new RuntimeConstructedGenericTypeInfo(key); } public static readonly ConstructedGenericTypeTable Table = new ConstructedGenericTypeTable(); } } internal sealed partial class RuntimeCLSIDTypeInfo { public static RuntimeCLSIDTypeInfo GetRuntimeCLSIDTypeInfo(Guid clsid, string server) { UnificationKey key = new UnificationKey(clsid, server); return ClsIdTypeTable.Table.GetOrAdd(key); } private sealed class ClsIdTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeCLSIDTypeInfo> { protected sealed override RuntimeCLSIDTypeInfo Factory(UnificationKey key) { return new RuntimeCLSIDTypeInfo(key.ClsId, key.Server); } public static readonly ClsIdTypeTable Table = new ClsIdTypeTable(); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnUsuario class. /// </summary> [Serializable] public partial class PnUsuarioCollection : ActiveList<PnUsuario, PnUsuarioCollection> { public PnUsuarioCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnUsuarioCollection</returns> public PnUsuarioCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnUsuario o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_usuarios table. /// </summary> [Serializable] public partial class PnUsuario : ActiveRecord<PnUsuario>, IActiveRecord { #region .ctors and Default Settings public PnUsuario() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnUsuario(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnUsuario(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnUsuario(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_usuarios", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema); colvarIdUsuario.ColumnName = "id_usuario"; colvarIdUsuario.DataType = DbType.Int32; colvarIdUsuario.MaxLength = 0; colvarIdUsuario.AutoIncrement = true; colvarIdUsuario.IsNullable = false; colvarIdUsuario.IsPrimaryKey = true; colvarIdUsuario.IsForeignKey = false; colvarIdUsuario.IsReadOnly = false; colvarIdUsuario.DefaultSetting = @""; colvarIdUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuario); TableSchema.TableColumn colvarLogin = new TableSchema.TableColumn(schema); colvarLogin.ColumnName = "login"; colvarLogin.DataType = DbType.AnsiString; colvarLogin.MaxLength = 20; colvarLogin.AutoIncrement = false; colvarLogin.IsNullable = true; colvarLogin.IsPrimaryKey = false; colvarLogin.IsForeignKey = false; colvarLogin.IsReadOnly = false; colvarLogin.DefaultSetting = @""; colvarLogin.ForeignKeyTableName = ""; schema.Columns.Add(colvarLogin); TableSchema.TableColumn colvarPasswd = new TableSchema.TableColumn(schema); colvarPasswd.ColumnName = "passwd"; colvarPasswd.DataType = DbType.AnsiString; colvarPasswd.MaxLength = 32; colvarPasswd.AutoIncrement = false; colvarPasswd.IsNullable = true; colvarPasswd.IsPrimaryKey = false; colvarPasswd.IsForeignKey = false; colvarPasswd.IsReadOnly = false; colvarPasswd.DefaultSetting = @""; colvarPasswd.ForeignKeyTableName = ""; schema.Columns.Add(colvarPasswd); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = -1; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema); colvarApellido.ColumnName = "apellido"; colvarApellido.DataType = DbType.AnsiString; colvarApellido.MaxLength = -1; colvarApellido.AutoIncrement = false; colvarApellido.IsNullable = true; colvarApellido.IsPrimaryKey = false; colvarApellido.IsForeignKey = false; colvarApellido.IsReadOnly = false; colvarApellido.DefaultSetting = @""; colvarApellido.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellido); TableSchema.TableColumn colvarDireccion = new TableSchema.TableColumn(schema); colvarDireccion.ColumnName = "direccion"; colvarDireccion.DataType = DbType.AnsiString; colvarDireccion.MaxLength = -1; colvarDireccion.AutoIncrement = false; colvarDireccion.IsNullable = true; colvarDireccion.IsPrimaryKey = false; colvarDireccion.IsForeignKey = false; colvarDireccion.IsReadOnly = false; colvarDireccion.DefaultSetting = @""; colvarDireccion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDireccion); TableSchema.TableColumn colvarTelefono = new TableSchema.TableColumn(schema); colvarTelefono.ColumnName = "telefono"; colvarTelefono.DataType = DbType.AnsiString; colvarTelefono.MaxLength = -1; colvarTelefono.AutoIncrement = false; colvarTelefono.IsNullable = true; colvarTelefono.IsPrimaryKey = false; colvarTelefono.IsForeignKey = false; colvarTelefono.IsReadOnly = false; colvarTelefono.DefaultSetting = @""; colvarTelefono.ForeignKeyTableName = ""; schema.Columns.Add(colvarTelefono); TableSchema.TableColumn colvarCelular = new TableSchema.TableColumn(schema); colvarCelular.ColumnName = "celular"; colvarCelular.DataType = DbType.AnsiString; colvarCelular.MaxLength = -1; colvarCelular.AutoIncrement = false; colvarCelular.IsNullable = true; colvarCelular.IsPrimaryKey = false; colvarCelular.IsForeignKey = false; colvarCelular.IsReadOnly = false; colvarCelular.DefaultSetting = @""; colvarCelular.ForeignKeyTableName = ""; schema.Columns.Add(colvarCelular); TableSchema.TableColumn colvarMail = new TableSchema.TableColumn(schema); colvarMail.ColumnName = "mail"; colvarMail.DataType = DbType.AnsiString; colvarMail.MaxLength = -1; colvarMail.AutoIncrement = false; colvarMail.IsNullable = true; colvarMail.IsPrimaryKey = false; colvarMail.IsForeignKey = false; colvarMail.IsReadOnly = false; colvarMail.DefaultSetting = @""; colvarMail.ForeignKeyTableName = ""; schema.Columns.Add(colvarMail); TableSchema.TableColumn colvarFechaAlta = new TableSchema.TableColumn(schema); colvarFechaAlta.ColumnName = "fecha_alta"; colvarFechaAlta.DataType = DbType.DateTime; colvarFechaAlta.MaxLength = 0; colvarFechaAlta.AutoIncrement = false; colvarFechaAlta.IsNullable = true; colvarFechaAlta.IsPrimaryKey = false; colvarFechaAlta.IsForeignKey = false; colvarFechaAlta.IsReadOnly = false; colvarFechaAlta.DefaultSetting = @""; colvarFechaAlta.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaAlta); TableSchema.TableColumn colvarComentarios = new TableSchema.TableColumn(schema); colvarComentarios.ColumnName = "comentarios"; colvarComentarios.DataType = DbType.AnsiString; colvarComentarios.MaxLength = -1; colvarComentarios.AutoIncrement = false; colvarComentarios.IsNullable = true; colvarComentarios.IsPrimaryKey = false; colvarComentarios.IsForeignKey = false; colvarComentarios.IsReadOnly = false; colvarComentarios.DefaultSetting = @""; colvarComentarios.ForeignKeyTableName = ""; schema.Columns.Add(colvarComentarios); TableSchema.TableColumn colvarPaginaInicio = new TableSchema.TableColumn(schema); colvarPaginaInicio.ColumnName = "pagina_inicio"; colvarPaginaInicio.DataType = DbType.AnsiString; colvarPaginaInicio.MaxLength = 100; colvarPaginaInicio.AutoIncrement = false; colvarPaginaInicio.IsNullable = true; colvarPaginaInicio.IsPrimaryKey = false; colvarPaginaInicio.IsForeignKey = false; colvarPaginaInicio.IsReadOnly = false; colvarPaginaInicio.DefaultSetting = @""; colvarPaginaInicio.ForeignKeyTableName = ""; schema.Columns.Add(colvarPaginaInicio); TableSchema.TableColumn colvarFirma1 = new TableSchema.TableColumn(schema); colvarFirma1.ColumnName = "firma1"; colvarFirma1.DataType = DbType.AnsiString; colvarFirma1.MaxLength = 30; colvarFirma1.AutoIncrement = false; colvarFirma1.IsNullable = true; colvarFirma1.IsPrimaryKey = false; colvarFirma1.IsForeignKey = false; colvarFirma1.IsReadOnly = false; colvarFirma1.DefaultSetting = @""; colvarFirma1.ForeignKeyTableName = ""; schema.Columns.Add(colvarFirma1); TableSchema.TableColumn colvarFirma2 = new TableSchema.TableColumn(schema); colvarFirma2.ColumnName = "firma2"; colvarFirma2.DataType = DbType.AnsiString; colvarFirma2.MaxLength = 30; colvarFirma2.AutoIncrement = false; colvarFirma2.IsNullable = true; colvarFirma2.IsPrimaryKey = false; colvarFirma2.IsForeignKey = false; colvarFirma2.IsReadOnly = false; colvarFirma2.DefaultSetting = @""; colvarFirma2.ForeignKeyTableName = ""; schema.Columns.Add(colvarFirma2); TableSchema.TableColumn colvarFirma3 = new TableSchema.TableColumn(schema); colvarFirma3.ColumnName = "firma3"; colvarFirma3.DataType = DbType.AnsiString; colvarFirma3.MaxLength = 30; colvarFirma3.AutoIncrement = false; colvarFirma3.IsNullable = true; colvarFirma3.IsPrimaryKey = false; colvarFirma3.IsForeignKey = false; colvarFirma3.IsReadOnly = false; colvarFirma3.DefaultSetting = @""; colvarFirma3.ForeignKeyTableName = ""; schema.Columns.Add(colvarFirma3); TableSchema.TableColumn colvarAcceso1 = new TableSchema.TableColumn(schema); colvarAcceso1.ColumnName = "acceso1"; colvarAcceso1.DataType = DbType.AnsiString; colvarAcceso1.MaxLength = 100; colvarAcceso1.AutoIncrement = false; colvarAcceso1.IsNullable = true; colvarAcceso1.IsPrimaryKey = false; colvarAcceso1.IsForeignKey = false; colvarAcceso1.IsReadOnly = false; colvarAcceso1.DefaultSetting = @""; colvarAcceso1.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso1); TableSchema.TableColumn colvarAcceso2 = new TableSchema.TableColumn(schema); colvarAcceso2.ColumnName = "acceso2"; colvarAcceso2.DataType = DbType.AnsiString; colvarAcceso2.MaxLength = 100; colvarAcceso2.AutoIncrement = false; colvarAcceso2.IsNullable = true; colvarAcceso2.IsPrimaryKey = false; colvarAcceso2.IsForeignKey = false; colvarAcceso2.IsReadOnly = false; colvarAcceso2.DefaultSetting = @""; colvarAcceso2.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso2); TableSchema.TableColumn colvarAcceso3 = new TableSchema.TableColumn(schema); colvarAcceso3.ColumnName = "acceso3"; colvarAcceso3.DataType = DbType.AnsiString; colvarAcceso3.MaxLength = 100; colvarAcceso3.AutoIncrement = false; colvarAcceso3.IsNullable = true; colvarAcceso3.IsPrimaryKey = false; colvarAcceso3.IsForeignKey = false; colvarAcceso3.IsReadOnly = false; colvarAcceso3.DefaultSetting = @""; colvarAcceso3.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso3); TableSchema.TableColumn colvarAcceso4 = new TableSchema.TableColumn(schema); colvarAcceso4.ColumnName = "acceso4"; colvarAcceso4.DataType = DbType.AnsiString; colvarAcceso4.MaxLength = 100; colvarAcceso4.AutoIncrement = false; colvarAcceso4.IsNullable = true; colvarAcceso4.IsPrimaryKey = false; colvarAcceso4.IsForeignKey = false; colvarAcceso4.IsReadOnly = false; colvarAcceso4.DefaultSetting = @""; colvarAcceso4.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso4); TableSchema.TableColumn colvarAcceso5 = new TableSchema.TableColumn(schema); colvarAcceso5.ColumnName = "acceso5"; colvarAcceso5.DataType = DbType.AnsiString; colvarAcceso5.MaxLength = 100; colvarAcceso5.AutoIncrement = false; colvarAcceso5.IsNullable = true; colvarAcceso5.IsPrimaryKey = false; colvarAcceso5.IsForeignKey = false; colvarAcceso5.IsReadOnly = false; colvarAcceso5.DefaultSetting = @""; colvarAcceso5.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso5); TableSchema.TableColumn colvarAcceso6 = new TableSchema.TableColumn(schema); colvarAcceso6.ColumnName = "acceso6"; colvarAcceso6.DataType = DbType.AnsiString; colvarAcceso6.MaxLength = 100; colvarAcceso6.AutoIncrement = false; colvarAcceso6.IsNullable = true; colvarAcceso6.IsPrimaryKey = false; colvarAcceso6.IsForeignKey = false; colvarAcceso6.IsReadOnly = false; colvarAcceso6.DefaultSetting = @""; colvarAcceso6.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso6); TableSchema.TableColumn colvarAvisarOc = new TableSchema.TableColumn(schema); colvarAvisarOc.ColumnName = "avisar_oc"; colvarAvisarOc.DataType = DbType.Int16; colvarAvisarOc.MaxLength = 0; colvarAvisarOc.AutoIncrement = false; colvarAvisarOc.IsNullable = true; colvarAvisarOc.IsPrimaryKey = false; colvarAvisarOc.IsForeignKey = false; colvarAvisarOc.IsReadOnly = false; colvarAvisarOc.DefaultSetting = @""; colvarAvisarOc.ForeignKeyTableName = ""; schema.Columns.Add(colvarAvisarOc); TableSchema.TableColumn colvarIdLugarPedidoComida = new TableSchema.TableColumn(schema); colvarIdLugarPedidoComida.ColumnName = "id_lugar_pedido_comida"; colvarIdLugarPedidoComida.DataType = DbType.Int16; colvarIdLugarPedidoComida.MaxLength = 0; colvarIdLugarPedidoComida.AutoIncrement = false; colvarIdLugarPedidoComida.IsNullable = true; colvarIdLugarPedidoComida.IsPrimaryKey = false; colvarIdLugarPedidoComida.IsForeignKey = false; colvarIdLugarPedidoComida.IsReadOnly = false; colvarIdLugarPedidoComida.DefaultSetting = @""; colvarIdLugarPedidoComida.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLugarPedidoComida); TableSchema.TableColumn colvarAcceso7 = new TableSchema.TableColumn(schema); colvarAcceso7.ColumnName = "acceso7"; colvarAcceso7.DataType = DbType.AnsiString; colvarAcceso7.MaxLength = 100; colvarAcceso7.AutoIncrement = false; colvarAcceso7.IsNullable = true; colvarAcceso7.IsPrimaryKey = false; colvarAcceso7.IsForeignKey = false; colvarAcceso7.IsReadOnly = false; colvarAcceso7.DefaultSetting = @""; colvarAcceso7.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso7); TableSchema.TableColumn colvarAcceso8 = new TableSchema.TableColumn(schema); colvarAcceso8.ColumnName = "acceso8"; colvarAcceso8.DataType = DbType.AnsiString; colvarAcceso8.MaxLength = 100; colvarAcceso8.AutoIncrement = false; colvarAcceso8.IsNullable = true; colvarAcceso8.IsPrimaryKey = false; colvarAcceso8.IsForeignKey = false; colvarAcceso8.IsReadOnly = false; colvarAcceso8.DefaultSetting = @""; colvarAcceso8.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso8); TableSchema.TableColumn colvarAcceso9 = new TableSchema.TableColumn(schema); colvarAcceso9.ColumnName = "acceso9"; colvarAcceso9.DataType = DbType.AnsiString; colvarAcceso9.MaxLength = 100; colvarAcceso9.AutoIncrement = false; colvarAcceso9.IsNullable = true; colvarAcceso9.IsPrimaryKey = false; colvarAcceso9.IsForeignKey = false; colvarAcceso9.IsReadOnly = false; colvarAcceso9.DefaultSetting = @""; colvarAcceso9.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso9); TableSchema.TableColumn colvarAcceso10 = new TableSchema.TableColumn(schema); colvarAcceso10.ColumnName = "acceso10"; colvarAcceso10.DataType = DbType.AnsiString; colvarAcceso10.MaxLength = 100; colvarAcceso10.AutoIncrement = false; colvarAcceso10.IsNullable = true; colvarAcceso10.IsPrimaryKey = false; colvarAcceso10.IsForeignKey = false; colvarAcceso10.IsReadOnly = false; colvarAcceso10.DefaultSetting = @""; colvarAcceso10.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso10); TableSchema.TableColumn colvarAcceso11 = new TableSchema.TableColumn(schema); colvarAcceso11.ColumnName = "acceso11"; colvarAcceso11.DataType = DbType.AnsiString; colvarAcceso11.MaxLength = 100; colvarAcceso11.AutoIncrement = false; colvarAcceso11.IsNullable = true; colvarAcceso11.IsPrimaryKey = false; colvarAcceso11.IsForeignKey = false; colvarAcceso11.IsReadOnly = false; colvarAcceso11.DefaultSetting = @""; colvarAcceso11.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso11); TableSchema.TableColumn colvarAcceso12 = new TableSchema.TableColumn(schema); colvarAcceso12.ColumnName = "acceso12"; colvarAcceso12.DataType = DbType.AnsiString; colvarAcceso12.MaxLength = 100; colvarAcceso12.AutoIncrement = false; colvarAcceso12.IsNullable = true; colvarAcceso12.IsPrimaryKey = false; colvarAcceso12.IsForeignKey = false; colvarAcceso12.IsReadOnly = false; colvarAcceso12.DefaultSetting = @""; colvarAcceso12.ForeignKeyTableName = ""; schema.Columns.Add(colvarAcceso12); TableSchema.TableColumn colvarTipoLic = new TableSchema.TableColumn(schema); colvarTipoLic.ColumnName = "tipo_lic"; colvarTipoLic.DataType = DbType.AnsiString; colvarTipoLic.MaxLength = -1; colvarTipoLic.AutoIncrement = false; colvarTipoLic.IsNullable = true; colvarTipoLic.IsPrimaryKey = false; colvarTipoLic.IsForeignKey = false; colvarTipoLic.IsReadOnly = false; colvarTipoLic.DefaultSetting = @""; colvarTipoLic.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoLic); TableSchema.TableColumn colvarIniciales = new TableSchema.TableColumn(schema); colvarIniciales.ColumnName = "iniciales"; colvarIniciales.DataType = DbType.AnsiString; colvarIniciales.MaxLength = -1; colvarIniciales.AutoIncrement = false; colvarIniciales.IsNullable = true; colvarIniciales.IsPrimaryKey = false; colvarIniciales.IsForeignKey = false; colvarIniciales.IsReadOnly = false; colvarIniciales.DefaultSetting = @""; colvarIniciales.ForeignKeyTableName = ""; schema.Columns.Add(colvarIniciales); TableSchema.TableColumn colvarPciaUbicacion = new TableSchema.TableColumn(schema); colvarPciaUbicacion.ColumnName = "pcia_ubicacion"; colvarPciaUbicacion.DataType = DbType.Int16; colvarPciaUbicacion.MaxLength = 0; colvarPciaUbicacion.AutoIncrement = false; colvarPciaUbicacion.IsNullable = true; colvarPciaUbicacion.IsPrimaryKey = false; colvarPciaUbicacion.IsForeignKey = false; colvarPciaUbicacion.IsReadOnly = false; colvarPciaUbicacion.DefaultSetting = @""; colvarPciaUbicacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarPciaUbicacion); TableSchema.TableColumn colvarNroTarjeta = new TableSchema.TableColumn(schema); colvarNroTarjeta.ColumnName = "nro_tarjeta"; colvarNroTarjeta.DataType = DbType.AnsiString; colvarNroTarjeta.MaxLength = -1; colvarNroTarjeta.AutoIncrement = false; colvarNroTarjeta.IsNullable = true; colvarNroTarjeta.IsPrimaryKey = false; colvarNroTarjeta.IsForeignKey = false; colvarNroTarjeta.IsReadOnly = false; colvarNroTarjeta.DefaultSetting = @""; colvarNroTarjeta.ForeignKeyTableName = ""; schema.Columns.Add(colvarNroTarjeta); TableSchema.TableColumn colvarVersionTarjeta = new TableSchema.TableColumn(schema); colvarVersionTarjeta.ColumnName = "version_tarjeta"; colvarVersionTarjeta.DataType = DbType.Int16; colvarVersionTarjeta.MaxLength = 0; colvarVersionTarjeta.AutoIncrement = false; colvarVersionTarjeta.IsNullable = true; colvarVersionTarjeta.IsPrimaryKey = false; colvarVersionTarjeta.IsForeignKey = false; colvarVersionTarjeta.IsReadOnly = false; colvarVersionTarjeta.DefaultSetting = @"((0))"; colvarVersionTarjeta.ForeignKeyTableName = ""; schema.Columns.Add(colvarVersionTarjeta); TableSchema.TableColumn colvarVisible = new TableSchema.TableColumn(schema); colvarVisible.ColumnName = "visible"; colvarVisible.DataType = DbType.Int16; colvarVisible.MaxLength = 0; colvarVisible.AutoIncrement = false; colvarVisible.IsNullable = true; colvarVisible.IsPrimaryKey = false; colvarVisible.IsForeignKey = false; colvarVisible.IsReadOnly = false; colvarVisible.DefaultSetting = @""; colvarVisible.ForeignKeyTableName = ""; schema.Columns.Add(colvarVisible); TableSchema.TableColumn colvarAccesoRemoto = new TableSchema.TableColumn(schema); colvarAccesoRemoto.ColumnName = "acceso_remoto"; colvarAccesoRemoto.DataType = DbType.Int16; colvarAccesoRemoto.MaxLength = 0; colvarAccesoRemoto.AutoIncrement = false; colvarAccesoRemoto.IsNullable = true; colvarAccesoRemoto.IsPrimaryKey = false; colvarAccesoRemoto.IsForeignKey = false; colvarAccesoRemoto.IsReadOnly = false; colvarAccesoRemoto.DefaultSetting = @"((0))"; colvarAccesoRemoto.ForeignKeyTableName = ""; schema.Columns.Add(colvarAccesoRemoto); TableSchema.TableColumn colvarFoto = new TableSchema.TableColumn(schema); colvarFoto.ColumnName = "foto"; colvarFoto.DataType = DbType.Binary; colvarFoto.MaxLength = -1; colvarFoto.AutoIncrement = false; colvarFoto.IsNullable = true; colvarFoto.IsPrimaryKey = false; colvarFoto.IsForeignKey = false; colvarFoto.IsReadOnly = false; colvarFoto.DefaultSetting = @""; colvarFoto.ForeignKeyTableName = ""; schema.Columns.Add(colvarFoto); TableSchema.TableColumn colvarHuella = new TableSchema.TableColumn(schema); colvarHuella.ColumnName = "huella"; colvarHuella.DataType = DbType.Binary; colvarHuella.MaxLength = -1; colvarHuella.AutoIncrement = false; colvarHuella.IsNullable = true; colvarHuella.IsPrimaryKey = false; colvarHuella.IsForeignKey = false; colvarHuella.IsReadOnly = false; colvarHuella.DefaultSetting = @""; colvarHuella.ForeignKeyTableName = ""; schema.Columns.Add(colvarHuella); TableSchema.TableColumn colvarHuella1 = new TableSchema.TableColumn(schema); colvarHuella1.ColumnName = "huella1"; colvarHuella1.DataType = DbType.Binary; colvarHuella1.MaxLength = -1; colvarHuella1.AutoIncrement = false; colvarHuella1.IsNullable = true; colvarHuella1.IsPrimaryKey = false; colvarHuella1.IsForeignKey = false; colvarHuella1.IsReadOnly = false; colvarHuella1.DefaultSetting = @""; colvarHuella1.ForeignKeyTableName = ""; schema.Columns.Add(colvarHuella1); TableSchema.TableColumn colvarHuella2 = new TableSchema.TableColumn(schema); colvarHuella2.ColumnName = "huella2"; colvarHuella2.DataType = DbType.Binary; colvarHuella2.MaxLength = -1; colvarHuella2.AutoIncrement = false; colvarHuella2.IsNullable = true; colvarHuella2.IsPrimaryKey = false; colvarHuella2.IsForeignKey = false; colvarHuella2.IsReadOnly = false; colvarHuella2.DefaultSetting = @""; colvarHuella2.ForeignKeyTableName = ""; schema.Columns.Add(colvarHuella2); TableSchema.TableColumn colvarHuella3 = new TableSchema.TableColumn(schema); colvarHuella3.ColumnName = "huella3"; colvarHuella3.DataType = DbType.Binary; colvarHuella3.MaxLength = -1; colvarHuella3.AutoIncrement = false; colvarHuella3.IsNullable = true; colvarHuella3.IsPrimaryKey = false; colvarHuella3.IsForeignKey = false; colvarHuella3.IsReadOnly = false; colvarHuella3.DefaultSetting = @""; colvarHuella3.ForeignKeyTableName = ""; schema.Columns.Add(colvarHuella3); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_usuarios",schema); } } #endregion #region Props [XmlAttribute("IdUsuario")] [Bindable(true)] public int IdUsuario { get { return GetColumnValue<int>(Columns.IdUsuario); } set { SetColumnValue(Columns.IdUsuario, value); } } [XmlAttribute("Login")] [Bindable(true)] public string Login { get { return GetColumnValue<string>(Columns.Login); } set { SetColumnValue(Columns.Login, value); } } [XmlAttribute("Passwd")] [Bindable(true)] public string Passwd { get { return GetColumnValue<string>(Columns.Passwd); } set { SetColumnValue(Columns.Passwd, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Apellido")] [Bindable(true)] public string Apellido { get { return GetColumnValue<string>(Columns.Apellido); } set { SetColumnValue(Columns.Apellido, value); } } [XmlAttribute("Direccion")] [Bindable(true)] public string Direccion { get { return GetColumnValue<string>(Columns.Direccion); } set { SetColumnValue(Columns.Direccion, value); } } [XmlAttribute("Telefono")] [Bindable(true)] public string Telefono { get { return GetColumnValue<string>(Columns.Telefono); } set { SetColumnValue(Columns.Telefono, value); } } [XmlAttribute("Celular")] [Bindable(true)] public string Celular { get { return GetColumnValue<string>(Columns.Celular); } set { SetColumnValue(Columns.Celular, value); } } [XmlAttribute("Mail")] [Bindable(true)] public string Mail { get { return GetColumnValue<string>(Columns.Mail); } set { SetColumnValue(Columns.Mail, value); } } [XmlAttribute("FechaAlta")] [Bindable(true)] public DateTime? FechaAlta { get { return GetColumnValue<DateTime?>(Columns.FechaAlta); } set { SetColumnValue(Columns.FechaAlta, value); } } [XmlAttribute("Comentarios")] [Bindable(true)] public string Comentarios { get { return GetColumnValue<string>(Columns.Comentarios); } set { SetColumnValue(Columns.Comentarios, value); } } [XmlAttribute("PaginaInicio")] [Bindable(true)] public string PaginaInicio { get { return GetColumnValue<string>(Columns.PaginaInicio); } set { SetColumnValue(Columns.PaginaInicio, value); } } [XmlAttribute("Firma1")] [Bindable(true)] public string Firma1 { get { return GetColumnValue<string>(Columns.Firma1); } set { SetColumnValue(Columns.Firma1, value); } } [XmlAttribute("Firma2")] [Bindable(true)] public string Firma2 { get { return GetColumnValue<string>(Columns.Firma2); } set { SetColumnValue(Columns.Firma2, value); } } [XmlAttribute("Firma3")] [Bindable(true)] public string Firma3 { get { return GetColumnValue<string>(Columns.Firma3); } set { SetColumnValue(Columns.Firma3, value); } } [XmlAttribute("Acceso1")] [Bindable(true)] public string Acceso1 { get { return GetColumnValue<string>(Columns.Acceso1); } set { SetColumnValue(Columns.Acceso1, value); } } [XmlAttribute("Acceso2")] [Bindable(true)] public string Acceso2 { get { return GetColumnValue<string>(Columns.Acceso2); } set { SetColumnValue(Columns.Acceso2, value); } } [XmlAttribute("Acceso3")] [Bindable(true)] public string Acceso3 { get { return GetColumnValue<string>(Columns.Acceso3); } set { SetColumnValue(Columns.Acceso3, value); } } [XmlAttribute("Acceso4")] [Bindable(true)] public string Acceso4 { get { return GetColumnValue<string>(Columns.Acceso4); } set { SetColumnValue(Columns.Acceso4, value); } } [XmlAttribute("Acceso5")] [Bindable(true)] public string Acceso5 { get { return GetColumnValue<string>(Columns.Acceso5); } set { SetColumnValue(Columns.Acceso5, value); } } [XmlAttribute("Acceso6")] [Bindable(true)] public string Acceso6 { get { return GetColumnValue<string>(Columns.Acceso6); } set { SetColumnValue(Columns.Acceso6, value); } } [XmlAttribute("AvisarOc")] [Bindable(true)] public short? AvisarOc { get { return GetColumnValue<short?>(Columns.AvisarOc); } set { SetColumnValue(Columns.AvisarOc, value); } } [XmlAttribute("IdLugarPedidoComida")] [Bindable(true)] public short? IdLugarPedidoComida { get { return GetColumnValue<short?>(Columns.IdLugarPedidoComida); } set { SetColumnValue(Columns.IdLugarPedidoComida, value); } } [XmlAttribute("Acceso7")] [Bindable(true)] public string Acceso7 { get { return GetColumnValue<string>(Columns.Acceso7); } set { SetColumnValue(Columns.Acceso7, value); } } [XmlAttribute("Acceso8")] [Bindable(true)] public string Acceso8 { get { return GetColumnValue<string>(Columns.Acceso8); } set { SetColumnValue(Columns.Acceso8, value); } } [XmlAttribute("Acceso9")] [Bindable(true)] public string Acceso9 { get { return GetColumnValue<string>(Columns.Acceso9); } set { SetColumnValue(Columns.Acceso9, value); } } [XmlAttribute("Acceso10")] [Bindable(true)] public string Acceso10 { get { return GetColumnValue<string>(Columns.Acceso10); } set { SetColumnValue(Columns.Acceso10, value); } } [XmlAttribute("Acceso11")] [Bindable(true)] public string Acceso11 { get { return GetColumnValue<string>(Columns.Acceso11); } set { SetColumnValue(Columns.Acceso11, value); } } [XmlAttribute("Acceso12")] [Bindable(true)] public string Acceso12 { get { return GetColumnValue<string>(Columns.Acceso12); } set { SetColumnValue(Columns.Acceso12, value); } } [XmlAttribute("TipoLic")] [Bindable(true)] public string TipoLic { get { return GetColumnValue<string>(Columns.TipoLic); } set { SetColumnValue(Columns.TipoLic, value); } } [XmlAttribute("Iniciales")] [Bindable(true)] public string Iniciales { get { return GetColumnValue<string>(Columns.Iniciales); } set { SetColumnValue(Columns.Iniciales, value); } } [XmlAttribute("PciaUbicacion")] [Bindable(true)] public short? PciaUbicacion { get { return GetColumnValue<short?>(Columns.PciaUbicacion); } set { SetColumnValue(Columns.PciaUbicacion, value); } } [XmlAttribute("NroTarjeta")] [Bindable(true)] public string NroTarjeta { get { return GetColumnValue<string>(Columns.NroTarjeta); } set { SetColumnValue(Columns.NroTarjeta, value); } } [XmlAttribute("VersionTarjeta")] [Bindable(true)] public short? VersionTarjeta { get { return GetColumnValue<short?>(Columns.VersionTarjeta); } set { SetColumnValue(Columns.VersionTarjeta, value); } } [XmlAttribute("Visible")] [Bindable(true)] public short? Visible { get { return GetColumnValue<short?>(Columns.Visible); } set { SetColumnValue(Columns.Visible, value); } } [XmlAttribute("AccesoRemoto")] [Bindable(true)] public short? AccesoRemoto { get { return GetColumnValue<short?>(Columns.AccesoRemoto); } set { SetColumnValue(Columns.AccesoRemoto, value); } } [XmlAttribute("Foto")] [Bindable(true)] public byte[] Foto { get { return GetColumnValue<byte[]>(Columns.Foto); } set { SetColumnValue(Columns.Foto, value); } } [XmlAttribute("Huella")] [Bindable(true)] public byte[] Huella { get { return GetColumnValue<byte[]>(Columns.Huella); } set { SetColumnValue(Columns.Huella, value); } } [XmlAttribute("Huella1")] [Bindable(true)] public byte[] Huella1 { get { return GetColumnValue<byte[]>(Columns.Huella1); } set { SetColumnValue(Columns.Huella1, value); } } [XmlAttribute("Huella2")] [Bindable(true)] public byte[] Huella2 { get { return GetColumnValue<byte[]>(Columns.Huella2); } set { SetColumnValue(Columns.Huella2, value); } } [XmlAttribute("Huella3")] [Bindable(true)] public byte[] Huella3 { get { return GetColumnValue<byte[]>(Columns.Huella3); } set { SetColumnValue(Columns.Huella3, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.PnGruposUsuarioCollection colPnGruposUsuarios; public DalSic.PnGruposUsuarioCollection PnGruposUsuarios { get { if(colPnGruposUsuarios == null) { colPnGruposUsuarios = new DalSic.PnGruposUsuarioCollection().Where(PnGruposUsuario.Columns.IdUsuario, IdUsuario).Load(); colPnGruposUsuarios.ListChanged += new ListChangedEventHandler(colPnGruposUsuarios_ListChanged); } return colPnGruposUsuarios; } set { colPnGruposUsuarios = value; colPnGruposUsuarios.ListChanged += new ListChangedEventHandler(colPnGruposUsuarios_ListChanged); } } void colPnGruposUsuarios_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnGruposUsuarios[e.NewIndex].IdUsuario = IdUsuario; } } private DalSic.PnPermisosActualeCollection colPnPermisosActuales; public DalSic.PnPermisosActualeCollection PnPermisosActuales { get { if(colPnPermisosActuales == null) { colPnPermisosActuales = new DalSic.PnPermisosActualeCollection().Where(PnPermisosActuale.Columns.IdUsuario, IdUsuario).Load(); colPnPermisosActuales.ListChanged += new ListChangedEventHandler(colPnPermisosActuales_ListChanged); } return colPnPermisosActuales; } set { colPnPermisosActuales = value; colPnPermisosActuales.ListChanged += new ListChangedEventHandler(colPnPermisosActuales_ListChanged); } } void colPnPermisosActuales_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnPermisosActuales[e.NewIndex].IdUsuario = IdUsuario; } } private DalSic.PnPermisosSesionCollection colPnPermisosSesionRecords; public DalSic.PnPermisosSesionCollection PnPermisosSesionRecords { get { if(colPnPermisosSesionRecords == null) { colPnPermisosSesionRecords = new DalSic.PnPermisosSesionCollection().Where(PnPermisosSesion.Columns.IdUsuario, IdUsuario).Load(); colPnPermisosSesionRecords.ListChanged += new ListChangedEventHandler(colPnPermisosSesionRecords_ListChanged); } return colPnPermisosSesionRecords; } set { colPnPermisosSesionRecords = value; colPnPermisosSesionRecords.ListChanged += new ListChangedEventHandler(colPnPermisosSesionRecords_ListChanged); } } void colPnPermisosSesionRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnPermisosSesionRecords[e.NewIndex].IdUsuario = IdUsuario; } } private DalSic.PnPermisosUsuarioCollection colPnPermisosUsuarios; public DalSic.PnPermisosUsuarioCollection PnPermisosUsuarios { get { if(colPnPermisosUsuarios == null) { colPnPermisosUsuarios = new DalSic.PnPermisosUsuarioCollection().Where(PnPermisosUsuario.Columns.IdUsuario, IdUsuario).Load(); colPnPermisosUsuarios.ListChanged += new ListChangedEventHandler(colPnPermisosUsuarios_ListChanged); } return colPnPermisosUsuarios; } set { colPnPermisosUsuarios = value; colPnPermisosUsuarios.ListChanged += new ListChangedEventHandler(colPnPermisosUsuarios_ListChanged); } } void colPnPermisosUsuarios_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnPermisosUsuarios[e.NewIndex].IdUsuario = IdUsuario; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varLogin,string varPasswd,string varNombre,string varApellido,string varDireccion,string varTelefono,string varCelular,string varMail,DateTime? varFechaAlta,string varComentarios,string varPaginaInicio,string varFirma1,string varFirma2,string varFirma3,string varAcceso1,string varAcceso2,string varAcceso3,string varAcceso4,string varAcceso5,string varAcceso6,short? varAvisarOc,short? varIdLugarPedidoComida,string varAcceso7,string varAcceso8,string varAcceso9,string varAcceso10,string varAcceso11,string varAcceso12,string varTipoLic,string varIniciales,short? varPciaUbicacion,string varNroTarjeta,short? varVersionTarjeta,short? varVisible,short? varAccesoRemoto,byte[] varFoto,byte[] varHuella,byte[] varHuella1,byte[] varHuella2,byte[] varHuella3) { PnUsuario item = new PnUsuario(); item.Login = varLogin; item.Passwd = varPasswd; item.Nombre = varNombre; item.Apellido = varApellido; item.Direccion = varDireccion; item.Telefono = varTelefono; item.Celular = varCelular; item.Mail = varMail; item.FechaAlta = varFechaAlta; item.Comentarios = varComentarios; item.PaginaInicio = varPaginaInicio; item.Firma1 = varFirma1; item.Firma2 = varFirma2; item.Firma3 = varFirma3; item.Acceso1 = varAcceso1; item.Acceso2 = varAcceso2; item.Acceso3 = varAcceso3; item.Acceso4 = varAcceso4; item.Acceso5 = varAcceso5; item.Acceso6 = varAcceso6; item.AvisarOc = varAvisarOc; item.IdLugarPedidoComida = varIdLugarPedidoComida; item.Acceso7 = varAcceso7; item.Acceso8 = varAcceso8; item.Acceso9 = varAcceso9; item.Acceso10 = varAcceso10; item.Acceso11 = varAcceso11; item.Acceso12 = varAcceso12; item.TipoLic = varTipoLic; item.Iniciales = varIniciales; item.PciaUbicacion = varPciaUbicacion; item.NroTarjeta = varNroTarjeta; item.VersionTarjeta = varVersionTarjeta; item.Visible = varVisible; item.AccesoRemoto = varAccesoRemoto; item.Foto = varFoto; item.Huella = varHuella; item.Huella1 = varHuella1; item.Huella2 = varHuella2; item.Huella3 = varHuella3; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdUsuario,string varLogin,string varPasswd,string varNombre,string varApellido,string varDireccion,string varTelefono,string varCelular,string varMail,DateTime? varFechaAlta,string varComentarios,string varPaginaInicio,string varFirma1,string varFirma2,string varFirma3,string varAcceso1,string varAcceso2,string varAcceso3,string varAcceso4,string varAcceso5,string varAcceso6,short? varAvisarOc,short? varIdLugarPedidoComida,string varAcceso7,string varAcceso8,string varAcceso9,string varAcceso10,string varAcceso11,string varAcceso12,string varTipoLic,string varIniciales,short? varPciaUbicacion,string varNroTarjeta,short? varVersionTarjeta,short? varVisible,short? varAccesoRemoto,byte[] varFoto,byte[] varHuella,byte[] varHuella1,byte[] varHuella2,byte[] varHuella3) { PnUsuario item = new PnUsuario(); item.IdUsuario = varIdUsuario; item.Login = varLogin; item.Passwd = varPasswd; item.Nombre = varNombre; item.Apellido = varApellido; item.Direccion = varDireccion; item.Telefono = varTelefono; item.Celular = varCelular; item.Mail = varMail; item.FechaAlta = varFechaAlta; item.Comentarios = varComentarios; item.PaginaInicio = varPaginaInicio; item.Firma1 = varFirma1; item.Firma2 = varFirma2; item.Firma3 = varFirma3; item.Acceso1 = varAcceso1; item.Acceso2 = varAcceso2; item.Acceso3 = varAcceso3; item.Acceso4 = varAcceso4; item.Acceso5 = varAcceso5; item.Acceso6 = varAcceso6; item.AvisarOc = varAvisarOc; item.IdLugarPedidoComida = varIdLugarPedidoComida; item.Acceso7 = varAcceso7; item.Acceso8 = varAcceso8; item.Acceso9 = varAcceso9; item.Acceso10 = varAcceso10; item.Acceso11 = varAcceso11; item.Acceso12 = varAcceso12; item.TipoLic = varTipoLic; item.Iniciales = varIniciales; item.PciaUbicacion = varPciaUbicacion; item.NroTarjeta = varNroTarjeta; item.VersionTarjeta = varVersionTarjeta; item.Visible = varVisible; item.AccesoRemoto = varAccesoRemoto; item.Foto = varFoto; item.Huella = varHuella; item.Huella1 = varHuella1; item.Huella2 = varHuella2; item.Huella3 = varHuella3; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdUsuarioColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn LoginColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn PasswdColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn ApellidoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn DireccionColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn TelefonoColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn CelularColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn MailColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn FechaAltaColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn ComentariosColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn PaginaInicioColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn Firma1Column { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn Firma2Column { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn Firma3Column { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn Acceso1Column { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn Acceso2Column { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn Acceso3Column { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn Acceso4Column { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn Acceso5Column { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn Acceso6Column { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn AvisarOcColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn IdLugarPedidoComidaColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn Acceso7Column { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn Acceso8Column { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn Acceso9Column { get { return Schema.Columns[25]; } } public static TableSchema.TableColumn Acceso10Column { get { return Schema.Columns[26]; } } public static TableSchema.TableColumn Acceso11Column { get { return Schema.Columns[27]; } } public static TableSchema.TableColumn Acceso12Column { get { return Schema.Columns[28]; } } public static TableSchema.TableColumn TipoLicColumn { get { return Schema.Columns[29]; } } public static TableSchema.TableColumn InicialesColumn { get { return Schema.Columns[30]; } } public static TableSchema.TableColumn PciaUbicacionColumn { get { return Schema.Columns[31]; } } public static TableSchema.TableColumn NroTarjetaColumn { get { return Schema.Columns[32]; } } public static TableSchema.TableColumn VersionTarjetaColumn { get { return Schema.Columns[33]; } } public static TableSchema.TableColumn VisibleColumn { get { return Schema.Columns[34]; } } public static TableSchema.TableColumn AccesoRemotoColumn { get { return Schema.Columns[35]; } } public static TableSchema.TableColumn FotoColumn { get { return Schema.Columns[36]; } } public static TableSchema.TableColumn HuellaColumn { get { return Schema.Columns[37]; } } public static TableSchema.TableColumn Huella1Column { get { return Schema.Columns[38]; } } public static TableSchema.TableColumn Huella2Column { get { return Schema.Columns[39]; } } public static TableSchema.TableColumn Huella3Column { get { return Schema.Columns[40]; } } #endregion #region Columns Struct public struct Columns { public static string IdUsuario = @"id_usuario"; public static string Login = @"login"; public static string Passwd = @"passwd"; public static string Nombre = @"nombre"; public static string Apellido = @"apellido"; public static string Direccion = @"direccion"; public static string Telefono = @"telefono"; public static string Celular = @"celular"; public static string Mail = @"mail"; public static string FechaAlta = @"fecha_alta"; public static string Comentarios = @"comentarios"; public static string PaginaInicio = @"pagina_inicio"; public static string Firma1 = @"firma1"; public static string Firma2 = @"firma2"; public static string Firma3 = @"firma3"; public static string Acceso1 = @"acceso1"; public static string Acceso2 = @"acceso2"; public static string Acceso3 = @"acceso3"; public static string Acceso4 = @"acceso4"; public static string Acceso5 = @"acceso5"; public static string Acceso6 = @"acceso6"; public static string AvisarOc = @"avisar_oc"; public static string IdLugarPedidoComida = @"id_lugar_pedido_comida"; public static string Acceso7 = @"acceso7"; public static string Acceso8 = @"acceso8"; public static string Acceso9 = @"acceso9"; public static string Acceso10 = @"acceso10"; public static string Acceso11 = @"acceso11"; public static string Acceso12 = @"acceso12"; public static string TipoLic = @"tipo_lic"; public static string Iniciales = @"iniciales"; public static string PciaUbicacion = @"pcia_ubicacion"; public static string NroTarjeta = @"nro_tarjeta"; public static string VersionTarjeta = @"version_tarjeta"; public static string Visible = @"visible"; public static string AccesoRemoto = @"acceso_remoto"; public static string Foto = @"foto"; public static string Huella = @"huella"; public static string Huella1 = @"huella1"; public static string Huella2 = @"huella2"; public static string Huella3 = @"huella3"; } #endregion #region Update PK Collections public void SetPKValues() { if (colPnGruposUsuarios != null) { foreach (DalSic.PnGruposUsuario item in colPnGruposUsuarios) { if (item.IdUsuario != IdUsuario) { item.IdUsuario = IdUsuario; } } } if (colPnPermisosActuales != null) { foreach (DalSic.PnPermisosActuale item in colPnPermisosActuales) { if (item.IdUsuario != IdUsuario) { item.IdUsuario = IdUsuario; } } } if (colPnPermisosSesionRecords != null) { foreach (DalSic.PnPermisosSesion item in colPnPermisosSesionRecords) { if (item.IdUsuario != IdUsuario) { item.IdUsuario = IdUsuario; } } } if (colPnPermisosUsuarios != null) { foreach (DalSic.PnPermisosUsuario item in colPnPermisosUsuarios) { if (item.IdUsuario != IdUsuario) { item.IdUsuario = IdUsuario; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colPnGruposUsuarios != null) { colPnGruposUsuarios.SaveAll(); } if (colPnPermisosActuales != null) { colPnPermisosActuales.SaveAll(); } if (colPnPermisosSesionRecords != null) { colPnPermisosSesionRecords.SaveAll(); } if (colPnPermisosUsuarios != null) { colPnPermisosUsuarios.SaveAll(); } } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace HUX.Collections { /// <summary> /// An Object Collection is simply a set of child objects organized with some /// layout parameters. The object collection can be used to quickly create /// control panels or sets of prefab/objects. /// </summary> public class ObjectCollection : MonoBehaviour { /// <summary> /// The type of surface to map the collect to. /// </summary> #region public members public enum SurfaceTypeEnum { Cylinder, Plane, Sphere, Scatter, } public enum SortTypeEnum { None, // Don't sort, just display in order received Transform, // Sort by transform order Alphabetical, // Sort by transform name TransformReversed, // Sort by transform order reversed AlphabeticalReversed, // Sort by transform name reversed } public enum OrientTypeEnum { None, // Don't rotate at all FaceOrigin, // Rotate towards the origin FaceOriginReversed, // Rotate towards the origin + 180 degrees FaceFoward, // Zero rotation FaceForwardReversed, // Zero rotation + 180 degrees } public enum LayoutTypeEnum { ColumnThenRow, // Sort by column, then by row RowThenColumn, // Sort by row, then by column } /// <summary> /// Collection node is a data storage class for individual data about an object in the collection. /// </summary> [System.Serializable] public class CollectionNode { public string Name; public Vector2 Offset; public float Radius; public Transform transform; } /// <summary> /// Action called when collection is updated /// </summary> public Action<ObjectCollection> OnCollectionUpdated; /// <summary> /// List of objects with generated data on the object. /// </summary> [SerializeField] public List<CollectionNode> NodeList = new List<CollectionNode>(); /// <summary> /// Type of surface to map the collection to. /// </summary> [Tooltip("Type of surface to map the collection to")] public SurfaceTypeEnum SurfaceType = SurfaceTypeEnum.Plane; /// <summary> /// Type of sorting to use. /// </summary> [Tooltip("Type of sorting to use")] public SortTypeEnum SortType = SortTypeEnum.None; /// <summary> /// Should the objects in the collection face the origin of the collection /// </summary> [Tooltip("Should the objects in the collection be rotated / how should they be rotated")] public OrientTypeEnum OrientType = OrientTypeEnum.FaceOrigin; /// <summary> /// Whether to sort objects by row first or by column first /// </summary> [Tooltip("Whether to sort objects by row first or by column first")] public LayoutTypeEnum LayoutType = LayoutTypeEnum.ColumnThenRow; /// <summary> /// This is the radius of either the Cylinder or Sphere mapping and is ignored when using the plane mapping. /// </summary> [Range(0.05f, 5.0f)] [Tooltip("Radius for the sphere or cylinder")] public float Radius = 2f; /// <summary> /// Number of rows per column, column number is automatically determined /// </summary> [Tooltip("Number of rows per column")] public int Rows = 3; /// <summary> /// Width of the cell per object in the collection. /// </summary> [Tooltip("Width of cell per object")] public float CellWidth = 0.5f; /// <summary> /// Height of the cell per object in the collection. /// </summary> [Tooltip("Height of cell per object")] public float CellHeight = 0.5f; /// <summary> /// Reference mesh to use for rendering the sphere layout /// </summary> [HideInInspector] public Mesh SphereMesh; /// <summary> /// Reference mesh to use for rendering the cylinder layout /// </summary> [HideInInspector] public Mesh CylinderMesh; #endregion #region private variables private int _columns; private float _width; private float _height; private float _circ; private Vector2 _halfCell; #endregion public float Width { get { return _width; } } public float Height { get { return _height; } } /// <summary> /// Update collection is called from the editor button on the inspector. /// This function rebuilds / updates the layout. /// </summary> public void UpdateCollection() { // Check for empty nodes and remove them List<CollectionNode> emptyNodes = new List<CollectionNode>(); for (int i = 0; i < NodeList.Count; i++) { if (NodeList[i].transform == null) { emptyNodes.Add(NodeList[i]); } } // Now delete the empty nodes foreach (CollectionNode node in emptyNodes) { NodeList.Remove(node); } emptyNodes.Clear(); // Check when children change and adjust for (int i = 0; i < this.transform.childCount; i++) { Transform child = this.transform.GetChild(i); if (!ContainsNode(child)) { CollectionNode node = new CollectionNode(); // TODO MICROSOFT: Initial offset node.Name = child.name; node.transform = child; NodeList.Add(node); } } switch (SortType) { case SortTypeEnum.None: break; case SortTypeEnum.Transform: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.transform.GetSiblingIndex().CompareTo(c2.transform.GetSiblingIndex()); }); break; case SortTypeEnum.Alphabetical: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.Name.CompareTo(c2.Name); }); break; case SortTypeEnum.AlphabeticalReversed: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.Name.CompareTo(c2.Name); }); NodeList.Reverse(); break; case SortTypeEnum.TransformReversed: NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.transform.GetSiblingIndex().CompareTo(c2.transform.GetSiblingIndex()); }); NodeList.Reverse(); break; } _columns = Mathf.CeilToInt((float)NodeList.Count / (float)Rows); _width = _columns * CellWidth; _height = Rows * CellHeight; _halfCell = new Vector2(CellWidth / 2f, CellHeight / 2f); _circ = 2f * Mathf.PI * Radius; LayoutChildren(); if (OnCollectionUpdated != null) { OnCollectionUpdated.Invoke(this); } } /// <summary> /// Internal function for laying out all the children when UpdateCollection is called. /// </summary> private void LayoutChildren() { int cellCounter = 0; float startOffsetX, startOffsetY; Vector3[] nodeGrid = new Vector3[NodeList.Count]; Vector3 newPos = Vector3.zero; Vector3 newRot = Vector3.zero; // Now lets lay out the grid startOffsetX = ((float)_columns / 2.0f) * CellWidth; startOffsetY = ((float)Rows / 2.0f) * CellHeight; cellCounter = 0; // First start with a grid then project onto surface switch (LayoutType) { case LayoutTypeEnum.ColumnThenRow: default: for (int c = 0; c < _columns; c++) { for (int r = 0; r < Rows; r++) { if (cellCounter < NodeList.Count) { nodeGrid[cellCounter] = new Vector3((c * CellWidth) - startOffsetX + _halfCell.x, (r * CellHeight) - startOffsetY + _halfCell.y, 0f) + (Vector3)((CollectionNode)(NodeList[cellCounter])).Offset; } cellCounter++; } } break; case LayoutTypeEnum.RowThenColumn: for (int r = 0; r < Rows; r++) { for (int c = 0; c < _columns; c++) { if (cellCounter < NodeList.Count) { nodeGrid[cellCounter] = new Vector3((c * CellWidth) - startOffsetX + _halfCell.x, (r * CellHeight) - startOffsetY + _halfCell.y, 0f) + (Vector3)((CollectionNode)(NodeList[cellCounter])).Offset; } cellCounter++; } } break; } switch (SurfaceType) { case SurfaceTypeEnum.Plane: for (int i = 0; i < NodeList.Count; i++) { newPos = nodeGrid[i]; NodeList[i].transform.localPosition = newPos; switch (OrientType) { case OrientTypeEnum.None: default: // Don't apply any rotation break; case OrientTypeEnum.FaceOrigin: case OrientTypeEnum.FaceFoward: NodeList[i].transform.forward = transform.forward; break; case OrientTypeEnum.FaceOriginReversed: case OrientTypeEnum.FaceForwardReversed: newRot = Vector3.zero; NodeList[i].transform.forward = transform.forward; NodeList[i].transform.Rotate(0f, 180f, 0f); break; } } break; case SurfaceTypeEnum.Cylinder: for (int i = 0; i < NodeList.Count; i++) { newPos = CylindricalMapping(nodeGrid[i], Radius); switch (OrientType) { case OrientTypeEnum.None: default: // Don't apply any rotation break; case OrientTypeEnum.FaceOrigin: newRot = new Vector3(newPos.x, 0.0f, newPos.z); NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); break; case OrientTypeEnum.FaceOriginReversed: newRot = new Vector3(newPos.x, 0f, newPos.z); NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.FaceFoward: NodeList[i].transform.forward = transform.forward; break; case OrientTypeEnum.FaceForwardReversed: NodeList[i].transform.forward = transform.forward; NodeList[i].transform.Rotate(0f, 180f, 0f); break; } NodeList[i].transform.localPosition = newPos; } break; case SurfaceTypeEnum.Sphere: for (int i = 0; i < NodeList.Count; i++) { newPos = SphericalMapping(nodeGrid[i], Radius); switch (OrientType) { case OrientTypeEnum.None: default: // Don't apply any rotation break; case OrientTypeEnum.FaceOrigin: newRot = newPos; NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); break; case OrientTypeEnum.FaceOriginReversed: newRot = newPos; NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); NodeList[i].transform.Rotate(0f, 180f, 0f); break; case OrientTypeEnum.FaceFoward: NodeList[i].transform.forward = transform.forward; break; case OrientTypeEnum.FaceForwardReversed: NodeList[i].transform.forward = transform.forward; NodeList[i].transform.Rotate(0f, 180f, 0f); break; } NodeList[i].transform.localPosition = newPos; } break; case SurfaceTypeEnum.Scatter: // TODO fix this rough first commit! Magic numbers galore! // Get randomized planar mapping // Calculate radius of each node while we're here // Then use the packer function to shift them into place for (int i = 0; i < NodeList.Count; i++) { newPos = ScatterMapping (nodeGrid[i], Radius); Collider nodeCollider = NodeList[i].transform.GetComponentInChildren<Collider>(); if (nodeCollider != null) { // Make the radius the largest of the object's dimensions to avoid overlap Bounds bounds = nodeCollider.bounds; NodeList[i].Radius = Mathf.Max (Mathf.Max(bounds.size.x, bounds.size.y), bounds.size.z) / 2; } else { // Make the radius a default value // TODO move this into a public field ? NodeList[i].Radius = 1f; } NodeList[i].transform.localPosition = newPos; switch (OrientType) { case OrientTypeEnum.None: default: // Don't apply any rotation break; case OrientTypeEnum.FaceOrigin: case OrientTypeEnum.FaceFoward: newRot = Vector3.zero; NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); break; case OrientTypeEnum.FaceOriginReversed: case OrientTypeEnum.FaceForwardReversed: newRot = Vector3.zero; NodeList[i].transform.rotation = Quaternion.LookRotation(newRot); NodeList[i].transform.Rotate(0f, 180f, 0f); break; } } // Iterate [x] times // TODO move center, iterations and padding into a public field for (int i = 0; i < 100; i++) { IterateScatterPacking (NodeList, Radius); } break; } } /// <summary> /// Internal function for getting the relative mapping based on a source Vec3 and a radius for spherical mapping. /// </summary> /// <param name="source">The source <see cref="Vector3"/> to be mapped to sphere</param> /// <param name="radius">This is a <see cref="float"/> for the radius of the sphere</param> /// <returns></returns> private Vector3 SphericalMapping(Vector3 source, float radius) { Vector3 newPos = new Vector3(0f, 0f, Radius); float xAngle = (source.x / _circ) * 360f; float yAngle = (source.y / _circ) * 360f; Quaternion rot = Quaternion.Euler(yAngle, xAngle, 0.0f); newPos = rot * newPos; return newPos; } /// <summary> /// Internal function for getting the relative mapping based on a source Vec3 and a radius for cylinder mapping. /// </summary> /// <param name="source">The source <see cref="Vector3"/> to be mapped to cylinder</param> /// <param name="radius">This is a <see cref="float"/> for the radius of the cylinder</param> /// <returns></returns> private Vector3 CylindricalMapping(Vector3 source, float radius) { Vector3 newPos = new Vector3(0f, source.y, Radius); float xAngle = (source.x / _circ) * 360f; Quaternion rot = Quaternion.Euler(0.0f, xAngle, 0.0f); newPos = rot * newPos; return newPos; } /// <summary> /// Internal function to check if a node exists in the NodeList. /// </summary> /// <param name="node">A <see cref="Transform"/> of the node to see if it's in the NodeList</param> /// <returns></returns> private bool ContainsNode(Transform node) { foreach (CollectionNode cn in NodeList) { if (cn != null) { if (cn.transform == node) return true; } } return false; } /// <summary> /// Internal function for randomized mapping based on a source Vec3 and a radius for randomization distance. /// </summary> /// <param name="source">The source <see cref="Vector3"/> to be mapped to cylinder</param> /// <param name="radius">This is a <see cref="float"/> for the radius of the cylinder</param> /// <returns></returns> private Vector3 ScatterMapping(Vector3 source, float radius) { source.x = UnityEngine.Random.Range(-radius, radius); source.y = UnityEngine.Random.Range(-radius, radius); return source; } /// <summary> /// Internal function to pack randomly spaced nodes so they don't overlap /// Usually requires about 25 iterations for decent packing /// </summary> /// <returns></returns> private void IterateScatterPacking(List<CollectionNode> nodes, float radiusPadding) { // Sort by closest to center (don't worry about z axis) // Use the position of the collection as the packing center // TODO make it possible to specify? nodes.Sort(delegate (CollectionNode circle1, CollectionNode circle2) { float distance1 = (circle1.transform.localPosition).sqrMagnitude; float distance2 = (circle2.transform.localPosition).sqrMagnitude; return distance1.CompareTo(distance2); }); Vector3 difference = Vector3.zero; Vector2 difference2D = Vector2.zero; // Move them closer together float radiusPaddingSquared = Mathf.Pow(radiusPadding, 2f); for (int i = 0; i < nodes.Count - 1; i++) { for (int j = i + 1; j < nodes.Count; j++) { if (i != j) { difference = nodes[j].transform.localPosition - nodes[i].transform.localPosition; // Ignore Z axis difference2D.x = difference.x; difference2D.y = difference.y; float combinedRadius = nodes[i].Radius + nodes[j].Radius; float distance = difference2D.SqrMagnitude() - radiusPaddingSquared; float minSeparation = Mathf.Min(distance, radiusPaddingSquared); distance -= minSeparation; if (distance < (Mathf.Pow(combinedRadius, 2))) { difference2D.Normalize(); difference *= ((combinedRadius - Mathf.Sqrt(distance)) * 0.5f); nodes[j].transform.localPosition += difference; nodes[i].transform.localPosition -= difference; } } } } } /// <summary> /// Gizmos to draw when the Collection is selected. /// </summary> protected virtual void OnDrawGizmosSelected() { Vector3 scale = (2f * Radius) * Vector3.one; switch (SurfaceType) { case SurfaceTypeEnum.Plane: break; case SurfaceTypeEnum.Cylinder: Gizmos.color = Color.green; Gizmos.DrawWireMesh(CylinderMesh, transform.position, transform.rotation, scale); break; case SurfaceTypeEnum.Sphere: Gizmos.color = Color.green; Gizmos.DrawWireMesh(SphereMesh, transform.position, transform.rotation, scale); break; } } } }
// 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.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Collections.Concurrent { /// <summary> /// Represents a thread-safe first-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the queue.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))] public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { // This implementation provides an unbounded, multi-producer multi-consumer queue // that supports the standard Enqueue/TryDequeue operations, as well as support for // snapshot enumeration (GetEnumerator, ToArray, CopyTo), peeking, and Count/IsEmpty. // It is composed of a linked list of bounded ring buffers, each of which has a head // and a tail index, isolated from each other to minimize false sharing. As long as // the number of elements in the queue remains less than the size of the current // buffer (Segment), no additional allocations are required for enqueued items. When // the number of items exceeds the size of the current segment, the current segment is // "frozen" to prevent further enqueues, and a new segment is linked from it and set // as the new tail segment for subsequent enqueues. As old segments are consumed by // dequeues, the head reference is updated to point to the segment that dequeuers should // try next. To support snapshot enumeration, segments also support the notion of // preserving for observation, whereby they avoid overwriting state as part of dequeues. // Any operation that requires a snapshot results in all current segments being // both frozen for enqueues and preserved for observation: any new enqueues will go // to new segments, and dequeuers will consume from the existing segments but without // overwriting the existing data. /// <summary>Initial length of the segments used in the queue.</summary> private const int InitialSegmentLength = 32; /// <summary> /// Maximum length of the segments used in the queue. This is a somewhat arbitrary limit: /// larger means that as long as we don't exceed the size, we avoid allocating more segments, /// but if we do exceed it, then the segment becomes garbage. /// </summary> private const int MaxSegmentLength = 1024 * 1024; /// <summary> /// Lock used to protect cross-segment operations, including any updates to <see cref="_tail"/> or <see cref="_head"/> /// and any operations that need to get a consistent view of them. /// </summary> private readonly object _crossSegmentLock; /// <summary>The current tail segment.</summary> private volatile ConcurrentQueueSegment<T> _tail; /// <summary>The current head segment.</summary> private volatile ConcurrentQueueSegment<T> _head; // SOS's ThreadPool command depends on this name /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class. /// </summary> public ConcurrentQueue() { _crossSegmentLock = new object(); _tail = _head = new ConcurrentQueueSegment<T>(InitialSegmentLength); } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class that contains elements copied /// from the specified collection. /// </summary> /// <param name="collection"> /// The collection whose elements are copied to the new <see cref="ConcurrentQueue{T}"/>. /// </param> /// <exception cref="System.ArgumentNullException">The <paramref name="collection"/> argument is null.</exception> public ConcurrentQueue(IEnumerable<T> collection) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } _crossSegmentLock = new object(); // Determine the initial segment size. We'll use the default, // unless the collection is known to be larger than that, in which // case we round its length up to a power of 2, as all segments must // be a power of 2 in length. int length = InitialSegmentLength; if (collection is ICollection<T> c) { int count = c.Count; if (count > length) { length = Math.Min(ConcurrentQueueSegment<T>.RoundUpToPowerOf2(count), MaxSegmentLength); } } // Initialize the segment and add all of the data to it. _tail = _head = new ConcurrentQueueSegment<T>(length); foreach (T item in collection) { Enqueue(item); } } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see /// cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array">Array</see> that is the destination of the /// elements copied from the <see cref="ConcurrentQueue{T}"/>. <paramref name="array"/> must have /// zero-based indexing. /// </param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Special-case when the Array is actually a T[], taking a faster path if (array is T[] szArray) { CopyTo(szArray, index); return; } // Validate arguments. if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } // Otherwise, fall back to the slower path that first copies the contents // to an array, and then uses that array's non-generic CopyTo to do the copy. ToArray().CopyTo(array, index); } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized => false; // always false, as true implies synchronization via SyncRoot /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="ICollection"/>. This property is not supported. /// </summary> /// <exception cref="NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default; } } /// <summary>Returns an enumerator that iterates through a collection.</summary> /// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator(); /// <summary> /// Attempts to add an object to the <see cref="Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the /// end of the <see cref="ConcurrentQueue{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Enqueue(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see cref="Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object /// from the beginning of the <see cref="ConcurrentQueue{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) => TryDequeue(out item); /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { get { // IsEmpty == !TryPeek. We use a "resultUsed:false" peek in order to avoid marking // segments as preserved for observation, making IsEmpty a cheaper way than either // TryPeek(out T) or Count == 0 to check whether any elements are in the queue. T ignoredResult; return !TryPeek(out ignoredResult, resultUsed: false); } } /// <summary>Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.</summary> /// <returns>A new array containing a snapshot of elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns> public T[] ToArray() { // Snap the current contents for enumeration. ConcurrentQueueSegment<T> head, tail; int headHead, tailTail; SnapForObservation(out head, out headHead, out tail, out tailTail); // Count the number of items in that snapped set, and use it to allocate an // array of the right size. long count = GetCount(head, headHead, tail, tailTail); T[] arr = new T[count]; // Now enumerate the contents, copying each element into the array. using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail)) { int i = 0; while (e.MoveNext()) { arr[i++] = e.Current; } Debug.Assert(count == i); } // And return it. return arr; } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { get { var spinner = new SpinWait(); while (true) { // Capture the head and tail, as well as the head's head and tail. ConcurrentQueueSegment<T> head = _head; ConcurrentQueueSegment<T> tail = _tail; int headHead = Volatile.Read(ref head._headAndTail.Head); int headTail = Volatile.Read(ref head._headAndTail.Tail); if (head == tail) { // There was a single segment in the queue. If the captured segments still // match, then we can trust the values to compute the segment's count. (It's // theoretically possible the values could have looped around and still exactly match, // but that would required at least ~4 billion elements to have been enqueued and // dequeued between the reads.) if (head == _head && tail == _tail && headHead == Volatile.Read(ref head._headAndTail.Head) && headTail == Volatile.Read(ref head._headAndTail.Tail)) { return GetCount(head, headHead, headTail); } } else if (head._nextSegment == tail) { // There were two segments in the queue. Get the positions from the tail, and as above, // if the captured values match the previous reads, return the sum of the counts from both segments. int tailHead = Volatile.Read(ref tail._headAndTail.Head); int tailTail = Volatile.Read(ref tail._headAndTail.Tail); if (head == _head && tail == _tail && headHead == Volatile.Read(ref head._headAndTail.Head) && headTail == Volatile.Read(ref head._headAndTail.Tail) && tailHead == Volatile.Read(ref tail._headAndTail.Head) && tailTail == Volatile.Read(ref tail._headAndTail.Tail)) { return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); } } else { // There were more than two segments in the queue. Fall back to taking the cross-segment lock, // which will ensure that the head and tail segments we read are stable (since the lock is needed to change them); // for the two-segment case above, we can simply rely on subsequent comparisons, but for the two+ case, we need // to be able to trust the internal segments between the head and tail. lock (_crossSegmentLock) { // Now that we hold the lock, re-read the previously captured head and tail segments and head positions. // If either has changed, start over. if (head == _head && tail == _tail) { // Get the positions from the tail, and as above, if the captured values match the previous reads, // we can use the values to compute the count of the head and tail segments. int tailHead = Volatile.Read(ref tail._headAndTail.Head); int tailTail = Volatile.Read(ref tail._headAndTail.Tail); if (headHead == Volatile.Read(ref head._headAndTail.Head) && headTail == Volatile.Read(ref head._headAndTail.Tail) && tailHead == Volatile.Read(ref tail._headAndTail.Head) && tailTail == Volatile.Read(ref tail._headAndTail.Tail)) { // We got stable values for the head and tail segments, so we can just compute the sizes // based on those and add them. Note that this and the below additions to count may overflow: previous // implementations allowed that, so we don't check, either, and it is theoretically possible for the // queue to store more than int.MaxValue items. int count = GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); // Now add the counts for each internal segment. Since there were segments before these, // for counting purposes we consider them to start at the 0th element, and since there is at // least one segment after each, each was frozen, so we can count until each's frozen tail. // With the cross-segment lock held, we're guaranteed that all of these internal segments are // consistent, as the head and tail segment can't be changed while we're holding the lock, and // dequeueing and enqueueing can only be done from the head and tail segments, which these aren't. for (ConcurrentQueueSegment<T> s = head._nextSegment!; s != tail; s = s._nextSegment!) { Debug.Assert(s._frozenForEnqueues, "Internal segment must be frozen as there's a following segment."); count += s._headAndTail.Tail - s.FreezeOffset; } return count; } } } } // We raced with enqueues/dequeues and captured an inconsistent picture of the queue. // Spin and try again. spinner.SpinOnce(); } } } /// <summary>Computes the number of items in a segment based on a fixed head and tail in that segment.</summary> private static int GetCount(ConcurrentQueueSegment<T> s, int head, int tail) { if (head != tail && head != tail - s.FreezeOffset) { head &= s._slotsMask; tail &= s._slotsMask; return head < tail ? tail - head : s._slots.Length - head + tail; } return 0; } /// <summary>Gets the number of items in snapped region.</summary> private static long GetCount(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail) { // All of the segments should have been both frozen for enqueues and preserved for observation. // Validate that here for head and tail; we'll validate it for intermediate segments later. Debug.Assert(head._preservedForObservation); Debug.Assert(head._frozenForEnqueues); Debug.Assert(tail._preservedForObservation); Debug.Assert(tail._frozenForEnqueues); long count = 0; // Head segment. We've already marked it as frozen for enqueues, so its tail position is fixed, // and we've already marked it as preserved for observation (before we grabbed the head), so we // can safely enumerate from its head to its tail and access its elements. int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset; if (headHead < headTail) { // Mask the head and tail for the head segment headHead &= head._slotsMask; headTail &= head._slotsMask; // Increase the count by either the one or two regions, based on whether tail // has wrapped to be less than head. count += headHead < headTail ? headTail - headHead : head._slots.Length - headHead + headTail; } // We've enumerated the head. If the tail is different from the head, we need to // enumerate the remaining segments. if (head != tail) { // Count the contents of each segment between head and tail, not including head and tail. // Since there were segments before these, for our purposes we consider them to start at // the 0th element, and since there is at least one segment after each, each was frozen // by the time we snapped it, so we can iterate until each's frozen tail. for (ConcurrentQueueSegment<T> s = head._nextSegment!; s != tail; s = s._nextSegment!) { Debug.Assert(s._preservedForObservation); Debug.Assert(s._frozenForEnqueues); count += s._headAndTail.Tail - s.FreezeOffset; } // Finally, enumerate the tail. As with the intermediate segments, there were segments // before this in the snapped region, so we can start counting from the beginning. Unlike // the intermediate segments, we can't just go until the Tail, as that could still be changing; // instead we need to go until the tail we snapped for observation. count += tailTail - tail.FreezeOffset; } // Return the computed count. return count; } /// <summary> /// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see /// cref="Array">Array</see>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentQueue{T}"/>. The <see cref="Array">Array</see> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } // Snap for enumeration ConcurrentQueueSegment<T> head, tail; int headHead, tailTail; SnapForObservation(out head, out headHead, out tail, out tailTail); // Get the number of items to be enumerated long count = GetCount(head, headHead, tail, tailTail); if (index > array.Length - count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } // Copy the items to the target array int i = index; using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail)) { while (e.MoveNext()) { array[i++] = e.Current; } } Debug.Assert(count == i - index); } /// <summary>Returns an enumerator that iterates through the <see cref="ConcurrentQueue{T}"/>.</summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentQueue{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the queue. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the queue. /// </remarks> public IEnumerator<T> GetEnumerator() { ConcurrentQueueSegment<T> head, tail; int headHead, tailTail; SnapForObservation(out head, out headHead, out tail, out tailTail); return Enumerate(head, headHead, tail, tailTail); } /// <summary> /// Gets the head and tail information of the current contents of the queue. /// After this call returns, the specified region can be enumerated any number /// of times and will not change. /// </summary> private void SnapForObservation(out ConcurrentQueueSegment<T> head, out int headHead, out ConcurrentQueueSegment<T> tail, out int tailTail) { lock (_crossSegmentLock) // _head and _tail may only change while the lock is held. { // Snap the head and tail head = _head; tail = _tail; Debug.Assert(head != null); Debug.Assert(tail != null); Debug.Assert(tail._nextSegment == null); // Mark them and all segments in between as preserving, and ensure no additional items // can be added to the tail. for (ConcurrentQueueSegment<T> s = head; ; s = s._nextSegment!) { s._preservedForObservation = true; if (s == tail) break; Debug.Assert(s._frozenForEnqueues); // any non-tail should already be marked } tail.EnsureFrozenForEnqueues(); // we want to prevent the tailTail from moving // At this point, any dequeues from any segment won't overwrite the value, and // none of the existing segments can have new items enqueued. headHead = Volatile.Read(ref head._headAndTail.Head); tailTail = Volatile.Read(ref tail._headAndTail.Tail); } } /// <summary>Gets the item stored in the <paramref name="i"/>th entry in <paramref name="segment"/>.</summary> private T GetItemWhenAvailable(ConcurrentQueueSegment<T> segment, int i) { Debug.Assert(segment._preservedForObservation); // Get the expected value for the sequence number int expectedSequenceNumberAndMask = (i + 1) & segment._slotsMask; // If the expected sequence number is not yet written, we're still waiting for // an enqueuer to finish storing it. Spin until it's there. if ((segment._slots[i].SequenceNumber & segment._slotsMask) != expectedSequenceNumberAndMask) { var spinner = new SpinWait(); while ((Volatile.Read(ref segment._slots[i].SequenceNumber) & segment._slotsMask) != expectedSequenceNumberAndMask) { spinner.SpinOnce(); } } // Return the value from the slot. return segment._slots[i].Item; } private IEnumerator<T> Enumerate(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail) { Debug.Assert(head._preservedForObservation); Debug.Assert(head._frozenForEnqueues); Debug.Assert(tail._preservedForObservation); Debug.Assert(tail._frozenForEnqueues); // Head segment. We've already marked it as not accepting any more enqueues, // so its tail position is fixed, and we've already marked it as preserved for // enumeration (before we grabbed its head), so we can safely enumerate from // its head to its tail. int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset; if (headHead < headTail) { headHead &= head._slotsMask; headTail &= head._slotsMask; if (headHead < headTail) { for (int i = headHead; i < headTail; i++) yield return GetItemWhenAvailable(head, i); } else { for (int i = headHead; i < head._slots.Length; i++) yield return GetItemWhenAvailable(head, i); for (int i = 0; i < headTail; i++) yield return GetItemWhenAvailable(head, i); } } // We've enumerated the head. If the tail is the same, we're done. if (head != tail) { // Each segment between head and tail, not including head and tail. Since there were // segments before these, for our purposes we consider it to start at the 0th element. for (ConcurrentQueueSegment<T> s = head._nextSegment!; s != tail; s = s._nextSegment!) { Debug.Assert(s._preservedForObservation, "Would have had to been preserved as a segment part of enumeration"); Debug.Assert(s._frozenForEnqueues, "Would have had to be frozen for enqueues as it's intermediate"); int sTail = s._headAndTail.Tail - s.FreezeOffset; for (int i = 0; i < sTail; i++) { yield return GetItemWhenAvailable(s, i); } } // Enumerate the tail. Since there were segments before this, we can just start at // its beginning, and iterate until the tail we already grabbed. tailTail -= tail.FreezeOffset; for (int i = 0; i < tailTail; i++) { yield return GetItemWhenAvailable(tail, i); } } } /// <summary>Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.</summary> /// <param name="item"> /// The object to add to the end of the <see cref="ConcurrentQueue{T}"/>. /// The value can be a null reference (Nothing in Visual Basic) for reference types. /// </param> public void Enqueue(T item) { // Try to enqueue to the current tail. if (!_tail.TryEnqueue(item)) { // If we're unable to, we need to take a slow path that will // try to add a new tail segment. EnqueueSlow(item); } } /// <summary>Adds to the end of the queue, adding a new segment if necessary.</summary> private void EnqueueSlow(T item) { while (true) { ConcurrentQueueSegment<T> tail = _tail; // Try to append to the existing tail. if (tail.TryEnqueue(item)) { return; } // If we were unsuccessful, take the lock so that we can compare and manipulate // the tail. Assuming another enqueuer hasn't already added a new segment, // do so, then loop around to try enqueueing again. lock (_crossSegmentLock) { if (tail == _tail) { // Make sure no one else can enqueue to this segment. tail.EnsureFrozenForEnqueues(); // We determine the new segment's length based on the old length. // In general, we double the size of the segment, to make it less likely // that we'll need to grow again. However, if the tail segment is marked // as preserved for observation, something caused us to avoid reusing this // segment, and if that happens a lot and we grow, we'll end up allocating // lots of wasted space. As such, in such situations we reset back to the // initial segment length; if these observations are happening frequently, // this will help to avoid wasted memory, and if they're not, we'll // relatively quickly grow again to a larger size. int nextSize = tail._preservedForObservation ? InitialSegmentLength : Math.Min(tail.Capacity * 2, MaxSegmentLength); var newTail = new ConcurrentQueueSegment<T>(nextSize); // Hook up the new tail. tail._nextSegment = newTail; _tail = newTail; } } } } /// <summary> /// Attempts to remove and return the object at the beginning of the <see /// cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns> /// true if an element was removed and returned from the beginning of the /// <see cref="ConcurrentQueue{T}"/> successfully; otherwise, false. /// </returns> public bool TryDequeue([MaybeNullWhen(false)] out T result) => _head.TryDequeue(out result) || // fast-path that operates just on the head segment TryDequeueSlow(out result); // slow path that needs to fix up segments /// <summary>Tries to dequeue an item, removing empty segments as needed.</summary> private bool TryDequeueSlow([MaybeNullWhen(false)] out T item) { while (true) { // Get the current head ConcurrentQueueSegment<T> head = _head; // Try to take. If we're successful, we're done. if (head.TryDequeue(out item)) { return true; } // Check to see whether this segment is the last. If it is, we can consider // this to be a moment-in-time empty condition (even though between the TryDequeue // check and this check, another item could have arrived). if (head._nextSegment == null) { item = default!; return false; } // At this point we know that head.Next != null, which means // this segment has been frozen for additional enqueues. But between // the time that we ran TryDequeue and checked for a next segment, // another item could have been added. Try to dequeue one more time // to confirm that the segment is indeed empty. Debug.Assert(head._frozenForEnqueues); if (head.TryDequeue(out item)) { return true; } // This segment is frozen (nothing more can be added) and empty (nothing is in it). // Update head to point to the next segment in the list, assuming no one's beat us to it. lock (_crossSegmentLock) { if (head == _head) { _head = head._nextSegment; } } } } /// <summary> /// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/> /// without removing it. /// </summary> /// <param name="result"> /// When this method returns, <paramref name="result"/> contains an object from /// the beginning of the <see cref="Concurrent.ConcurrentQueue{T}"/> or default(T) /// if the operation failed. /// </param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than peeking. /// </remarks> public bool TryPeek([MaybeNullWhen(false)] out T result) => TryPeek(out result, resultUsed: true); /// <summary>Attempts to retrieve the value for the first element in the queue.</summary> /// <param name="result">The value of the first element, if found.</param> /// <param name="resultUsed">true if the result is needed; otherwise false if only the true/false outcome is needed.</param> /// <returns>true if an element was found; otherwise, false.</returns> private bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed) { // Starting with the head segment, look through all of the segments // for the first one we can find that's not empty. ConcurrentQueueSegment<T> s = _head; while (true) { // Grab the next segment from this one, before we peek. // This is to be able to see whether the value has changed // during the peek operation. ConcurrentQueueSegment<T>? next = Volatile.Read(ref s._nextSegment); // Peek at the segment. If we find an element, we're done. if (s.TryPeek(out result, resultUsed)) { return true; } // The current segment was empty at the moment we checked. if (next != null) { // If prior to the peek there was already a next segment, then // during the peek no additional items could have been enqueued // to it and we can just move on to check the next segment. Debug.Assert(next == s._nextSegment); s = next; } else if (Volatile.Read(ref s._nextSegment) == null) { // The next segment is null. Nothing more to peek at. break; } // The next segment was null before we peeked but non-null after. // That means either when we peeked the first segment had // already been frozen but the new segment not yet added, // or that the first segment was empty and between the time // that we peeked and then checked _nextSegment, so many items // were enqueued that we filled the first segment and went // into the next. Since we need to peek in order, we simply // loop around again to peek on the same segment. The next // time around on this segment we'll then either successfully // peek or we'll find that next was non-null before peeking, // and we'll traverse to that segment. } result = default!; return false; } /// <summary> /// Removes all objects from the <see cref="ConcurrentQueue{T}"/>. /// </summary> public void Clear() { lock (_crossSegmentLock) { // Simply substitute a new segment for the existing head/tail, // as is done in the constructor. Operations currently in flight // may still read from or write to an existing segment that's // getting dropped, meaning that in flight operations may not be // linear with regards to this clear operation. To help mitigate // in-flight operations enqueuing onto the tail that's about to // be dropped, we first freeze it; that'll force enqueuers to take // this lock to synchronize and see the new tail. _tail.EnsureFrozenForEnqueues(); _tail = _head = new ConcurrentQueueSegment<T>(InitialSegmentLength); } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace VotingInfo.Database.Logic.Data { [Serializable] public abstract partial class CandidateLogicBase : LogicBase<CandidateLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<CandidateContract> Results; public CandidateLogicBase() { Results = new List<CandidateContract>(); } /// <summary> /// Run Candidate_Insert. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName ) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationId", fldLocationId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@CandidateName", fldCandidateName) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run Candidate_Insert. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationId", fldLocationId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@CandidateName", fldCandidateName) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(CandidateContract row) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationId", row.LocationId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@CandidateName", row.CandidateName) }); result = (int?)cmd.ExecuteScalar(); row.CandidateId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Data].[Candidate_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationId", row.LocationId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@CandidateName", row.CandidateName) }); result = (int?)cmd.ExecuteScalar(); row.CandidateId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<CandidateContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run Candidate_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> public virtual int Update(int fldCandidateId , int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) , new SqlParameter("@UserId", fldUserId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationId", fldLocationId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@CandidateName", fldCandidateName) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run Candidate_Update. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldCandidateId , int fldUserId , int fldContentInspectionId , int fldLocationId , int fldOrganizationId , string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Candidate_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) , new SqlParameter("@UserId", fldUserId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@LocationId", fldLocationId) , new SqlParameter("@OrganizationId", fldOrganizationId) , new SqlParameter("@CandidateName", fldCandidateName) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(CandidateContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", row.CandidateId) , new SqlParameter("@UserId", row.UserId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationId", row.LocationId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@CandidateName", row.CandidateName) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Candidate_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", row.CandidateId) , new SqlParameter("@UserId", row.UserId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@LocationId", row.LocationId) , new SqlParameter("@OrganizationId", row.OrganizationId) , new SqlParameter("@CandidateName", row.CandidateName) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<CandidateContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run Candidate_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldCandidateId">Value for CandidateId</param> public virtual int Delete(int fldCandidateId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run Candidate_Delete. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Candidate_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(CandidateContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", row.CandidateId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[Candidate_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", row.CandidateId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<CandidateContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldCandidateId ) { bool result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run Candidate_Search, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool Search(string fldCandidateName ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateName", fldCandidateName) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_Search, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool Search(string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateName", fldCandidateName) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Candidate_SelectAll, and return results as a list of CandidateRow. /// </summary> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectAll() { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_SelectAll, and return results as a list of CandidateRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Candidate_List, and return results as a list. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldCandidateName ) { List<ListItemContract> result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_List]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateName", fldCandidateName) }); using(var r = cmd.ExecuteReader()) result = ListItemLogic.ReadAllNow(r); } }); return result; } /// <summary> /// Run Candidate_List, and return results as a list. /// </summary> /// <param name="fldCandidateName">Value for CandidateName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldCandidateName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_List]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateName", fldCandidateName) }); using(var r = cmd.ExecuteReader()) return ListItemLogic.ReadAllNow(r); } } /// <summary> /// Run Candidate_SelectBy_CandidateId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_CandidateId(int fldCandidateId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_CandidateId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_SelectBy_CandidateId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_CandidateId(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_CandidateId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Candidate_SelectBy_UserId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_UserId(int fldUserId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_UserId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_SelectBy_UserId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_UserId(int fldUserId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_UserId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Candidate_SelectBy_ContentInspectionId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_ContentInspectionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_SelectBy_ContentInspectionId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_ContentInspectionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Candidate_SelectBy_LocationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_LocationId(int fldLocationId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_LocationId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_SelectBy_LocationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldLocationId">Value for LocationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_LocationId(int fldLocationId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_LocationId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@LocationId", fldLocationId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run Candidate_SelectBy_OrganizationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_OrganizationId(int fldOrganizationId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_OrganizationId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationId", fldOrganizationId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run Candidate_SelectBy_OrganizationId, and return results as a list of CandidateRow. /// </summary> /// <param name="fldOrganizationId">Value for OrganizationId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateRow.</returns> public virtual bool SelectBy_OrganizationId(int fldOrganizationId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[Candidate_SelectBy_OrganizationId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@OrganizationId", fldOrganizationId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new CandidateContract { CandidateId = reader.GetInt32(0), UserId = reader.GetInt32(1), ContentInspectionId = reader.GetInt32(2), LocationId = reader.GetInt32(3), OrganizationId = reader.GetInt32(4), CandidateName = reader.GetString(5), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(CandidateContract row) { if(row == null) return 0; if(row.CandidateId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(CandidateContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.CandidateId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<CandidateContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<CandidateContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Microsoft.AspNetCore.Routing.Constraints; namespace Microsoft.AspNetCore.Routing.Patterns { /// <summary> /// Contains factory methods for creating <see cref="RoutePattern"/> and related types. /// Use <see cref="Parse(string)"/> to parse a route pattern in /// string format. /// </summary> public static class RoutePatternFactory { private static readonly IReadOnlyDictionary<string, object?> EmptyDictionary = new ReadOnlyDictionary<string, object?>(new Dictionary<string, object?>()); private static readonly IReadOnlyDictionary<string, IReadOnlyList<RoutePatternParameterPolicyReference>> EmptyPoliciesDictionary = new ReadOnlyDictionary<string, IReadOnlyList<RoutePatternParameterPolicyReference>>(new Dictionary<string, IReadOnlyList<RoutePatternParameterPolicyReference>>()); /// <summary> /// Creates a <see cref="RoutePattern"/> from its string representation. /// </summary> /// <param name="pattern">The route pattern string to parse.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Parse(string pattern) { if (pattern == null) { throw new ArgumentNullException(nameof(pattern)); } return RoutePatternParser.Parse(pattern); } /// <summary> /// Creates a <see cref="RoutePattern"/> from its string representation along /// with provided default values and parameter policies. /// </summary> /// <param name="pattern">The route pattern string to parse.</param> /// <param name="defaults"> /// Additional default values to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the parsed route pattern. /// </param> /// <param name="parameterPolicies"> /// Additional parameter policies to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the parsed route pattern. /// Multiple policies can be specified for a key by providing a collection as the value. /// </param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Parse(string pattern, object? defaults, object? parameterPolicies) { if (pattern == null) { throw new ArgumentNullException(nameof(pattern)); } var original = RoutePatternParser.Parse(pattern); return PatternCore(original.RawText, Wrap(defaults), Wrap(parameterPolicies), requiredValues: null, original.PathSegments); } /// <summary> /// Creates a <see cref="RoutePattern"/> from its string representation along /// with provided default values and parameter policies. /// </summary> /// <param name="pattern">The route pattern string to parse.</param> /// <param name="defaults"> /// Additional default values to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the parsed route pattern. /// </param> /// <param name="parameterPolicies"> /// Additional parameter policies to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the parsed route pattern. /// Multiple policies can be specified for a key by providing a collection as the value. /// </param> /// <param name="requiredValues"> /// Route values that can be substituted for parameters in the route pattern. See remarks on <see cref="RoutePattern.RequiredValues"/>. /// </param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Parse(string pattern, object? defaults, object? parameterPolicies, object? requiredValues) { if (pattern == null) { throw new ArgumentNullException(nameof(pattern)); } var original = RoutePatternParser.Parse(pattern); return PatternCore(original.RawText, Wrap(defaults), Wrap(parameterPolicies), Wrap(requiredValues), original.PathSegments); } /// <summary> /// Creates a new instance of <see cref="RoutePattern"/> from a collection of segments. /// </summary> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern(IEnumerable<RoutePatternPathSegment> segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(null, null, null, null, segments); } /// <summary> /// Creates a new instance of <see cref="RoutePattern"/> from a collection of segments. /// </summary> /// <param name="rawText">The raw text to associate with the route pattern. May be null.</param> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern(string? rawText, IEnumerable<RoutePatternPathSegment> segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(rawText, null, null, null, segments); } /// <summary> /// Creates a <see cref="RoutePattern"/> from a collection of segments along /// with provided default values and parameter policies. /// </summary> /// <param name="defaults"> /// Additional default values to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// </param> /// <param name="parameterPolicies"> /// Additional parameter policies to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// Multiple policies can be specified for a key by providing a collection as the value. /// </param> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern( object? defaults, object? parameterPolicies, IEnumerable<RoutePatternPathSegment> segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(null, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } /// <summary> /// Creates a <see cref="RoutePattern"/> from a collection of segments along /// with provided default values and parameter policies. /// </summary> /// <param name="rawText">The raw text to associate with the route pattern. May be null.</param> /// <param name="defaults"> /// Additional default values to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// </param> /// <param name="parameterPolicies"> /// Additional parameter policies to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// Multiple policies can be specified for a key by providing a collection as the value. /// </param> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern( string? rawText, object? defaults, object? parameterPolicies, IEnumerable<RoutePatternPathSegment> segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(rawText, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } /// <summary> /// Creates a new instance of <see cref="RoutePattern"/> from a collection of segments. /// </summary> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern(params RoutePatternPathSegment[] segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(null, null, null, requiredValues: null, segments); } /// <summary> /// Creates a new instance of <see cref="RoutePattern"/> from a collection of segments. /// </summary> /// <param name="rawText">The raw text to associate with the route pattern. May be null.</param> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern(string rawText, params RoutePatternPathSegment[] segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(rawText, null, null, requiredValues: null, segments); } /// <summary> /// Creates a <see cref="RoutePattern"/> from a collection of segments along /// with provided default values and parameter policies. /// </summary> /// <param name="defaults"> /// Additional default values to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// </param> /// <param name="parameterPolicies"> /// Additional parameter policies to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// Multiple policies can be specified for a key by providing a collection as the value. /// </param> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern( object? defaults, object? parameterPolicies, params RoutePatternPathSegment[] segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(null, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } /// <summary> /// Creates a <see cref="RoutePattern"/> from a collection of segments along /// with provided default values and parameter policies. /// </summary> /// <param name="rawText">The raw text to associate with the route pattern.</param> /// <param name="defaults"> /// Additional default values to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// </param> /// <param name="parameterPolicies"> /// Additional parameter policies to associated with the route pattern. May be null. /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/> /// and then merged into the route pattern. /// Multiple policies can be specified for a key by providing a collection as the value. /// </param> /// <param name="segments">The collection of segments.</param> /// <returns>The <see cref="RoutePattern"/>.</returns> public static RoutePattern Pattern( string? rawText, object? defaults, object? parameterPolicies, params RoutePatternPathSegment[] segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } return PatternCore(rawText, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } private static RoutePattern PatternCore( string? rawText, RouteValueDictionary? defaults, RouteValueDictionary? parameterPolicies, RouteValueDictionary? requiredValues, IEnumerable<RoutePatternPathSegment> segments) { // We want to merge the segment data with the 'out of line' defaults and parameter policies. // // This means that for parameters that have 'out of line' defaults we will modify // the parameter to contain the default (same story for parameter policies). // // We also maintain a collection of defaults and parameter policies that will also // contain the values that don't match a parameter. // // It's important that these two views of the data are consistent. We don't want // values specified out of line to have a different behavior. Dictionary<string, object?>? updatedDefaults = null; if (defaults != null && defaults.Count > 0) { updatedDefaults = new Dictionary<string, object?>(defaults.Count, StringComparer.OrdinalIgnoreCase); foreach (var kvp in defaults) { updatedDefaults.Add(kvp.Key, kvp.Value); } } Dictionary<string, List<RoutePatternParameterPolicyReference>>? updatedParameterPolicies = null; if (parameterPolicies != null && parameterPolicies.Count > 0) { updatedParameterPolicies = new Dictionary<string, List<RoutePatternParameterPolicyReference>>(parameterPolicies.Count, StringComparer.OrdinalIgnoreCase); foreach (var kvp in parameterPolicies) { var policyReferences = new List<RoutePatternParameterPolicyReference>(); if (kvp.Value is IParameterPolicy parameterPolicy) { policyReferences.Add(ParameterPolicy(parameterPolicy)); } else if (kvp.Value is string) { // Constraint will convert string values into regex constraints policyReferences.Add(Constraint(kvp.Value)); } else if (kvp.Value is IEnumerable multiplePolicies) { foreach (var item in multiplePolicies) { // Constraint will convert string values into regex constraints policyReferences.Add(item is IParameterPolicy p ? ParameterPolicy(p) : Constraint(item)); } } else { throw new InvalidOperationException(Resources.FormatRoutePattern_InvalidConstraintReference( kvp.Value ?? "null", typeof(IRouteConstraint))); } updatedParameterPolicies.Add(kvp.Key, policyReferences); } } List<RoutePatternParameterPart>? parameters = null; var updatedSegments = segments.ToArray(); for (var i = 0; i < updatedSegments.Length; i++) { var segment = VisitSegment(updatedSegments[i]); updatedSegments[i] = segment; for (var j = 0; j < segment.Parts.Count; j++) { if (segment.Parts[j] is RoutePatternParameterPart parameter) { if (parameters == null) { parameters = new List<RoutePatternParameterPart>(); } parameters.Add(parameter); } } } // Each Required Value either needs to either: // 1. be null-ish // 2. have a corresponding parameter // 3. have a corresponding default that matches both key and value if (requiredValues != null) { foreach (var kvp in requiredValues) { // 1.be null-ish var found = RouteValueEqualityComparer.Default.Equals(string.Empty, kvp.Value); // 2. have a corresponding parameter if (!found && parameters != null) { for (var i = 0; i < parameters.Count; i++) { if (string.Equals(kvp.Key, parameters[i].Name, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } } // 3. have a corresponding default that matches both key and value if (!found && updatedDefaults != null && updatedDefaults.TryGetValue(kvp.Key, out var defaultValue) && RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue)) { found = true; } if (!found) { throw new InvalidOperationException( $"No corresponding parameter or default value could be found for the required value " + $"'{kvp.Key}={kvp.Value}'. A non-null required value must correspond to a route parameter or the " + $"route pattern must have a matching default value."); } } } return new RoutePattern( rawText, updatedDefaults ?? EmptyDictionary, updatedParameterPolicies != null ? updatedParameterPolicies.ToDictionary(kvp => kvp.Key, kvp => (IReadOnlyList<RoutePatternParameterPolicyReference>)kvp.Value.ToArray()) : EmptyPoliciesDictionary, requiredValues ?? EmptyDictionary, (IReadOnlyList<RoutePatternParameterPart>?)parameters ?? Array.Empty<RoutePatternParameterPart>(), updatedSegments); RoutePatternPathSegment VisitSegment(RoutePatternPathSegment segment) { RoutePatternPart[]? updatedParts = null; for (var i = 0; i < segment.Parts.Count; i++) { var part = segment.Parts[i]; var updatedPart = VisitPart(part); if (part != updatedPart) { if (updatedParts == null) { updatedParts = segment.Parts.ToArray(); } updatedParts[i] = updatedPart; } } if (updatedParts == null) { // Segment has not changed return segment; } return new RoutePatternPathSegment(updatedParts); } RoutePatternPart VisitPart(RoutePatternPart part) { if (!part.IsParameter) { return part; } var parameter = (RoutePatternParameterPart)part; var @default = parameter.Default; if (updatedDefaults != null && updatedDefaults.TryGetValue(parameter.Name, out var newDefault)) { if (parameter.Default != null && !Equals(newDefault, parameter.Default)) { var message = Resources.FormatTemplateRoute_CannotHaveDefaultValueSpecifiedInlineAndExplicitly(parameter.Name); throw new InvalidOperationException(message); } if (parameter.IsOptional) { var message = Resources.TemplateRoute_OptionalCannotHaveDefaultValue; throw new InvalidOperationException(message); } @default = newDefault; } if (parameter.Default != null) { if (updatedDefaults == null) { updatedDefaults = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase); } updatedDefaults[parameter.Name] = parameter.Default; } List<RoutePatternParameterPolicyReference>? parameterConstraints = null; if ((updatedParameterPolicies == null || !updatedParameterPolicies.TryGetValue(parameter.Name, out parameterConstraints)) && parameter.ParameterPolicies.Count > 0) { if (updatedParameterPolicies == null) { updatedParameterPolicies = new Dictionary<string, List<RoutePatternParameterPolicyReference>>(StringComparer.OrdinalIgnoreCase); } parameterConstraints = new List<RoutePatternParameterPolicyReference>(parameter.ParameterPolicies.Count); updatedParameterPolicies.Add(parameter.Name, parameterConstraints); } if (parameter.ParameterPolicies.Count > 0) { parameterConstraints!.AddRange(parameter.ParameterPolicies); } if (Equals(parameter.Default, @default) && parameter.ParameterPolicies.Count == 0 && (parameterConstraints?.Count ?? 0) == 0) { // Part has not changed return part; } return ParameterPartCore( parameter.Name, @default, parameter.ParameterKind, parameterConstraints?.ToArray() ?? Array.Empty<RoutePatternParameterPolicyReference>(), parameter.EncodeSlashes); } } /// <summary> /// Creates a <see cref="RoutePatternPathSegment"/> from the provided collection /// of parts. /// </summary> /// <param name="parts">The collection of parts.</param> /// <returns>The <see cref="RoutePatternPathSegment"/>.</returns> public static RoutePatternPathSegment Segment(IEnumerable<RoutePatternPart> parts) { if (parts == null) { throw new ArgumentNullException(nameof(parts)); } return SegmentCore(parts.ToArray()); } /// <summary> /// Creates a <see cref="RoutePatternPathSegment"/> from the provided collection /// of parts. /// </summary> /// <param name="parts">The collection of parts.</param> /// <returns>The <see cref="RoutePatternPathSegment"/>.</returns> public static RoutePatternPathSegment Segment(params RoutePatternPart[] parts) { if (parts == null) { throw new ArgumentNullException(nameof(parts)); } return SegmentCore((RoutePatternPart[])parts.Clone()); } private static RoutePatternPathSegment SegmentCore(RoutePatternPart[] parts) { return new RoutePatternPathSegment(parts); } /// <summary> /// Creates a <see cref="RoutePatternLiteralPart"/> from the provided text /// content. /// </summary> /// <param name="content">The text content.</param> /// <returns>The <see cref="RoutePatternLiteralPart"/>.</returns> public static RoutePatternLiteralPart LiteralPart(string content) { if (string.IsNullOrEmpty(content)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(content)); } if (content.IndexOf('?') >= 0) { throw new ArgumentException(Resources.FormatTemplateRoute_InvalidLiteral(content)); } return LiteralPartCore(content); } private static RoutePatternLiteralPart LiteralPartCore(string content) { return new RoutePatternLiteralPart(content); } /// <summary> /// Creates a <see cref="RoutePatternSeparatorPart"/> from the provided text /// content. /// </summary> /// <param name="content">The text content.</param> /// <returns>The <see cref="RoutePatternSeparatorPart"/>.</returns> public static RoutePatternSeparatorPart SeparatorPart(string content) { if (string.IsNullOrEmpty(content)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(content)); } return SeparatorPartCore(content); } private static RoutePatternSeparatorPart SeparatorPartCore(string content) { return new RoutePatternSeparatorPart(content); } /// <summary> /// Creates a <see cref="RoutePatternParameterPart"/> from the provided parameter name. /// </summary> /// <param name="parameterName">The parameter name.</param> /// <returns>The <see cref="RoutePatternParameterPart"/>.</returns> public static RoutePatternParameterPart ParameterPart(string parameterName) { if (string.IsNullOrEmpty(parameterName)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(parameterName)); } if (parameterName.IndexOfAny(RoutePatternParser.InvalidParameterNameChars) >= 0) { throw new ArgumentException(Resources.FormatTemplateRoute_InvalidParameterName(parameterName)); } return ParameterPartCore( parameterName: parameterName, @default: null, parameterKind: RoutePatternParameterKind.Standard, parameterPolicies: Array.Empty<RoutePatternParameterPolicyReference>()); } /// <summary> /// Creates a <see cref="RoutePatternParameterPart"/> from the provided parameter name /// and default value. /// </summary> /// <param name="parameterName">The parameter name.</param> /// <param name="default">The parameter default value. May be <c>null</c>.</param> /// <returns>The <see cref="RoutePatternParameterPart"/>.</returns> public static RoutePatternParameterPart ParameterPart(string parameterName, object @default) { if (string.IsNullOrEmpty(parameterName)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(parameterName)); } if (parameterName.IndexOfAny(RoutePatternParser.InvalidParameterNameChars) >= 0) { throw new ArgumentException(Resources.FormatTemplateRoute_InvalidParameterName(parameterName)); } return ParameterPartCore( parameterName: parameterName, @default: @default, parameterKind: RoutePatternParameterKind.Standard, parameterPolicies: Array.Empty<RoutePatternParameterPolicyReference>()); } /// <summary> /// Creates a <see cref="RoutePatternParameterPart"/> from the provided parameter name /// and default value, and parameter kind. /// </summary> /// <param name="parameterName">The parameter name.</param> /// <param name="default">The parameter default value. May be <c>null</c>.</param> /// <param name="parameterKind">The parameter kind.</param> /// <returns>The <see cref="RoutePatternParameterPart"/>.</returns> public static RoutePatternParameterPart ParameterPart( string parameterName, object? @default, RoutePatternParameterKind parameterKind) { if (string.IsNullOrEmpty(parameterName)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(parameterName)); } if (parameterName.IndexOfAny(RoutePatternParser.InvalidParameterNameChars) >= 0) { throw new ArgumentException(Resources.FormatTemplateRoute_InvalidParameterName(parameterName)); } if (@default != null && parameterKind == RoutePatternParameterKind.Optional) { throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue); } return ParameterPartCore( parameterName: parameterName, @default: @default, parameterKind: parameterKind, parameterPolicies: Array.Empty<RoutePatternParameterPolicyReference>()); } /// <summary> /// Creates a <see cref="RoutePatternParameterPart"/> from the provided parameter name /// and default value, parameter kind, and parameter policies. /// </summary> /// <param name="parameterName">The parameter name.</param> /// <param name="default">The parameter default value. May be <c>null</c>.</param> /// <param name="parameterKind">The parameter kind.</param> /// <param name="parameterPolicies">The parameter policies to associated with the parameter.</param> /// <returns>The <see cref="RoutePatternParameterPart"/>.</returns> public static RoutePatternParameterPart ParameterPart( string parameterName, object? @default, RoutePatternParameterKind parameterKind, IEnumerable<RoutePatternParameterPolicyReference> parameterPolicies) { if (string.IsNullOrEmpty(parameterName)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(parameterName)); } if (parameterName.IndexOfAny(RoutePatternParser.InvalidParameterNameChars) >= 0) { throw new ArgumentException(Resources.FormatTemplateRoute_InvalidParameterName(parameterName)); } if (@default != null && parameterKind == RoutePatternParameterKind.Optional) { throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue); } if (parameterPolicies == null) { throw new ArgumentNullException(nameof(parameterPolicies)); } return ParameterPartCore( parameterName: parameterName, @default: @default, parameterKind: parameterKind, parameterPolicies: parameterPolicies.ToArray()); } /// <summary> /// Creates a <see cref="RoutePatternParameterPart"/> from the provided parameter name /// and default value, parameter kind, and parameter policies. /// </summary> /// <param name="parameterName">The parameter name.</param> /// <param name="default">The parameter default value. May be <c>null</c>.</param> /// <param name="parameterKind">The parameter kind.</param> /// <param name="parameterPolicies">The parameter policies to associated with the parameter.</param> /// <returns>The <see cref="RoutePatternParameterPart"/>.</returns> public static RoutePatternParameterPart ParameterPart( string parameterName, object? @default, RoutePatternParameterKind parameterKind, params RoutePatternParameterPolicyReference[] parameterPolicies) { if (string.IsNullOrEmpty(parameterName)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(parameterName)); } if (parameterName.IndexOfAny(RoutePatternParser.InvalidParameterNameChars) >= 0) { throw new ArgumentException(Resources.FormatTemplateRoute_InvalidParameterName(parameterName)); } if (@default != null && parameterKind == RoutePatternParameterKind.Optional) { throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue); } if (parameterPolicies == null) { throw new ArgumentNullException(nameof(parameterPolicies)); } return ParameterPartCore( parameterName: parameterName, @default: @default, parameterKind: parameterKind, parameterPolicies: (RoutePatternParameterPolicyReference[])parameterPolicies.Clone()); } private static RoutePatternParameterPart ParameterPartCore( string parameterName, object? @default, RoutePatternParameterKind parameterKind, RoutePatternParameterPolicyReference[] parameterPolicies) { return ParameterPartCore(parameterName, @default, parameterKind, parameterPolicies, encodeSlashes: true); } private static RoutePatternParameterPart ParameterPartCore( string parameterName, object? @default, RoutePatternParameterKind parameterKind, RoutePatternParameterPolicyReference[] parameterPolicies, bool encodeSlashes) { return new RoutePatternParameterPart( parameterName, @default, parameterKind, parameterPolicies, encodeSlashes); } /// <summary> /// Creates a <see cref="RoutePatternParameterPolicyReference"/> from the provided contraint. /// </summary> /// <param name="constraint"> /// The constraint object, which must be of type <see cref="IRouteConstraint"/> /// or <see cref="string"/>. If the constraint object is a <see cref="string"/> /// then it will be transformed into an instance of <see cref="RegexRouteConstraint"/>. /// </param> /// <returns>The <see cref="RoutePatternParameterPolicyReference"/>.</returns> public static RoutePatternParameterPolicyReference Constraint(object constraint) { // Similar to RouteConstraintBuilder if (constraint is IRouteConstraint policy) { return ParameterPolicyCore(policy); } else if (constraint is string content) { return ParameterPolicyCore(new RegexRouteConstraint("^(" + content + ")$")); } else { throw new InvalidOperationException(Resources.FormatRoutePattern_InvalidConstraintReference( constraint ?? "null", typeof(IRouteConstraint))); } } /// <summary> /// Creates a <see cref="RoutePatternParameterPolicyReference"/> from the provided constraint. /// </summary> /// <param name="constraint"> /// The constraint object. /// </param> /// <returns>The <see cref="RoutePatternParameterPolicyReference"/>.</returns> public static RoutePatternParameterPolicyReference Constraint(IRouteConstraint constraint) { if (constraint == null) { throw new ArgumentNullException(nameof(constraint)); } return ParameterPolicyCore(constraint); } /// <summary> /// Creates a <see cref="RoutePatternParameterPolicyReference"/> from the provided constraint. /// </summary> /// <param name="constraint"> /// The constraint text, which will be resolved by <see cref="ParameterPolicyFactory"/>. /// </param> /// <returns>The <see cref="RoutePatternParameterPolicyReference"/>.</returns> public static RoutePatternParameterPolicyReference Constraint(string constraint) { if (string.IsNullOrEmpty(constraint)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(constraint)); } return ParameterPolicyCore(constraint); } /// <summary> /// Creates a <see cref="RoutePatternParameterPolicyReference"/> from the provided object. /// </summary> /// <param name="parameterPolicy"> /// The parameter policy object. /// </param> /// <returns>The <see cref="RoutePatternParameterPolicyReference"/>.</returns> public static RoutePatternParameterPolicyReference ParameterPolicy(IParameterPolicy parameterPolicy) { if (parameterPolicy == null) { throw new ArgumentNullException(nameof(parameterPolicy)); } return ParameterPolicyCore(parameterPolicy); } /// <summary> /// Creates a <see cref="RoutePatternParameterPolicyReference"/> from the provided object. /// </summary> /// <param name="parameterPolicy"> /// The parameter policy text, which will be resolved by <see cref="ParameterPolicyFactory"/>. /// </param> /// <returns>The <see cref="RoutePatternParameterPolicyReference"/>.</returns> public static RoutePatternParameterPolicyReference ParameterPolicy(string parameterPolicy) { if (string.IsNullOrEmpty(parameterPolicy)) { throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(parameterPolicy)); } return ParameterPolicyCore(parameterPolicy); } private static RoutePatternParameterPolicyReference ParameterPolicyCore(string parameterPolicy) { return new RoutePatternParameterPolicyReference(parameterPolicy); } private static RoutePatternParameterPolicyReference ParameterPolicyCore(IParameterPolicy parameterPolicy) { return new RoutePatternParameterPolicyReference(parameterPolicy); } private static RouteValueDictionary? Wrap(object? values) { return values == null ? null : new RouteValueDictionary(values); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.IO; using System.Xml.Linq; using System.Collections; using System.Xml.XPath; using System.Xml; using System.Reflection; using System.Text.RegularExpressions; using System.IO.Compression; namespace Template10.MSBUILD { /// <summary> /// A custom MS BUILD Task that generates a Project Template ZIP file /// and copies to the specified location. This is used to covert the existing /// Template 10 projects into project templates for deployment via the /// the VSIX. /// </summary> public class VSTemplateBuildTask : Microsoft.Build.Utilities.Task { #region ---- Private Variables ---------------- private string tempFolder; private ItemFolder topFolder; bool helpFileReferenceExists = false; #endregion #region ---- public properties ------- /// <summary> /// Gets or sets the csproj file. /// </summary> /// <value> /// The csproj file. /// </value> [Required] public string CsprojFile { get; set; } /// <summary> /// Gets or sets the name of the zip. /// </summary> /// <value> /// The name of the zip. /// </value> [Required] public string ZipName { get; set; } /// <summary> /// Gets or sets the help URL. /// </summary> /// <value> /// The help URL. /// </value> [Required] public string HelpUrl { get; set; } /// <summary> /// Gets or sets the project description. /// </summary> /// <value> /// The project description. /// </value> [Required] public string ProjectDescription { get; set; } /// <summary> /// Gets or sets the preview image path. /// </summary> /// <value> /// The preview image path. /// </value> [Required] public string PreviewImagePath { get; set; } /// <summary> /// Gets or sets the name of the project friendly. /// </summary> /// <value> /// The name of the project friendly. /// </value> [Required] public string ProjectFriendlyName { get; set; } /// <summary> /// Gets or sets the source dir. /// </summary> /// <value> /// The source dir. /// </value> [Required] public string SourceDir { get; set; } public string TargetDir2 { get; set; } /// <summary> /// Gets or sets the target dir. /// </summary> /// <value> /// The target dir. /// </value> public string TargetDir { get; set; } #endregion /// <summary> /// Executes this instance. /// </summary> /// <returns></returns> public override bool Execute() { helpFileReferenceExists = false; tempFolder = Path.Combine(TargetDir, Constants.TEMPFOLDER); if (Directory.Exists(tempFolder)) { Directory.Delete(tempFolder, true); } string projectFolder = Path.GetDirectoryName(CsprojFile); CopyProjectFilesToTempFolder(projectFolder, tempFolder); ReplaceNamespace(tempFolder); FileHelper.DeleteKey(tempFolder); ProcessVSTemplate(tempFolder); OperateOnCsProj(tempFolder, CsprojFile); OperateOnManifest(Path.Combine(tempFolder, "Package.appxmanifest")); CopyEmbeddedFilesToOutput(tempFolder); string jsonProj = Path.Combine(tempFolder, Constants.PROJECTJSON); AddTemplate10Nuget(jsonProj); SetupHelpFile(Path.Combine(tempFolder, Constants.HELPHTML), HelpUrl); ZipFiles(tempFolder, ZipName, TargetDir); return true; } /// <summary> /// Replaces the namespace. /// </summary> /// <param name="tempFolder">The temporary folder.</param> private void ReplaceNamespace(string tempFolder) { string csprojXml = FileHelper.ReadFile(CsprojFile); string rootNamespace = GetExistingRootNamespace(csprojXml); var ext = new List<string> { ".cs", ".xaml"}; var files = Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories).Where(s => ext.Any(e => s.EndsWith(e))); foreach (var file in files) { string text = FileHelper.ReadFile(file); //TODO: think about a safer way to do this... what if there is another use of RootNamespace string elsewhere... this will break the generated project. text = text.Replace(rootNamespace, "$safeprojectname$"); FileHelper.WriteFile(file, text); } } /// <summary> /// Operates the on manifest. /// </summary> /// <param name="manifestFile">The manifest file.</param> private void OperateOnManifest(string manifestFile) { string manifestText = FileHelper.ReadFile(manifestFile); var replacements = new List<FindReplaceItem>(); replacements.Add(new FindReplaceItem() { Pattern = "<mp:PhoneIdentity(.*?)/>", Replacement = @"<mp:PhoneIdentity PhoneProductId=""$$guid9$$"" PhonePublisherId=""00000000-0000-0000-0000-000000000000""/>" }); replacements.Add(new FindReplaceItem() { Pattern = "<DisplayName>(.*?)</DisplayName>", Replacement = @"<DisplayName>$$projectname$$</DisplayName>" }); replacements.Add(new FindReplaceItem() { Pattern = "<PublisherDisplayName>(.*?)</PublisherDisplayName>", Replacement = @"<PublisherDisplayName>$$XmlEscapedPublisher$$</PublisherDisplayName>" }); replacements.Add(new FindReplaceItem() { Pattern = @"Executable=""(.*?)""", Replacement = @"Executable=""$$targetnametoken$$.exe""" }); replacements.Add(new FindReplaceItem() { Pattern = @"EntryPoint=""(.*?)""", Replacement = @"EntryPoint=""$$safeprojectname$$.App""" }); replacements.Add(new FindReplaceItem() { Pattern = @"DisplayName=""(.*?)""", Replacement = @"DisplayName=""$$projectname$$.App""" }); replacements.Add(new FindReplaceItem() { Pattern = @"EntryPoint=""(.*?)""", Replacement = @"EntryPoint=""$$projectname$$.App""" }); foreach (var item in replacements) { manifestText = Regex.Replace(manifestText, item.Pattern, item.Replacement); } manifestText = ReplaceIdentityNode(manifestText); FileHelper.WriteFile(manifestFile, manifestText); } /// <summary> /// Adds the template10 nuget. /// </summary> /// <param name="jsonProj">The json proj.</param> private void AddTemplate10Nuget(string jsonProj) { string txt = FileHelper.ReadFile(jsonProj); if (txt.Contains(Constants.TEMPLATE10)) { return; } string template10Txt = Constants.TEMPLATE10PROJECTJSON; string newtonsoft = Constants.NEWTONSOFT_PROJECTJSON; txt = txt.Insert(txt.IndexOf(newtonsoft) + newtonsoft.Length, ",\n\r" + template10Txt); FileHelper.WriteFile(jsonProj, txt); } /// <summary> /// Sets up the help file, basically changing the redirect. /// </summary> /// <param name="helpFile">The help file.</param> /// <param name="helpUrl">The help URL.</param> private void SetupHelpFile(string helpFile, string helpUrl) { if (!File.Exists(helpFile)) return; string helpText = FileHelper.ReadFile(helpFile); helpText = helpText.Replace(Constants.HELPURL, helpUrl); FileHelper.WriteFile(helpFile, helpText); } /// <summary> /// Copies the project files to temporary folder. /// </summary> /// <param name="projectFolder">The project folder.</param> /// <param name="tempFolder">The temporary folder.</param> private void CopyProjectFilesToTempFolder(string projectFolder, string tempFolder) { FileHelper.DirectoryCopy(projectFolder, tempFolder, true); } /// <summary> /// Processes the vs template. /// </summary> /// <param name="tempFolder">The temporary folder.</param> private void ProcessVSTemplate(string tempFolder) { string xml = FileHelper.ReadFile(CsprojFile); string projectName = Path.GetFileName(CsprojFile); string projXml = GetProjectNode(xml, projectName); xml = Constants.VSTEMPLATETEXT.Replace(Constants.PROJECTNODE, projXml); xml = xml.Replace(Constants.TEMPLATENAME, ProjectFriendlyName); xml = xml.Replace(Constants.TEMPLATEDESCRIPTION, ProjectDescription); string previewFileName = Path.GetFileName(PreviewImagePath); xml = xml.Replace(Constants.PREVIEWIMAGEFILE, previewFileName); string filePath = Path.Combine(tempFolder, Constants.VSTEMPLATENAME); FileHelper.WriteFile(filePath, xml); } /// <summary> /// Zips the files. /// </summary> /// <param name="tempFolder">The temporary folder.</param> /// <param name="zipName">Name of the zip.</param> /// <param name="targetDir">The target dir.</param> private void ZipFiles(string tempFolder, string zipName, string targetDir) { string zipFileName = Path.Combine(targetDir, ZipName); string zipFileName2 = Path.Combine(TargetDir2, ZipName); if (File.Exists(zipFileName)) { File.Delete(zipFileName); } ZipFile.CreateFromDirectory(tempFolder, zipFileName); //-- now second one... File.Copy(zipFileName, zipFileName2, true); //-- clean up the temporary folder Directory.Delete(tempFolder, true); } /// <summary> /// Copies the embedded files to output. /// </summary> /// <param name="targetDir">The target dir.</param> private void CopyEmbeddedFilesToOutput(string targetDir) { string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); foreach (var item in names) { using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(item)) { var targetFile = Path.Combine(targetDir, Path.GetFileName(item.Substring(item.LastIndexOf("EmbeddedFiles.") + 14))); using (var fileStream = File.Create(targetFile)) { s.Seek(0, SeekOrigin.Begin); s.CopyTo(fileStream); } } } } /// <summary> /// Operates the on cs proj. /// </summary> /// <param name="tempFolder">The temporary folder.</param> /// <param name="csprojFile">The csproj file.</param> private void OperateOnCsProj(string tempFolder, string csprojFile) { string fileName = Path.GetFileName(CsprojFile); string targetPath = Path.Combine(tempFolder, fileName); File.Copy(CsprojFile, targetPath, true); string csprojText = FileHelper.ReadFile(targetPath); var replacements = new List<FindReplaceItem>(); replacements.Add(new FindReplaceItem() { Pattern = @"<PackageCertificateKeyFile>(.*?)</PackageCertificateKeyFile>", Replacement = @"<PackageCertificateKeyFile>$$projectname$$_TemporaryKey.pfx</PackageCertificateKeyFile>" }); replacements.Add(new FindReplaceItem() { Pattern = "<RootNamespace>(.*?)</RootNamespace>", Replacement = "<RootNamespace>$$safeprojectname$$</RootNamespace>" }); replacements.Add(new FindReplaceItem() { Pattern = "<AssemblyName>(.*?)</AssemblyName>", Replacement = "<AssemblyName>$$safeprojectname$$</AssemblyName>" }); replacements.Add(new FindReplaceItem() { Pattern = @"<None Include=""(.*?)_TemporaryKey.pfx"" />", Replacement = @"<None Include=""$$projectname$$_TemporaryKey.pfx"" />" }); replacements.Add(new FindReplaceItem() { Pattern = @"<ProjectGuid>(.*?)</ProjectGuid>", Replacement = @"<ProjectGuid>$guid1$</ProjectGuid>" }); foreach (var item in replacements) { csprojText = Regex.Replace(csprojText, item.Pattern, item.Replacement); } csprojText = RemoveItemNodeAround(@"csproj", csprojText); csprojText = AddHelpToCSProj(csprojText); FileHelper.WriteFile(targetPath, csprojText); } /// <summary> /// Adds the help to cs proj. /// </summary> /// <param name="csprojText">The csproj text.</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> private string AddHelpToCSProj(string csprojText) { //<Content Include="Help.htm" /> // <Content Include="Properties\Default.rd.xml" /> if (csprojText.ToLower().Contains("help.htm")) { return csprojText; } string findText = @"<Content Include=""Properties\Default.rd.xml"" />"; string helpText = @"<Content Include=""Help.htm"" />"; csprojText = csprojText.Replace(findText, helpText + findText); return csprojText; } /// <summary> /// Gets the existing root namespace. /// </summary> /// <param name="csprojxml">The csprojxml.</param> /// <returns></returns> private string GetExistingRootNamespace(string csprojxml) { XDocument xdoc; using (StringReader sr = new StringReader(csprojxml)) { xdoc = XDocument.Load(sr, LoadOptions.None); } XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; return xdoc.Descendants(ns + "RootNamespace").FirstOrDefault().Value; } /// <summary> /// Removes the item node around the specified text. This is used to remove the csproj reference in the csproj file which will be replaced by a project.json NuGet reference instead. /// </summary> /// <param name="findText">The find text.</param> /// <param name="csprojText">The csproj text.</param> /// <returns></returns> private string RemoveItemNodeAround(string findText, string csprojText) { if (!csprojText.Contains(findText)) { return csprojText; } int findTextIndex, start, end; string firstHalf, lastHalf; findTextIndex = csprojText.IndexOf(findText); start = csprojText.Substring(0, findTextIndex).LastIndexOf("<ItemGroup>"); end = csprojText.IndexOf("</ItemGroup>", findTextIndex); firstHalf = csprojText.Substring(0, start); lastHalf = csprojText.Substring(end + 12); return firstHalf + lastHalf; } /// <summary> /// Replaces the identity node. /// </summary> /// <param name="manifestText">The manifest text.</param> /// <returns></returns> private string ReplaceIdentityNode(string manifestText) { string findText = @"<Identity"; if (!manifestText.Contains(findText)) { return manifestText; } string identityReplacementText = @"<Identity Name=""$guid9$"" Publisher = ""$XmlEscapedPublisherDistinguishedName$"" Version = ""1.0.0.0"" /> "; int findTextIndex, start, end; string firstHalf, lastHalf; findTextIndex = manifestText.IndexOf(findText); start = findTextIndex; end = manifestText.IndexOf("/>", findTextIndex); firstHalf = manifestText.Substring(0, start); lastHalf = manifestText.Substring(end + 2); return firstHalf + identityReplacementText + lastHalf; } /// <summary> /// Gets the project node. /// </summary> /// <param name="csprojxml">The csprojxml.</param> /// <param name="projectFileName">Name of the project file.</param> /// <returns></returns> public string GetProjectNode(string csprojxml, string projectFileName) { string projectNodeStart = @"<Project TargetFileName=""$projectName"" File=""$projectName"" ReplaceParameters=""true"">"; projectNodeStart = projectNodeStart.Replace("$projectName", projectFileName); //string projectName = GetProjectName(csprojxml); List<string> projectItems = GetProjectItems(csprojxml); //-- sorting for directories projectItems = SortProjectItems(projectItems); GetItemFolder(projectItems); string foldersString = SerializeFolder(topFolder); if (!helpFileReferenceExists) { foldersString = InsertHelp(foldersString); } using (StringWriter writer = new StringWriter()) { writer.WriteLine(projectNodeStart); writer.WriteLine(foldersString); writer.WriteLine("</Project>"); return writer.ToString(); } } /// <summary> /// Inserts the help. /// </summary> /// <param name="foldersString">The folders string.</param> /// <returns></returns> private string InsertHelp(string foldersString) { string helpString = @"<ProjectItem ReplaceParameters=""false"" TargetFileName=""help.htm"" OpenInWebBrowser=""true"">help.htm</ProjectItem>"; return helpString + foldersString; } /// <summary> /// Serializes the folder. /// </summary> /// <param name="topFolder">The top folder.</param> /// <returns></returns> private string SerializeFolder(ItemFolder topFolder) { string folderString = string.Empty; string projItemNodeTemplate = @"<ProjectItem ReplaceParameters = ""true"" TargetFileName=""$filename"">$filename</ProjectItem>"; string folderItemNodeTemplate = @"<Folder Name=""$folderName"" TargetFolderName=""$folderName"" >"; if (topFolder.FolderName != null) { folderString = folderItemNodeTemplate.Replace("$folderName", topFolder.FolderName); } foreach (var item in topFolder.Items) { if (IsHelpItem(item)) { folderString = folderString + @"<ProjectItem ReplaceParameters=""false"" TargetFileName=""help.htm"" OpenInWebBrowser=""true"">help.htm</ProjectItem>"; helpFileReferenceExists = true; } else if (IsKeyProjectItemNode(item)) folderString = folderString + @"<ProjectItem ReplaceParameters=""false"" TargetFileName=""$projectname$_TemporaryKey.pfx"" BlendDoNotCreate=""true"">Application_TemporaryKey.pfx</ProjectItem>"; else { //-- now writing item. if (!string.IsNullOrEmpty(item) && !item.Contains("csproj") && !item.Contains("..")) { folderString = folderString + projItemNodeTemplate.Replace("$filename", item); } } } foreach (var folderItem in topFolder.Folders) { folderString = folderString + SerializeFolder(folderItem); } if (topFolder.FolderName != null) { folderString = folderString + "</Folder>"; } return folderString; } /// <summary> /// Determines whether [is help item] [the specified item]. /// </summary> /// <param name="item">The item.</param> /// <returns></returns> private bool IsHelpItem(string item) { return item.ToLower().Contains("help.htm"); } /// <summary> /// Gets the item folder. /// </summary> /// <param name="projectItems">The project items.</param> private void GetItemFolder(List<string> projectItems) { topFolder = new ItemFolder(); string[] stringSeparator = new string[] { @"\" }; foreach (var item in projectItems) { var parts = item.Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); AddPartsToTopFolder(parts); } } /// <summary> /// Adds the parts to top folder. /// </summary> /// <param name="parts">The parts.</param> private void AddPartsToTopFolder(string[] parts) { AddPartsToFolder(topFolder, parts, 0); } /// <summary> /// Adds the parts to folder. /// </summary> /// <param name="currentFolder">The current folder.</param> /// <param name="parts">The parts.</param> /// <param name="partIndex">Index of the part.</param> private void AddPartsToFolder(ItemFolder currentFolder, string[] parts, int partIndex) { //-- empty folder if (partIndex >= parts.Length) return; string part = parts[partIndex]; if (!IsFolder(part)) { currentFolder.Items.Add(part); return; } var folder = currentFolder.Folders.FirstOrDefault(e => e.FolderName == part); if (folder == null) { folder = new ItemFolder() { FolderName = part }; currentFolder.Folders.Add(folder); } AddPartsToFolder(folder, parts, ++partIndex); } /// <summary> /// Determines whether the specified part is folder. /// </summary> /// <param name="part">The part.</param> /// <returns></returns> private bool IsFolder(string part) { return !part.Contains("."); } /// <summary> /// Sorts the project items. /// </summary> /// <param name="projectItems">The project items.</param> /// <returns></returns> private List<string> SortProjectItems(List<string> projectItems) { projectItems.Sort(); var l2 = new List<string>(); foreach (var item in projectItems) { if (!item.Contains(@"\")) l2.Insert(0, item); else l2.Add(item); } projectItems = l2; return projectItems; } /// <summary> /// Gets the name of the folder. /// </summary> /// <param name="item">The item.</param> /// <returns></returns> private string GetFolderName(string item) { int startIndex = item.IndexOf(@"\"); return item.Substring(0, startIndex); } /// <summary> /// Determines whether [is key project item node] [the specified item]. /// </summary> /// <param name="item">The item.</param> /// <returns></returns> private bool IsKeyProjectItemNode(string item) { return item.Contains(".pfx"); } /// <summary> /// Gets the project items. /// </summary> /// <param name="csprojxml">The csprojxml.</param> /// <returns></returns> private List<string> GetProjectItems(string csprojxml) { List<string> files = new List<string>(); ; XDocument xdoc; using (StringReader sr = new StringReader(csprojxml)) { xdoc = XDocument.Load(sr, LoadOptions.None); } XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var items = xdoc.Descendants(ns + "ItemGroup"); string itemString = string.Empty; foreach (var itemG in items) { foreach (var item in itemG.Elements()) { itemString = item.Attribute("Include").Value; if (!string.IsNullOrEmpty(itemString) && !itemString.Contains("=") && !itemString.Contains(",")) { files.Add(itemString); } } } return files; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImageDownloader.cs" company="The Watcher"> // Copyright (c) The Watcher Partial Rights Reserved. // This software is licensed under the MIT license. See license.txt for details. // </copyright> // <summary> // Code Named: Ripper // Function : Extracts Images posted on forums and attempts to fetch them to disk. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Ripper.Services { using System.Collections; using Ripper.Core.Components; using Ripper.Services.ImageHosts; /// <summary> /// ImageDownloader is the bridging class between this routine and the /// ServiceTemplate base class (which is the parent to all hosting site's /// fetch code). /// </summary> public class ImageDownloader { /// <summary> /// The image URL /// </summary> private string imageURL = string.Empty; /// <summary> /// The thumb image URL /// </summary> private string thumbImageURL = string.Empty; /// <summary> /// The event table /// </summary> private Hashtable eventTable; /// <summary> /// The save path /// </summary> private string savePath = string.Empty; /// <summary> /// The x service /// </summary> private ServiceTemplate xService; /// <summary> /// The image name /// </summary> private string imageName = string.Empty; /// <summary> /// The image number /// </summary> private int imageNumber; /// <summary> /// Initializes a new instance of the <see cref="ImageDownloader" /> class. /// </summary> /// <param name="savePath">The save path.</param> /// <param name="url">The URL.</param> /// <param name="thumbUrl">The thumb URL.</param> /// <param name="imageName">Name of the image.</param> /// <param name="imageNumber">The image number.</param> /// <param name="hashTable">The hash table.</param> public ImageDownloader( string savePath, string url, string thumbUrl, string imageName, int imageNumber, Hashtable hashTable) { this.imageURL = url; this.thumbImageURL = thumbUrl; this.eventTable = hashTable; this.savePath = savePath; this.imageName = imageName; this.imageNumber = imageNumber; } /// <summary> /// Generals the downloader. /// </summary> public void GeneralDownloader() { this.xService = new uploadimages_net( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the upload image. /// </summary> public void GetUploadImage() { this.xService = new uploadimages_net( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the fapomatic. /// </summary> public void GetFapomatic() { this.xService = new fapomatic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the image venue. /// </summary> public void GetImageVenue() { this.xService = new imagevenue( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the image venue download. /// </summary> public void GetImageVenueNew() { this.xService = new imagevenueNew( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the moast download. /// </summary> public void GetMoast() { this.xService = new Moast( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetwatermarkIt() { this.xService = new watermarkIt( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicBux() { this.xService = new PicBux( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicturesUpload() { this.xService = new PicturesUpload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageHigh() { this.xService = new ImageHigh( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImage2Share() { this.xService = new Image2Share( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPaintedOver() { this.xService = new PaintedOver( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetDumbARump() { this.xService = new DumbARump( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageCrack() { this.xService = new ImageCrack( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetTenPix() { this.xService = new TenPix( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetSupload() { this.xService = new Supload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageThrust() { this.xService = new ImageThrust( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetShareAPic() { this.xService = new ShareAPic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFileDen() { this.xService = new FileDen( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicTiger() { this.xService = new PicTiger( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicTiger2() { this.xService = new PicTiger2( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetMyPhotos() { this.xService = new MyPhotos( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetTheImageHosting() { this.xService = new TheImageHosting( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetZShare() { this.xService = new ZShare( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetKeepMyFile() { this.xService = new KeepMyFile( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageBeaver() { this.xService = new ImageBeaver( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetShareAvenue() { this.xService = new ShareAvenue( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetGlowFoto() { this.xService = new GlowFoto( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetJpgHosting() { this.xService = new JpgHosting( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetJpgHosting2() { this.xService = new JpgHosting2( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageFling() { this.xService = new ImageFling( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetYourPix() { this.xService = new YourPix( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFreeImageHost() { this.xService = new FreeImageHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFreeShare() { this.xService = new FreeShare( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetSuprFile() { this.xService = new SuprFile( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetLetMeHost() { this.xService = new LetMeHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFileHost() { this.xService = new FileHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetTheFreeImageHosting() { this.xService = new TheFreeImageHosting( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetYesAlbum() { this.xService = new YesAlbum( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicsPlace() { this.xService = new PicsPlace( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetXsHosting() { this.xService = new XsHosting( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetCelebs() { this.xService = new Celebs( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetRipHq() { this.xService = new RipHq( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetBenuri() { this.xService = new Benuri( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageHaven() { this.xService = new ImageHaven( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImagePundit() { this.xService = new ImagePundit( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetUploadEm() { this.xService = new UploadEm( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetUpPix() { this.xService = new UpPix( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPixHosting() { this.xService = new PixHosting( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPussyUpload() { this.xService = new PussyUpload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetHotLinkImage() { this.xService = new HotLinkImage( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the Image Bam downloader. /// </summary> public void GetImageBam() { this.xService = new ImageBam( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetImageHosting() { this.xService = new ImageHosting( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetAllYouCanUpload() { this.xService = new AllYouCanUpload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetLargeImageHost() { this.xService = new LargeImageHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetRadikal() { this.xService = new Radikal( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetPixUp() { this.xService = new PixUp( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFreePornDumpster() { this.xService = new FreePornDumpster( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageSocket() { this.xService = new ImageSocket( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetStormFactory() { this.xService = new StormFactory( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicHoarder() { this.xService = new PicHoarder( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetMultiPics() { this.xService = new MultiPics( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageFoco() { this.xService = new ImageFoco( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetSpeedImg() { this.xService = new SpeedImg( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetDollarLink() { this.xService = new DollarLink( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicEasy() { this.xService = new PicEasy( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicturesHoster() { this.xService = new PicturesHoster( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicJackal() { this.xService = new PicJackal( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetAmazingDickSSl() { this.xService = new AmazingDickSSl( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImagesGal() { this.xService = new ImagesGal( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetBigPics() { this.xService = new BigPics( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetXPhotoSharing() { this.xService = new XPhotoSharing( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetBusyUpload() { this.xService = new BusyUpload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetUpMyPhoto() { this.xService = new UpMyPhoto( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetTurboImageHost() { this.xService = new TurboImageHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetAbload() { this.xService = new Abload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageDoza() { this.xService = new ImageDoza( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageWam() { this.xService = new ImageWam( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageFlea() { this.xService = new ImageFlea( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageCargo() { this.xService = new ImageCargo( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPixSlam() { this.xService = new PixSlam( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageHost() { this.xService = new ImageHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); this.xService.StartDownload(); } public void GetMyImageHost() { this.xService = new MyImageHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetShareNxs() { this.xService = new ShareNxs( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetKemiPic() { this.xService = new KemiPic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFotoTube() { this.xService = new FotoTube( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImmage() { this.xService = new Immage( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetIpicture() { this.xService = new Ipicture( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPornImgHost() { this.xService = new PornImgHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Gets the ImageTwist download /// </summary> public void GetImageTwist() { this.xService = new ImageTwist( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetImageWaste() { this.xService = new ImageWaste( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPixHost() { this.xService = new PixHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFastPic() { this.xService = new FastPic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetPicDir() { this.xService = new PicDir( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFotoSik() { this.xService = new FotoSik( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetDailyPoa() { this.xService = new DailyPoa( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageHostLi() { this.xService = new ImageHostLi( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetStooorage() { this.xService = new Stooorage( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImagePorter() { this.xService = new ImagePorter( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetFileMad() { this.xService = new FileMad( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetMyPixHost() { this.xService = new MyPixHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetSevenBucket() { this.xService = new SevenBucket( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } public void GetImageHyper() { this.xService = new ImageHyper( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageGiga Download /// </summary> public void GetImageGiga() { this.xService = new ImageGiga( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageSwitch Download /// </summary> public void GetImageSwitch() { this.xService = new ImageSwitch( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImgChili Download /// </summary> public void GetImgChili() { this.xService = new ImgChili( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgDepot Download /// </summary> public void GetImgDepot() { this.xService = new ImgDepot( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageUpper Download /// </summary> public void GetImageUpper() { this.xService = new ImageUpper( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImagePad Download /// </summary> public void GetImagePad() { this.xService = new ImagePad( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageBunk Download /// </summary> public void GetImageBunk() { this.xService = new ImageBunk( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get PimpAndHost Download /// </summary> public void GetPimpAndHost() { this.xService = new PimpAndHost( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get DumpPix Download /// </summary> public void GetDumpPix() { this.xService = new DumpPix( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get Hoooster Download /// </summary> public void GetHoooster() { this.xService = new Hoooster( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get PixHub Download /// </summary> public void GetPixHub() { this.xService = new PixHub( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get PixRoute Download /// </summary> public void GetPixRoute() { this.xService = new PixRoute( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImagePicasa Download /// </summary> public void GetImagePicasa() { this.xService = new ImagePicasa( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get DirectUpload Download /// </summary> public void GetDirectUpload() { this.xService = new DirectUpload( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImgBox Download /// </summary> public void GetImgBox() { this.xService = new ImgBox( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgDino Download /// </summary> public void GetImgDino() { this.xService = new ImgDino( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgWoot Download /// </summary> public void GetImgWoot() { this.xService = new ImgWoot( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImageEer Download /// </summary> public void GetImageEer() { this.xService = new ImageEer( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgPo Download /// </summary> public void GetImgPo() { this.xService = new ImgPo( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImGah Download /// </summary> public void GetImGah() { this.xService = new ImGah( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImgUr Download /// </summary> public void GetImgUr() { this.xService = new ImgUr( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get TusPics Download /// </summary> public void GetTusPics() { this.xService = new TusPics( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get FreeImagePic Download /// </summary> public void GetFreeImagePic() { this.xService = new FreeImagePic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get Celeb Sweet Download /// </summary> public void GetCelebSweet() { this.xService = new CelebSweet( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get SexyImg Download /// </summary> public void GetSexyImg() { this.xService = new SexyImg( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageJumbo Download /// </summary> public void GetImageJumbo() { this.xService = new ImageJumbo( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageDax Download /// </summary> public void GetImageDax() { this.xService = new ImageDax( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get HosterBin Download /// </summary> public void GetHosterBin() { this.xService = new HosterBin( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImgBabes Download /// </summary> public void GetImgBabes() { this.xService = new ImgBabes( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImagesIon Download /// </summary> public void GetImagesIon() { this.xService = new ImagesIon( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get PictureDip Download /// </summary> public void GetPictureDip() { this.xService = new PictureDip( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownload(); } /// <summary> /// Get ImageZilla Download /// </summary> public void GetImageZilla() { this.xService = new ImageZilla( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PicturesIon Download /// </summary> public void GetPicturesIon() { this.xService = new PicturesIon( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImageHostHQ Download /// </summary> public void GetImageHostHq() { this.xService = new ImageHostHq( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PixTreat Download /// </summary> public void GetPixTreat() { this.xService = new PixTreat( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PremiumPics Download /// </summary> public void GetPremiumPics() { this.xService = new PremiumPics( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgDollar Download /// </summary> public void GetImgDollar() { this.xService = new ImgDollar( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgFlare Download /// </summary> public void GetImgFlare() { this.xService = new ImgFlare( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get XLocker Download /// </summary> public void GetXLocker() { this.xService = new XLocker( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImageDunk Download /// </summary> public void GetImageDunk() { this.xService = new ImageDunk( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get Perverzia Download /// </summary> public void GetPerverzia() { this.xService = new Perverzia( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ViewCube Download /// </summary> public void GetViewCube() { this.xService = new ViewCube( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgSpice Download /// </summary> public void GetImgSpice() { this.xService = new ImgSpice( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImagesAholic Download /// </summary> public void GetImagesAholic() { this.xService = new ImagesAholic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImageShack Download /// </summary> public void GetImageShack() { this.xService = new ImageShack( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PostImage Download /// </summary> public void GetPostImage() { this.xService = new PostImage( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PostImg Download /// </summary> public void GetPostImg() { this.xService = new PostImg( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgPaying Download /// </summary> public void GetImgPaying() { this.xService = new ImgPaying( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get TruePic Download /// </summary> public void GetTruePic() { this.xService = new TruePic( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PixPal Download /// </summary> public void GetPixPal() { this.xService = new PixPal( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ViperII Download /// </summary> public void GetViperII() { this.xService = new ViperII( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgSee Download /// </summary> public void GetImgSee() { this.xService = new ImgSee( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgMega Download /// </summary> public void GetImgMega() { this.xService = new ImgMega( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgClick Download /// </summary> public void GetImgClick() { this.xService = new ImgClick( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get Imaaage Download /// </summary> public void GetImaaage() { this.xService = new Imaaage( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImageBugs Download /// </summary> public void GetImageBugs() { this.xService = new ImageBugs( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get Pictomania Download /// </summary> public void GetPictomania() { this.xService = new Pictomania( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgDap Download /// </summary> public void GetImgDap() { this.xService = new ImgDap( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get FileSpit Download /// </summary> public void GetFileSpit() { this.xService = new FileSpit( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get ImgBanana Download /// </summary> public void GetImgBanana() { this.xService = new ImgBanana( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PixLiv Download /// </summary> public void GetPixLiv() { this.xService = new PixLiv( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Get PicExposed Download /// </summary> public void GetPicExposed() { this.xService = new PicExposed( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } /// <summary> /// Hot linked image fetcher... /// </summary> public void GetImageHotLinked() { this.xService = new HotLinkedImage( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetImgTrex() { this.xService = new ImgTrex( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetGallerynova() { this.xService = new Gallerynova( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetLeechimg() { this.xService = new LeechImg( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } public void GetImgDriveCo() { this.xService = new ImgDriveCo( ref this.savePath, ref this.imageURL, ref this.thumbImageURL, ref this.imageName, ref this.imageNumber, ref this.eventTable); this.xService.StartDownloadAsync(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public partial class ApiManagementClient : ServiceClient<ApiManagementClient>, IApiManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IApiOperationPolicyOperations _apiOperationPolicy; /// <summary> /// Operations for managing API Operation Policy. /// </summary> public virtual IApiOperationPolicyOperations ApiOperationPolicy { get { return this._apiOperationPolicy; } } private IApiOperationsOperations _apiOperations; /// <summary> /// Operations for managing API Operations. /// </summary> public virtual IApiOperationsOperations ApiOperations { get { return this._apiOperations; } } private IApiPolicyOperations _apiPolicy; /// <summary> /// Operations for managing API Policy. /// </summary> public virtual IApiPolicyOperations ApiPolicy { get { return this._apiPolicy; } } private IApiProductsOperations _apiProducts; /// <summary> /// Operations for listing API associated Products. /// </summary> public virtual IApiProductsOperations ApiProducts { get { return this._apiProducts; } } private IApisOperations _apis; /// <summary> /// Operations for managing APIs. /// </summary> public virtual IApisOperations Apis { get { return this._apis; } } private IAuthorizationServersOperations _authorizationServers; /// <summary> /// Operations for managing Authorization Servers. /// </summary> public virtual IAuthorizationServersOperations AuthorizationServers { get { return this._authorizationServers; } } private IBackendOperations _backends; /// <summary> /// Operations for managing backend entity. /// </summary> public virtual IBackendOperations Backends { get { return this._backends; } } private ICertificatesOperations _certificates; /// <summary> /// Operations for managing Certificates. /// </summary> public virtual ICertificatesOperations Certificates { get { return this._certificates; } } private IGroupsOperations _groups; /// <summary> /// Operations for managing Groups. /// </summary> public virtual IGroupsOperations Groups { get { return this._groups; } } private IGroupUsersOperations _groupUsers; /// <summary> /// Operations for managing Group Users (list, add, remove users within /// a group). /// </summary> public virtual IGroupUsersOperations GroupUsers { get { return this._groupUsers; } } private IIdentityProviderOperations _identityProvider; /// <summary> /// Operations for managing Identity Providers. /// </summary> public virtual IIdentityProviderOperations IdentityProvider { get { return this._identityProvider; } } private ILoggerOperations _loggers; /// <summary> /// Operations for managing Loggers. /// </summary> public virtual ILoggerOperations Loggers { get { return this._loggers; } } private IOpenIdConnectProvidersOperations _openIdConnectProviders; /// <summary> /// Operations for managing OpenID Connect Providers. /// </summary> public virtual IOpenIdConnectProvidersOperations OpenIdConnectProviders { get { return this._openIdConnectProviders; } } private IPolicySnippetsOperations _policySnippents; /// <summary> /// Operations for managing Policy Snippets. /// </summary> public virtual IPolicySnippetsOperations PolicySnippents { get { return this._policySnippents; } } private IProductApisOperations _productApis; /// <summary> /// Operations for managing Product APIs. /// </summary> public virtual IProductApisOperations ProductApis { get { return this._productApis; } } private IProductGroupsOperations _productGroups; /// <summary> /// Operations for managing Product Groups. /// </summary> public virtual IProductGroupsOperations ProductGroups { get { return this._productGroups; } } private IProductPolicyOperations _productPolicy; /// <summary> /// Operations for managing Product Policy. /// </summary> public virtual IProductPolicyOperations ProductPolicy { get { return this._productPolicy; } } private IProductsOperations _products; /// <summary> /// Operations for managing Products. /// </summary> public virtual IProductsOperations Products { get { return this._products; } } private IProductSubscriptionsOperations _productSubscriptions; /// <summary> /// Operations for managing Product Subscriptions. /// </summary> public virtual IProductSubscriptionsOperations ProductSubscriptions { get { return this._productSubscriptions; } } private IPropertiesOperations _property; /// <summary> /// Operations for managing Properties. /// </summary> public virtual IPropertiesOperations Property { get { return this._property; } } private IRegionsOperations _regions; /// <summary> /// Operations for managing Regions. /// </summary> public virtual IRegionsOperations Regions { get { return this._regions; } } private IReportsOperations _reports; /// <summary> /// Operations for managing Reports. /// </summary> public virtual IReportsOperations Reports { get { return this._reports; } } private IResourceProviderOperations _resourceProvider; /// <summary> /// Operations for managing Api Management service provisioning /// (create/remove, backup/restore, scale, etc.). /// </summary> public virtual IResourceProviderOperations ResourceProvider { get { return this._resourceProvider; } } private ISubscriptionsOperations _subscriptions; /// <summary> /// Operations for managing Subscriptions. /// </summary> public virtual ISubscriptionsOperations Subscriptions { get { return this._subscriptions; } } private ITenantAccessGitOperations _tenantAccessGit; /// <summary> /// Operations for managing Tenant Access Git Information. /// </summary> public virtual ITenantAccessGitOperations TenantAccessGit { get { return this._tenantAccessGit; } } private ITenantAccessInformationOperations _tenantAccess; /// <summary> /// Operations for managing Tenant Access Information. /// </summary> public virtual ITenantAccessInformationOperations TenantAccess { get { return this._tenantAccess; } } private ITenantConfigurationOperations _tenantConfiguration; /// <summary> /// Operation to apply changes from specified Git branch to the /// configuration database. /// </summary> public virtual ITenantConfigurationOperations TenantConfiguration { get { return this._tenantConfiguration; } } private ITenantConfigurationSyncStateOperation _tenantConfigurationSyncState; /// <summary> /// Operation to return the status of the most recent synchronization /// between configuration database and the Git repository. /// </summary> public virtual ITenantConfigurationSyncStateOperation TenantConfigurationSyncState { get { return this._tenantConfigurationSyncState; } } private ITenantPolicyOperations _tenantPolicy; /// <summary> /// Operations for managing Tenant Policy. /// </summary> public virtual ITenantPolicyOperations TenantPolicy { get { return this._tenantPolicy; } } private IUserApplicationsOperations _userApplications; /// <summary> /// Operations for managing User Applications. /// </summary> public virtual IUserApplicationsOperations UserApplications { get { return this._userApplications; } } private IUserGroupsOperations _userGroups; /// <summary> /// Operations for managing User Groups. /// </summary> public virtual IUserGroupsOperations UserGroups { get { return this._userGroups; } } private IUserIdentitiesOperations _userIdentities; /// <summary> /// Operations for managing User Identities. /// </summary> public virtual IUserIdentitiesOperations UserIdentities { get { return this._userIdentities; } } private IUsersOperations _users; /// <summary> /// Operations for managing Users. /// </summary> public virtual IUsersOperations Users { get { return this._users; } } private IUserSubscriptionsOperations _userSubscriptions; /// <summary> /// Operations for managing User Subscriptions. /// </summary> public virtual IUserSubscriptionsOperations UserSubscriptions { get { return this._userSubscriptions; } } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> public ApiManagementClient() : base() { this._apiOperationPolicy = new ApiOperationPolicyOperations(this); this._apiOperations = new ApiOperationsOperations(this); this._apiPolicy = new ApiPolicyOperations(this); this._apiProducts = new ApiProductsOperations(this); this._apis = new ApisOperations(this); this._authorizationServers = new AuthorizationServersOperations(this); this._backends = new BackendOperations(this); this._certificates = new CertificatesOperations(this); this._groups = new GroupsOperations(this); this._groupUsers = new GroupUsersOperations(this); this._identityProvider = new IdentityProviderOperations(this); this._loggers = new LoggerOperations(this); this._openIdConnectProviders = new OpenIdConnectProvidersOperations(this); this._policySnippents = new PolicySnippetsOperations(this); this._productApis = new ProductApisOperations(this); this._productGroups = new ProductGroupsOperations(this); this._productPolicy = new ProductPolicyOperations(this); this._products = new ProductsOperations(this); this._productSubscriptions = new ProductSubscriptionsOperations(this); this._property = new PropertiesOperations(this); this._regions = new RegionsOperations(this); this._reports = new ReportsOperations(this); this._resourceProvider = new ResourceProviderOperations(this); this._subscriptions = new SubscriptionsOperations(this); this._tenantAccessGit = new TenantAccessGitOperations(this); this._tenantAccess = new TenantAccessInformationOperations(this); this._tenantConfiguration = new TenantConfigurationOperations(this); this._tenantConfigurationSyncState = new TenantConfigurationSyncStateOperation(this); this._tenantPolicy = new TenantPolicyOperations(this); this._userApplications = new UserApplicationsOperations(this); this._userGroups = new UserGroupsOperations(this); this._userIdentities = new UserIdentitiesOperations(this); this._users = new UsersOperations(this); this._userSubscriptions = new UserSubscriptionsOperations(this); this._apiVersion = "2016-10-10"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(HttpClient httpClient) : base(httpClient) { this._apiOperationPolicy = new ApiOperationPolicyOperations(this); this._apiOperations = new ApiOperationsOperations(this); this._apiPolicy = new ApiPolicyOperations(this); this._apiProducts = new ApiProductsOperations(this); this._apis = new ApisOperations(this); this._authorizationServers = new AuthorizationServersOperations(this); this._backends = new BackendOperations(this); this._certificates = new CertificatesOperations(this); this._groups = new GroupsOperations(this); this._groupUsers = new GroupUsersOperations(this); this._identityProvider = new IdentityProviderOperations(this); this._loggers = new LoggerOperations(this); this._openIdConnectProviders = new OpenIdConnectProvidersOperations(this); this._policySnippents = new PolicySnippetsOperations(this); this._productApis = new ProductApisOperations(this); this._productGroups = new ProductGroupsOperations(this); this._productPolicy = new ProductPolicyOperations(this); this._products = new ProductsOperations(this); this._productSubscriptions = new ProductSubscriptionsOperations(this); this._property = new PropertiesOperations(this); this._regions = new RegionsOperations(this); this._reports = new ReportsOperations(this); this._resourceProvider = new ResourceProviderOperations(this); this._subscriptions = new SubscriptionsOperations(this); this._tenantAccessGit = new TenantAccessGitOperations(this); this._tenantAccess = new TenantAccessInformationOperations(this); this._tenantConfiguration = new TenantConfigurationOperations(this); this._tenantConfigurationSyncState = new TenantConfigurationSyncStateOperation(this); this._tenantPolicy = new TenantPolicyOperations(this); this._userApplications = new UserApplicationsOperations(this); this._userGroups = new UserGroupsOperations(this); this._userIdentities = new UserIdentitiesOperations(this); this._users = new UsersOperations(this); this._userSubscriptions = new UserSubscriptionsOperations(this); this._apiVersion = "2016-10-10"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ApiManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ApiManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ApiManagementClient instance /// </summary> /// <param name='client'> /// Instance of ApiManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ApiManagementClient> client) { base.Clone(client); if (client is ApiManagementClient) { ApiManagementClient clonedClient = ((ApiManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type AsyncOperationState. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static AsyncOperationState ParseAsyncOperationState(string value) { if ("Started".Equals(value, StringComparison.OrdinalIgnoreCase)) { return AsyncOperationState.Started; } if ("InProgress".Equals(value, StringComparison.OrdinalIgnoreCase)) { return AsyncOperationState.InProgress; } if ("Succeeded".Equals(value, StringComparison.OrdinalIgnoreCase)) { return AsyncOperationState.Succeeded; } if ("Failed".Equals(value, StringComparison.OrdinalIgnoreCase)) { return AsyncOperationState.Failed; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type AsyncOperationState to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string AsyncOperationStateToString(AsyncOperationState value) { if (value == AsyncOperationState.Started) { return "Started"; } if (value == AsyncOperationState.InProgress) { return "InProgress"; } if (value == AsyncOperationState.Succeeded) { return "Succeeded"; } if (value == AsyncOperationState.Failed) { return "Failed"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type BearerTokenSendingMethodsContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static BearerTokenSendingMethodsContract ParseBearerTokenSendingMethodsContract(string value) { if ("authorizationHeader".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BearerTokenSendingMethodsContract.AuthorizationHeader; } if ("query".Equals(value, StringComparison.OrdinalIgnoreCase)) { return BearerTokenSendingMethodsContract.Query; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type BearerTokenSendingMethodsContract to a /// string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string BearerTokenSendingMethodsContractToString(BearerTokenSendingMethodsContract value) { if (value == BearerTokenSendingMethodsContract.AuthorizationHeader) { return "authorizationHeader"; } if (value == BearerTokenSendingMethodsContract.Query) { return "query"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type GrantTypesContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static GrantTypesContract ParseGrantTypesContract(string value) { if ("authorizationCode".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.AuthorizationCode; } if ("implicit".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.Implicit; } if ("resourceOwnerPassword".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.ResourceOwnerPassword; } if ("clientCredentials".Equals(value, StringComparison.OrdinalIgnoreCase)) { return GrantTypesContract.ClientCredentials; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type GrantTypesContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string GrantTypesContractToString(GrantTypesContract value) { if (value == GrantTypesContract.AuthorizationCode) { return "authorizationCode"; } if (value == GrantTypesContract.Implicit) { return "implicit"; } if (value == GrantTypesContract.ResourceOwnerPassword) { return "resourceOwnerPassword"; } if (value == GrantTypesContract.ClientCredentials) { return "clientCredentials"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type IdentityProviderTypeContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static IdentityProviderTypeContract ParseIdentityProviderTypeContract(string value) { if ("facebook".Equals(value, StringComparison.OrdinalIgnoreCase)) { return IdentityProviderTypeContract.Facebook; } if ("google".Equals(value, StringComparison.OrdinalIgnoreCase)) { return IdentityProviderTypeContract.Google; } if ("microsoft".Equals(value, StringComparison.OrdinalIgnoreCase)) { return IdentityProviderTypeContract.Microsoft; } if ("twitter".Equals(value, StringComparison.OrdinalIgnoreCase)) { return IdentityProviderTypeContract.Twitter; } if ("aad".Equals(value, StringComparison.OrdinalIgnoreCase)) { return IdentityProviderTypeContract.Aad; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type IdentityProviderTypeContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string IdentityProviderTypeContractToString(IdentityProviderTypeContract value) { if (value == IdentityProviderTypeContract.Facebook) { return "facebook"; } if (value == IdentityProviderTypeContract.Google) { return "google"; } if (value == IdentityProviderTypeContract.Microsoft) { return "microsoft"; } if (value == IdentityProviderTypeContract.Twitter) { return "twitter"; } if (value == IdentityProviderTypeContract.Aad) { return "aad"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type MethodContract. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static MethodContract ParseMethodContract(string value) { if ("HEAD".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Head; } if ("OPTIONS".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Options; } if ("TRACE".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Trace; } if ("GET".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Get; } if ("POST".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Post; } if ("PUT".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Put; } if ("PATCH".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Patch; } if ("DELETE".Equals(value, StringComparison.OrdinalIgnoreCase)) { return MethodContract.Delete; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type MethodContract to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string MethodContractToString(MethodContract value) { if (value == MethodContract.Head) { return "HEAD"; } if (value == MethodContract.Options) { return "OPTIONS"; } if (value == MethodContract.Trace) { return "TRACE"; } if (value == MethodContract.Get) { return "GET"; } if (value == MethodContract.Post) { return "POST"; } if (value == MethodContract.Put) { return "PUT"; } if (value == MethodContract.Patch) { return "PATCH"; } if (value == MethodContract.Delete) { return "DELETE"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type ReportsAggregation. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static ReportsAggregation ParseReportsAggregation(string value) { if ("byApi".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByApi; } if ("byGeo".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByGeo; } if ("byOperation".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByOperation; } if ("byProduct".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByProduct; } if ("bySubscription".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.BySubscription; } if ("byTime".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByTime; } if ("byUser".Equals(value, StringComparison.OrdinalIgnoreCase)) { return ReportsAggregation.ByUser; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type ReportsAggregation to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string ReportsAggregationToString(ReportsAggregation value) { if (value == ReportsAggregation.ByApi) { return "byApi"; } if (value == ReportsAggregation.ByGeo) { return "byGeo"; } if (value == ReportsAggregation.ByOperation) { return "byOperation"; } if (value == ReportsAggregation.ByProduct) { return "byProduct"; } if (value == ReportsAggregation.BySubscription) { return "bySubscription"; } if (value == ReportsAggregation.ByTime) { return "byTime"; } if (value == ReportsAggregation.ByUser) { return "byUser"; } throw new ArgumentOutOfRangeException("value"); } } }
// ExpressApplication.cs // Script#/Libraries/Node/Express // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using NodeApi.Network; namespace NodeApi.ExpressJS { [ScriptImport] [ScriptIgnoreNamespace] [ScriptName("express")] public sealed class ExpressApplication { private ExpressApplication() { } [ScriptField] public Dictionary<string, object> Locals { get { return null; } } [ScriptField] public Dictionary<string, List<ExpressRoute>> Routes { get { return null; } } [ScriptName("locals")] public void AddLocals(Dictionary<string, object> values) { } public ExpressApplication All(string path, ExpressHandler handler) { return null; } public ExpressApplication All(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication All(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication All(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Configure(Action callback) { return null; } public ExpressApplication Configure(string environmentName, Action callback) { return null; } public ExpressApplication Delete(string path, ExpressHandler handler) { return null; } public ExpressApplication Delete(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Delete(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication Delete(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } [ScriptName("disable")] public ExpressApplication DisableSetting(string name) { return null; } [ScriptName("disable")] public ExpressApplication DisableSetting(ExpressSettings name) { return null; } [ScriptName("enable")] public ExpressApplication EnableSetting(string name) { return null; } [ScriptName("enable")] public ExpressApplication EnableSetting(ExpressSettings name) { return null; } public ExpressApplication Engine(string extension, ExpressTemplateEngine engine) { return null; } public ExpressApplication Error(ExpressErrorHandler handler) { return null; } public ExpressApplication Error(ExpressChainedErrorHandler chainedHandler) { return null; } public ExpressApplication Get(string path, ExpressHandler handler) { return null; } public ExpressApplication Get(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Get(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication Get(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } [ScriptName("get")] public string GetSetting(string name) { return null; } [ScriptName("get")] public string GetSetting(ExpressSettings name) { return null; } public ExpressApplication Head(string path, ExpressHandler handler) { return null; } public ExpressApplication Head(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Head(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication Head(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } [ScriptName("disabled")] public bool IsSeSettingDisabled(string name) { return false; } [ScriptName("disabled")] public bool IsSeSettingDisabled(ExpressSettings name) { return false; } [ScriptName("enabled")] public bool IsSeSettingEnabled(string name) { return false; } [ScriptName("enabled")] public bool IsSeSettingEnabled(ExpressSettings name) { return false; } public void Listen(int port) { } public void Listen(int port, string hostName) { } public void Listen(int port, string hostName, int backlog) { } public ExpressApplication Param(string parameter, ExpressParameterHandler handler) { return null; } public ExpressApplication Options(string path, ExpressHandler handler) { return null; } public ExpressApplication Options(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Options(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication Options(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Post(string path, ExpressHandler handler) { return null; } public ExpressApplication Post(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Post(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication Post(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Put(string path, ExpressHandler handler) { return null; } public ExpressApplication Put(string path, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public ExpressApplication Put(RegExp pathPattern, ExpressHandler handler) { return null; } public ExpressApplication Put(RegExp pathPattern, ExpressChainedHandler[] chainedHandlers, ExpressHandler handler) { return null; } public void Render(string viewName, AsyncResultCallback<string> callback) { } public void Render(string viewName, Dictionary<string, object> data, AsyncResultCallback<string> callback) { } [ScriptName("set")] public void SetSetting(string name, string value) { } [ScriptName("set")] public void SetSetting(ExpressSettings name, string value) { } [ScriptSkip] public HttpListener ToHttpListener() { return null; } public ExpressApplication Use(ExpressMiddleware middleware) { return null; } public ExpressApplication Use(string path, ExpressMiddleware middleware) { return null; } } }
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using DebuggerApi; using JetBrains.Annotations; using Microsoft.VisualStudio; using YetiCommon; using YetiVSI.Shared.Metrics; namespace YetiVSI.DebugEngine { /// <summary> /// Handles loading binaries and symbols for modules by searching symbol stores for binary files /// and symbol files. /// </summary> public interface IModuleFileLoader { /// <summary> /// Searches for and loads binaries and symbols for the given modules. If |modules| contains /// placeholder modules and the matching binaries are successfully loaded, then |modules| /// will be modified, replacing the placeholder modules with the newly loaded modules. /// </summary> /// <returns> /// A <see cref="LoadModuleFilesResult"/>. /// </returns> Task<LoadModuleFilesResult> LoadModuleFilesAsync( [NotNull, ItemNotNull] IList<SbModule> modules, [NotNull] ICancelable task, [NotNull] IModuleFileLoadMetricsRecorder moduleFileLoadRecorder); /// <summary> /// Same as <see cref="LoadModuleFilesAsync(System.Collections.Generic.IList{DebuggerApi.SbModule},YetiVSI.ICancelable,YetiVSI.DebugEngine.IModuleFileLoadMetricsRecorder)"/> /// but allows user to additionally specify modules for which symbols should be loaded /// via SymbolInclusionSettings. /// </summary> /// <param name="modules">List of modules to process.</param> /// <param name="symbolSettings">Symbol settings with IncludeList and ExcludeList /// to filter out symbols that should be skipped. </param> /// <param name="useSymbolStores"> /// If true, then during loading the module the method will try to lookup module in /// symbol stores by the name extracted from module. /// <see cref="SymbolLoader.GetSymbolFileDirAndName"/> /// </param> /// <param name="isStadiaSymbolsServerUsed"> /// If true, then the method will not return suggestion to enable symbol store server. /// A <see cref="LoadModuleFilesResult.SuggestToEnableSymbolStore"/>. /// </param> /// <param name="task">Long-running operation associated with the process.</param> /// <param name="moduleFileLoadRecorder">Instance to record metrics related to the /// loading of symbols and binaries.</param> /// <returns> /// A <see cref="LoadModuleFilesResult"/>. /// </returns> Task<LoadModuleFilesResult> LoadModuleFilesAsync( [NotNull, ItemNotNull] IList<SbModule> modules, SymbolInclusionSettings symbolSettings, bool useSymbolStores, bool isStadiaSymbolsServerUsed, [NotNull] ICancelable task, [NotNull] IModuleFileLoadMetricsRecorder moduleFileLoadRecorder); } public interface IModuleFileLoaderFactory { IModuleFileLoader Create(ISymbolLoader symbolLoader, IBinaryLoader binaryLoader, bool isCoreAttach, IModuleSearchLogHolder moduleSearchLogHolder); } public interface IModuleSearchLogHolder { string GetSearchLog(SbModule lldbModule); void AppendSearchLog(SbModule lldbModule, string log); void ResetSearchLog(SbModule lldbModule); } public class ModuleSearchLogHolder : IModuleSearchLogHolder { // Maps module Id (it's unique) to per-module symbol search logs. readonly Dictionary<long, string> _logsByModuleId = new Dictionary<long, string>(); public string GetSearchLog(SbModule lldbModule) { long id = lldbModule.GetId(); return _logsByModuleId.TryGetValue(id, out string log) ? log : ""; } public void AppendSearchLog(SbModule lldbModule, string log) { if (string.IsNullOrWhiteSpace(log)) { return; } long id = lldbModule.GetId(); if (_logsByModuleId.TryGetValue(id, out string existingLog) && !string.IsNullOrWhiteSpace(existingLog)) { _logsByModuleId[id] = $"{existingLog}{Environment.NewLine}{log}"; } else { _logsByModuleId[id] = log; } } public void ResetSearchLog(SbModule lldbModule) { long id = lldbModule.GetId(); if (_logsByModuleId.TryGetValue(id, out string _)) { _logsByModuleId[id] = ""; } } } public class ModuleFileLoader : IModuleFileLoader { // TODO: Make ModuleFileLoader implementation thread safe public class Factory : IModuleFileLoaderFactory { public IModuleFileLoader Create(ISymbolLoader symbolLoader, IBinaryLoader binaryLoader, bool isCoreAttach, IModuleSearchLogHolder moduleSearchLogHolder) => new ModuleFileLoader(symbolLoader, binaryLoader, isCoreAttach, moduleSearchLogHolder); } readonly ISymbolLoader _symbolLoader; readonly IBinaryLoader _binaryLoader; readonly bool _isCoreAttach; readonly IModuleSearchLogHolder _moduleSearchLogHolder; static readonly IList<Regex> _importantModulesForCoreDumpDebugging = new[] { new Regex("amdvlk64\\.so", RegexOptions.Compiled), new Regex("ggpvlk\\.so", RegexOptions.Compiled), new Regex("libanl-?.*\\.so.*", RegexOptions.Compiled), new Regex("libasound\\.so.*", RegexOptions.Compiled), new Regex("libatomic\\.so.*", RegexOptions.Compiled), new Regex("libBrokenLocale-?.*\\.so", RegexOptions.Compiled), new Regex("libc-?([0-9].[0-9]{2})?\\.so.*", RegexOptions.Compiled), new Regex("libc\\+\\+abi\\.so.*", RegexOptions.Compiled), new Regex("libcap\\.so.*", RegexOptions.Compiled), new Regex("libcidn-?.*\\.so.*", RegexOptions.Compiled), new Regex("libcrypto\\.so.*", RegexOptions.Compiled), new Regex("libcrypt-?.*\\.so.*", RegexOptions.Compiled), new Regex("libc\\+\\+\\.so.*", RegexOptions.Compiled), new Regex("libdbus-1\\.so.*", RegexOptions.Compiled), new Regex("libdl-?.*\\.so.*", RegexOptions.Compiled), new Regex("libdrm_amdgpu\\.so.*", RegexOptions.Compiled), new Regex("libdrm\\.so.*", RegexOptions.Compiled), new Regex("libgcc_s\\.so.*", RegexOptions.Compiled), new Regex("libgcrypt\\.so.*", RegexOptions.Compiled), new Regex("libggp_g3\\.so.*", RegexOptions.Compiled), new Regex("libggp\\.so", RegexOptions.Compiled), new Regex("libggp_with_heap_isolation\\.so.*", RegexOptions.Compiled), new Regex("libgomp\\.so.*", RegexOptions.Compiled), new Regex("libgpg-error\\.so.*", RegexOptions.Compiled), new Regex("libGPUPerfAPIVK\\.so", RegexOptions.Compiled), new Regex("libidn\\.so.*", RegexOptions.Compiled), new Regex("liblz4\\.so.*", RegexOptions.Compiled), new Regex("liblzma\\.so.*", RegexOptions.Compiled), new Regex("libmemusage\\.so", RegexOptions.Compiled), new Regex("libm-?.*\\.so.*", RegexOptions.Compiled), new Regex("libmvec-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnettle\\.so.*", RegexOptions.Compiled), new Regex("libnsl-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnss_compat-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnss_dns-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnss_files-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnss_hesiod-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnss_nisplus-?.*\\.so.*", RegexOptions.Compiled), new Regex("libnss_nis-?.*\\.so.*", RegexOptions.Compiled), new Regex("libpcprofile.so", RegexOptions.Compiled), new Regex("libpcre\\.so.*", RegexOptions.Compiled), new Regex("libpthread-?.*\\.so.*", RegexOptions.Compiled), new Regex("libpulsecommon-12\\.0\\.so", RegexOptions.Compiled), new Regex("libpulse-simple\\.so.*", RegexOptions.Compiled), new Regex("libpulse\\.so.*", RegexOptions.Compiled), new Regex("librenderdoc\\.so", RegexOptions.Compiled), new Regex("libresolv-?.*\\.so.*", RegexOptions.Compiled), new Regex("librgpserver\\.so", RegexOptions.Compiled), new Regex("librt-?.*\\.so.*", RegexOptions.Compiled), new Regex("libSegFault\\.so", RegexOptions.Compiled), new Regex("libselinux\\.so.*", RegexOptions.Compiled), new Regex("libsndfile\\.so.*", RegexOptions.Compiled), new Regex("libssl\\.so.*", RegexOptions.Compiled), new Regex("libsystemd\\.so.*", RegexOptions.Compiled), new Regex("libthread_db-1\\.0\\.so.*", RegexOptions.Compiled), new Regex("libthread_db\\.so.*", RegexOptions.Compiled), new Regex("libutil-?.*\\.so.*", RegexOptions.Compiled), new Regex("libVkLayer.*\\.so", RegexOptions.Compiled), new Regex("libvulkan\\.so.*", RegexOptions.Compiled), new Regex("libz\\.so.*", RegexOptions.Compiled), new Regex("oskhost\\.so", RegexOptions.Compiled), }; public ModuleFileLoader(ISymbolLoader symbolLoader, IBinaryLoader binaryLoader, bool isCoreAttach, IModuleSearchLogHolder moduleSearchLogHolder) { _symbolLoader = symbolLoader; _binaryLoader = binaryLoader; _isCoreAttach = isCoreAttach; _moduleSearchLogHolder = moduleSearchLogHolder; } public async Task<LoadModuleFilesResult> LoadModuleFilesAsync( IList<SbModule> modules, SymbolInclusionSettings symbolSettings, bool useSymbolStores, bool isStadiaSymbolsServerUsed, ICancelable task, IModuleFileLoadMetricsRecorder moduleFileLoadRecorder) { // If LoadSymbols is called from the "Modules -> Load Symbols" context menu // or by clicking "Load Symbols" in "Symbols" pane in the settings, `symbolSettings` // will be empty. On the other hand, when LoadSymbols is called during // the debugger attaching, the `symbolSettings` will be set and IsManualLoad = false, // only in this case we'll be using cache when trying to load symbols from // remote symbolStores. bool forceLoad = symbolSettings?.IsManualLoad ?? true; int modulesWithSymbolsCount = modules.Count(m => m.HasSymbolsLoaded()); int binariesLoadedCount = modules.Count(m => m.HasBinaryLoaded()); var loadSymbolData = new DeveloperLogEvent.Types.LoadSymbolData { ModulesCount = modules.Count, ModulesBeforeCount = modules.Count, ModulesAfterCount = modules.Count, ModulesWithSymbolsLoadedBeforeCount = modulesWithSymbolsCount, ModulesWithSymbolsLoadedAfterCount = modulesWithSymbolsCount, BinariesLoadedBeforeCount = binariesLoadedCount, BinariesLoadedAfterCount = binariesLoadedCount }; // Add some metrics to the event proto before attempting to load symbols, so that they // are still recorded if the task is aborted or cancelled. moduleFileLoadRecorder.RecordBeforeLoad(loadSymbolData); var result = new LoadModuleFilesResult { ResultCode = VSConstants.S_OK, SuggestToEnableSymbolStore = false }; IEnumerable<SbModule> preFilteredModules = PrefilterModulesByName(modules, symbolSettings); List<SbModule> modulesWithBinariesLoaded = await ProcessModulePlaceholdersAsync( preFilteredModules, task, isStadiaSymbolsServerUsed, loadSymbolData, result); await ProcessModulesWithoutSymbolsAsync( modulesWithBinariesLoaded, task, useSymbolStores, forceLoad, loadSymbolData, result); // Record the final state. moduleFileLoadRecorder.RecordAfterLoad(loadSymbolData); return result; } public Task<LoadModuleFilesResult> LoadModuleFilesAsync( IList<SbModule> modules, ICancelable task, IModuleFileLoadMetricsRecorder moduleFileLoadRecorder) => LoadModuleFilesAsync(modules, null, true, true, task, moduleFileLoadRecorder); /// <summary> /// Filter out modules that should be skipped based on their name /// (empty, deleted or excluded). /// </summary> IEnumerable<SbModule> PrefilterModulesByName(IEnumerable<SbModule> modules, SymbolInclusionSettings settings) { foreach (SbModule sbModule in modules) { string name = sbModule.GetPlatformFileSpec()?.GetFilename(); string error = GetReasonToSkip(name, settings); // Modules loading can be an iterative process, we need to clean up the logs. _moduleSearchLogHolder.ResetSearchLog(sbModule); if (string.IsNullOrEmpty(error)) { yield return sbModule; } else { _moduleSearchLogHolder.AppendSearchLog(sbModule, error); } } } /// <summary> /// If module doesn't have a name or its name is in the list /// of ExcludedModules, no further processing is needed. /// </summary> /// <returns>Message to be recorded in the logs.</returns> string GetReasonToSkip(string moduleName, SymbolInclusionSettings settings) { if (string.IsNullOrWhiteSpace(moduleName)) { return "Module name not set."; } if (moduleName.EndsWith("(deleted)")) { return "Module marked as deleted by LLDB."; } return settings?.IsModuleIncluded(moduleName) == false ? SymbolInclusionSettings.ModuleExcludedMessage : null; } /// <summary> /// Attempts to replace placeholder modules with matching binaries. /// If this operation fails for one of the so-called "important modules" /// and Stadia SymbolStore is not enabled, we'll show a warning message /// suggesting to enable symbol stores in the settings. /// </summary> /// <remarks> /// Updates <c>loadSymbolData</c>'s BinariesLoadedAfterCount /// property and <c>result</c>'s ResultCode and SuggestToEnableSymbolStore. /// </remarks> /// <returns>List of modules with binaries loaded.</returns> async Task<List<SbModule>> ProcessModulePlaceholdersAsync( IEnumerable<SbModule> preFilteredModules, ICancelable task, bool isStadiaSymbolsServerUsed, DeveloperLogEvent.Types.LoadSymbolData loadSymbolData, LoadModuleFilesResult result) { var modulesWithBinary = new List<SbModule>(); foreach (SbModule sbModule in preFilteredModules) { if (sbModule.HasBinaryLoaded()) { modulesWithBinary.Add(sbModule); continue; } string name = sbModule.GetPlatformFileSpec().GetFilename(); TextWriter searchLog = new StringWriter(); task.ThrowIfCancellationRequested(); task.Progress.Report( $"Loading binary for {name}" + $"({sbModule.GetId()}/{loadSymbolData.ModulesCount})"); (SbModule outputModule, bool ok) = await _binaryLoader.LoadBinaryAsync(sbModule, searchLog); if (ok) { modulesWithBinary.Add(outputModule); loadSymbolData.BinariesLoadedAfterCount++; } else { result.ResultCode = VSConstants.E_FAIL; result.SuggestToEnableSymbolStore |= ShouldAskToEnableSymbolStores(name, isStadiaSymbolsServerUsed); } _moduleSearchLogHolder.AppendSearchLog(outputModule, searchLog.ToString()); } return modulesWithBinary; } /// <summary> /// Attempts to load symbols for all modules that don't have them loaded yet (it /// includes searching for a separate symbol file locally and in the enabled symbol /// stores). /// </summary> /// <remarks> /// Updates <c>loadSymbolData</c>'s ModulesWithSymbolsLoadedAfterCount property and /// <c>result</c>'s ResultCode. /// </remarks> async Task ProcessModulesWithoutSymbolsAsync( List<SbModule> modulesWithBinariesLoaded, ICancelable task, bool useSymbolStores, bool forceLoad, DeveloperLogEvent.Types.LoadSymbolData loadSymbolData, LoadModuleFilesResult result) { foreach (SbModule sbModule in modulesWithBinariesLoaded) { if (sbModule.HasSymbolsLoaded()) { continue; } string name = sbModule.GetPlatformFileSpec().GetFilename(); TextWriter searchLog = new StringWriter(); task.ThrowIfCancellationRequested(); task.Progress.Report( $"Loading symbols for {name} " + $"({sbModule.GetId()}/{loadSymbolData.ModulesCount})"); bool ok = await _symbolLoader.LoadSymbolsAsync( sbModule, searchLog, useSymbolStores, forceLoad); if (!ok) { result.ResultCode = VSConstants.E_FAIL; } else { loadSymbolData.ModulesWithSymbolsLoadedAfterCount++; } _moduleSearchLogHolder.AppendSearchLog(sbModule, searchLog.ToString()); } } bool ShouldAskToEnableSymbolStores(string name, bool isStadiaSymbolsServerUsed) { return !isStadiaSymbolsServerUsed && _isCoreAttach && _importantModulesForCoreDumpDebugging.Any( expr => expr.IsMatch(name)); } } }
/* * Copyright (c) 2005 Oren J. Maurice <oymaurice@hazorea.org.il> * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, 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 OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License version 2 (the "GPL"), in which case the * provisions of the GPL are applicable instead of the above. If you wish to * allow the use of your version of this file only under the terms of the * GPL and not to allow others to use your version of this file under the * BSD license, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the GPL. If * you do not delete the provisions above, a recipient may use your version * of this file under either the BSD or the GPL. */ using System; namespace LZF.NET { /// <summary> /// Summary description for CLZF. /// </summary> public class CLZF { // CRC32 data & function UInt32 []crc_32_tab = new UInt32[256] { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; public UInt32 crc32(UInt32 OldCRC,byte NewData) { return crc_32_tab[(OldCRC & 0xff) ^ NewData] ^ (OldCRC >> 8); } /// <summary> /// LZF Compressor /// </summary> UInt32 HLOG=14; UInt32 HSIZE=(1<<14); /* * don't play with this unless you benchmark! * decompression is not dependent on the hash function * the hashing function might seem strange, just believe me * it works ;) */ UInt32 MAX_LIT=(1 << 5); UInt32 MAX_OFF=(1 << 13); UInt32 MAX_REF=((1 << 8) + (1 << 3)); UInt32 FRST(byte[] Array,UInt32 ptr) { return (UInt32)(((Array[ptr]) << 8) | Array[ptr+1]); } UInt32 NEXT(UInt32 v,byte[] Array,UInt32 ptr) { return ((v) << 8) | Array[ptr+2]; } UInt32 IDX(UInt32 h) { return ((((h ^ (h << 5)) >> (int) (3*8 - HLOG)) - h*5) & (HSIZE - 1)); } /* * compressed format * * 000LLLLL <L+1> ; literal * LLLOOOOO oooooooo ; backref L * 111OOOOO LLLLLLLL oooooooo ; backref L+7 * */ public int lzf_compress (byte[] in_data, int in_len,byte[] out_data, int out_len) { int c; long []htab=new long[1<<14]; for (c=0;c<1<<14;c++) { htab[c]=0; } long hslot; UInt32 iidx = 0; UInt32 oidx = 0; //byte *in_end = ip + in_len; //byte *out_end = op + out_len; long reference; UInt32 hval = FRST (in_data,iidx); long off; int lit = 0; for (;;) { if (iidx < in_len - 2) { hval = NEXT (hval, in_data,iidx); hslot = IDX (hval); reference = htab[hslot]; htab[hslot] = (long)iidx; if ((off = iidx - reference - 1) < MAX_OFF && iidx + 4 < in_len && reference > 0 && in_data[reference+0] == in_data[iidx+0] && in_data[reference+1] == in_data[iidx+1] && in_data[reference+2] == in_data[iidx+2] ) { /* match found at *reference++ */ UInt32 len = 2; UInt32 maxlen = (UInt32)in_len - iidx - len; maxlen = maxlen > MAX_REF ? MAX_REF : maxlen; if (oidx + lit + 1 + 3 >= out_len) return 0; do len++; while (len < maxlen && in_data[reference+len] == in_data[iidx+len]); if (lit!=0) { out_data[oidx++] = (byte)(lit - 1); lit = -lit; do out_data[oidx++] = in_data[iidx+lit]; while ((++lit)!=0); } len -= 2; iidx++; if (len < 7) { out_data[oidx++] = (byte)((off >> 8) + (len << 5)); } else { out_data[oidx++] = (byte)((off >> 8) + ( 7 << 5)); out_data[oidx++] = (byte)(len - 7); } out_data[oidx++] = (byte)off; iidx += len-1; hval = FRST (in_data,iidx); hval = NEXT (hval,in_data, iidx); htab[IDX (hval)] = iidx; iidx++; hval = NEXT (hval, in_data,iidx); htab[IDX (hval)] = iidx; iidx++; continue; } } else if (iidx == in_len) break; /* one more literal byte we must copy */ lit++; iidx++; if (lit == MAX_LIT) { if (oidx + 1 + MAX_LIT >= out_len) return 0; out_data[oidx++] = (byte)(MAX_LIT - 1); lit = -lit; do out_data[oidx++] = in_data[iidx+lit]; while ((++lit)!=0); } } if (lit!=0) { if (oidx + lit + 1 >= out_len) return 0; out_data[oidx++] = (byte)(lit - 1); lit = -lit; do out_data[oidx++] = in_data[iidx+lit]; while ((++lit)!=0); } return (int)oidx; } /// <summary> /// LZF Decompressor /// </summary> public int lzf_decompress ( byte[] in_data, int in_len, byte[] out_data, int out_len) { UInt32 iidx=0; UInt32 oidx=0; do { UInt32 ctrl = in_data[iidx++]; if (ctrl < (1 << 5)) /* literal run */ { ctrl++; if (oidx + ctrl > out_len) { //SET_ERRNO (E2BIG); return 0; } do out_data[oidx++] = in_data[iidx++]; while ((--ctrl)!=0); } else /* back reference */ { UInt32 len = ctrl >> 5; int reference = (int)(oidx - ((ctrl & 0x1f) << 8) - 1); if (len == 7) len += in_data[iidx++]; reference -= in_data[iidx++]; if (oidx + len + 2 > out_len) { //SET_ERRNO (E2BIG); return 0; } if (reference < 0) { //SET_ERRNO (EINVAL); return 0; } out_data[oidx++]=out_data[reference++]; out_data[oidx++]=out_data[reference++]; do out_data[oidx++]=out_data[reference++]; while ((--len)!=0); } } while (iidx < in_len); return (int)oidx; } public CLZF() { // // TODO: Add ructor logic here // } } }
// 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.Xml.Schema; using System.Xml.Xsl.Qil; using System.Xml.Xsl.Runtime; using System.Xml.Xsl.XPath; namespace System.Xml.Xsl.Xslt { using T = XmlQueryTypeFactory; internal class XsltQilFactory : XPathQilFactory { public XsltQilFactory(QilFactory f, bool debug) : base(f, debug) { } [Conditional("DEBUG")] public void CheckXsltType(QilNode n) { // Five possible types are: anyType, node-set, string, boolean, and number XmlQueryType xt = n.XmlType; switch (xt.TypeCode) { case XmlTypeCode.String: case XmlTypeCode.Boolean: case XmlTypeCode.Double: Debug.Assert(xt.IsSingleton && xt.IsStrict, "Xslt assumes that these types will always be singleton and strict"); break; case XmlTypeCode.Item: case XmlTypeCode.None: break; case XmlTypeCode.QName: Debug.Assert(IsDebug, "QName is reserved as the marker for missing values"); break; default: Debug.Assert(xt.IsNode, "Unexpected expression type: " + xt.ToString()); break; } } [Conditional("DEBUG")] public void CheckQName(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.QNameX), "Must be a singleton QName"); } // We use a value of XmlQualifiedName type to denote a missing parameter public QilNode DefaultValueMarker() { return QName("default-value", XmlReservedNs.NsXslDebug); } public QilNode IsDefaultValueMarker(QilNode n) { return IsType(n, T.QNameX); } public QilNode InvokeIsSameNodeSort(QilNode n1, QilNode n2) { CheckNodeNotRtf(n1); CheckNodeNotRtf(n2); return XsltInvokeEarlyBound(QName("is-same-node-sort"), XsltMethods.IsSameNodeSort, T.BooleanX, new QilNode[] { n1, n2 } ); } public QilNode InvokeSystemProperty(QilNode n) { CheckQName(n); return XsltInvokeEarlyBound(QName("system-property"), XsltMethods.SystemProperty, T.Choice(T.DoubleX, T.StringX), new QilNode[] { n } ); } public QilNode InvokeElementAvailable(QilNode n) { CheckQName(n); return XsltInvokeEarlyBound(QName("element-available"), XsltMethods.ElementAvailable, T.BooleanX, new QilNode[] { n } ); } public QilNode InvokeCheckScriptNamespace(string nsUri) { return XsltInvokeEarlyBound(QName("register-script-namespace"), XsltMethods.CheckScriptNamespace, T.IntX, new QilNode[] { String(nsUri) } ); } public QilNode InvokeFunctionAvailable(QilNode n) { CheckQName(n); return XsltInvokeEarlyBound(QName("function-available"), XsltMethods.FunctionAvailable, T.BooleanX, new QilNode[] { n } ); } public QilNode InvokeBaseUri(QilNode n) { CheckNode(n); return XsltInvokeEarlyBound(QName("base-uri"), XsltMethods.BaseUri, T.StringX, new QilNode[] { n } ); } public QilNode InvokeOnCurrentNodeChanged(QilNode n) { CheckNode(n); return XsltInvokeEarlyBound(QName("on-current-node-changed"), XsltMethods.OnCurrentNodeChanged, T.IntX, new QilNode[] { n } ); } public QilNode InvokeLangToLcid(QilNode n, bool fwdCompat) { CheckString(n); return XsltInvokeEarlyBound(QName("lang-to-lcid"), XsltMethods.LangToLcid, T.IntX, new QilNode[] { n, Boolean(fwdCompat) } ); } public QilNode InvokeNumberFormat(QilNode value, QilNode format, QilNode lang, QilNode letterValue, QilNode groupingSeparator, QilNode groupingSize) { Debug.Assert(value != null && ( value.XmlType.IsSubtypeOf(T.IntXS) || value.XmlType.IsSubtypeOf(T.DoubleX)), "Value must be either a sequence of ints, or a double singleton" ); CheckString(format); CheckDouble(lang); CheckString(letterValue); CheckString(groupingSeparator); CheckDouble(groupingSize); return XsltInvokeEarlyBound(QName("number-format"), XsltMethods.NumberFormat, T.StringX, new QilNode[] { value, format, lang, letterValue, groupingSeparator, groupingSize } ); } public QilNode InvokeRegisterDecimalFormat(DecimalFormatDecl format) { Debug.Assert(format != null); return XsltInvokeEarlyBound(QName("register-decimal-format"), XsltMethods.RegisterDecimalFormat, T.IntX, new QilNode[] { QName(format.Name.Name, format.Name.Namespace), String(format.InfinitySymbol), String(format.NanSymbol), String(new string(format.Characters)) } ); } public QilNode InvokeRegisterDecimalFormatter(QilNode formatPicture, DecimalFormatDecl format) { CheckString(formatPicture); Debug.Assert(format != null); return XsltInvokeEarlyBound(QName("register-decimal-formatter"), XsltMethods.RegisterDecimalFormatter, T.DoubleX, new QilNode[] { formatPicture, String(format.InfinitySymbol), String(format.NanSymbol), String(new string(format.Characters)) } ); } public QilNode InvokeFormatNumberStatic(QilNode value, QilNode decimalFormatIndex) { CheckDouble(value); CheckDouble(decimalFormatIndex); return XsltInvokeEarlyBound(QName("format-number-static"), XsltMethods.FormatNumberStatic, T.StringX, new QilNode[] { value, decimalFormatIndex } ); } public QilNode InvokeFormatNumberDynamic(QilNode value, QilNode formatPicture, QilNode decimalFormatName, QilNode errorMessageName) { CheckDouble(value); CheckString(formatPicture); CheckQName(decimalFormatName); CheckString(errorMessageName); return XsltInvokeEarlyBound(QName("format-number-dynamic"), XsltMethods.FormatNumberDynamic, T.StringX, new QilNode[] { value, formatPicture, decimalFormatName, errorMessageName } ); } public QilNode InvokeOuterXml(QilNode n) { CheckNode(n); return XsltInvokeEarlyBound(QName("outer-xml"), XsltMethods.OuterXml, T.StringX, new QilNode[] { n } ); } public QilNode InvokeMsFormatDateTime(QilNode datetime, QilNode format, QilNode lang, QilNode isDate) { CheckString(datetime); CheckString(format); CheckString(lang); CheckBool(isDate); return XsltInvokeEarlyBound(QName("ms:format-date-time"), XsltMethods.MSFormatDateTime, T.StringX, new QilNode[] { datetime, format, lang, isDate } ); } public QilNode InvokeMsStringCompare(QilNode x, QilNode y, QilNode lang, QilNode options) { CheckString(x); CheckString(y); CheckString(lang); CheckString(options); return XsltInvokeEarlyBound(QName("ms:string-compare"), XsltMethods.MSStringCompare, T.DoubleX, new QilNode[] { x, y, lang, options } ); } public QilNode InvokeMsUtc(QilNode n) { CheckString(n); return XsltInvokeEarlyBound(QName("ms:utc"), XsltMethods.MSUtc, T.StringX, new QilNode[] { n } ); } public QilNode InvokeMsNumber(QilNode n) { return XsltInvokeEarlyBound(QName("ms:number"), XsltMethods.MSNumber, T.DoubleX, new QilNode[] { n } ); } public QilNode InvokeMsLocalName(QilNode n) { CheckString(n); return XsltInvokeEarlyBound(QName("ms:local-name"), XsltMethods.MSLocalName, T.StringX, new QilNode[] { n } ); } public QilNode InvokeMsNamespaceUri(QilNode n, QilNode currentNode) { CheckString(n); CheckNodeNotRtf(currentNode); return XsltInvokeEarlyBound(QName("ms:namespace-uri"), XsltMethods.MSNamespaceUri, T.StringX, new QilNode[] { n, currentNode } ); } public QilNode InvokeEXslObjectType(QilNode n) { return XsltInvokeEarlyBound(QName("exsl:object-type"), XsltMethods.EXslObjectType, T.StringX, new QilNode[] { n } ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Net.Quic; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Internal { internal partial class QuicStreamContext : TransportConnection, IPooledStream, IDisposable { // Internal for testing. internal Task _processingTask = Task.CompletedTask; private QuicStream? _stream; private readonly QuicConnectionContext _connection; private readonly QuicTransportContext _context; private readonly Pipe _inputPipe; private readonly Pipe _outputPipe; private readonly IDuplexPipe _originalTransport; private readonly IDuplexPipe _originalApplication; private readonly CompletionPipeReader _transportPipeReader; private readonly CompletionPipeWriter _transportPipeWriter; private readonly ILogger _log; private CancellationTokenSource _streamClosedTokenSource = default!; private string? _connectionId; private const int MinAllocBufferSize = 4096; private volatile Exception? _shutdownReadReason; private volatile Exception? _shutdownWriteReason; private volatile Exception? _shutdownReason; private volatile Exception? _writeAbortException; private bool _streamClosed; private bool _serverAborted; private bool _clientAbort; private TaskCompletionSource _waitForConnectionClosedTcs = default!; private readonly object _shutdownLock = new object(); public QuicStreamContext(QuicConnectionContext connection, QuicTransportContext context) { _connection = connection; _context = context; _log = context.Log; MemoryPool = connection.MemoryPool; MultiplexedConnectionFeatures = connection.Features; RemoteEndPoint = connection.RemoteEndPoint; LocalEndPoint = connection.LocalEndPoint; var maxReadBufferSize = context.Options.MaxReadBufferSize ?? 0; var maxWriteBufferSize = context.Options.MaxWriteBufferSize ?? 0; // TODO should we allow these PipeScheduler to be configurable here? var inputOptions = new PipeOptions(MemoryPool, PipeScheduler.ThreadPool, PipeScheduler.Inline, maxReadBufferSize, maxReadBufferSize / 2, useSynchronizationContext: false); var outputOptions = new PipeOptions(MemoryPool, PipeScheduler.Inline, PipeScheduler.ThreadPool, maxWriteBufferSize, maxWriteBufferSize / 2, useSynchronizationContext: false); _inputPipe = new Pipe(inputOptions); _outputPipe = new Pipe(outputOptions); _transportPipeReader = new CompletionPipeReader(_inputPipe.Reader); _transportPipeWriter = new CompletionPipeWriter(_outputPipe.Writer); _originalApplication = new DuplexPipe(_outputPipe.Reader, _inputPipe.Writer); _originalTransport = new DuplexPipe(_transportPipeReader, _transportPipeWriter); } public override MemoryPool<byte> MemoryPool { get; } private PipeWriter Input => Application.Output; private PipeReader Output => Application.Input; public bool CanReuse { get; private set; } public void Initialize(QuicStream stream) { Debug.Assert(_stream == null); _stream = stream; if (!(_streamClosedTokenSource?.TryReset() ?? false)) { _streamClosedTokenSource = new CancellationTokenSource(); } ConnectionClosed = _streamClosedTokenSource.Token; InitializeFeatures(); CanRead = _stream.CanRead; CanWrite = _stream.CanWrite; _error = null; StreamId = _stream.StreamId; PoolExpirationTicks = 0; Transport = _originalTransport; Application = _originalApplication; _transportPipeReader.Reset(); _transportPipeWriter.Reset(); _connectionId = null; _shutdownReason = null; _writeAbortException = null; _streamClosed = false; _serverAborted = false; _clientAbort = false; // TODO - resetable TCS _waitForConnectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Only reset pipes if the stream has been reused. if (CanReuse) { _inputPipe.Reset(); _outputPipe.Reset(); } CanReuse = false; } public override string ConnectionId { get => _connectionId ??= StringUtilities.ConcatAsHexSuffix(_connection.ConnectionId, ':', (uint)StreamId); set => _connectionId = value; } public long PoolExpirationTicks { get; set; } public void Start() { Debug.Assert(_processingTask.IsCompletedSuccessfully); _processingTask = StartAsync(); } private async Task StartAsync() { Debug.Assert(_stream != null); try { // Spawn send and receive logic // Streams may or may not have reading/writing, so only start tasks accordingly var receiveTask = Task.CompletedTask; var sendTask = Task.CompletedTask; if (_stream.CanRead) { receiveTask = DoReceive(); } if (_stream.CanWrite) { sendTask = DoSend(); } // Now wait for both to complete await receiveTask; await sendTask; await FireStreamClosedAsync(); } catch (Exception ex) { _log.LogError(0, ex, $"Unexpected exception in {nameof(QuicStreamContext)}.{nameof(StartAsync)}."); } } private async Task WaitForWritesCompleted() { Debug.Assert(_stream != null); try { await _stream.WaitForWriteCompletionAsync(); } catch (Exception ex) { // Send error to DoSend loop. _writeAbortException = ex; } finally { Output.CancelPendingRead(); } } private async Task DoReceive() { Debug.Assert(_stream != null); Exception? error = null; try { var input = Input; while (true) { var buffer = input.GetMemory(MinAllocBufferSize); var bytesReceived = await _stream.ReadAsync(buffer); if (bytesReceived == 0) { // Read completed. break; } input.Advance(bytesReceived); ValueTask<FlushResult> flushTask; if (_stream.ReadsCompleted) { // If the data returned from ReadAsync is the final chunk on the stream then // flush data and end pipe together with CompleteAsync. // // Getting data and complete together is important for HTTP/3 when parsing headers. // It is important that it knows that there is no body after the headers. var completeTask = input.CompleteAsync(); if (completeTask.IsCompletedSuccessfully) { // Fast path. CompleteAsync completed immediately. // Most implementations of ValueTask reset state in GetResult. completeTask.GetAwaiter().GetResult(); flushTask = ValueTask.FromResult(new FlushResult(isCanceled: false, isCompleted: true)); } else { flushTask = AwaitCompleteTaskAsync(completeTask); } } else { flushTask = input.FlushAsync(); } var paused = !flushTask.IsCompleted; if (paused) { QuicLog.StreamPause(_log, this); } var result = await flushTask; if (paused) { QuicLog.StreamResume(_log, this); } if (result.IsCompleted || result.IsCanceled) { // Pipe consumer is shut down, do we stop writing break; } } } catch (QuicStreamAbortedException ex) { // Abort from peer. _error = ex.ErrorCode; QuicLog.StreamAbortedRead(_log, this, ex.ErrorCode); // This could be ignored if _shutdownReason is already set. error = new ConnectionResetException(ex.Message, ex); _clientAbort = true; } catch (QuicConnectionAbortedException ex) { // Abort from peer. _error = ex.ErrorCode; QuicLog.StreamAbortedRead(_log, this, ex.ErrorCode); // This could be ignored if _shutdownReason is already set. error = new ConnectionResetException(ex.Message, ex); _clientAbort = true; } catch (QuicOperationAbortedException ex) { // AbortRead has been called for the stream. error = new ConnectionAbortedException(ex.Message, ex); } catch (Exception ex) { // This is unexpected. error = ex; QuicLog.StreamError(_log, this, error); } finally { // If Shutdown() has already bee called, assume that was the reason ProcessReceives() exited. Input.Complete(ResolveCompleteReceiveException(error)); } async static ValueTask<FlushResult> AwaitCompleteTaskAsync(ValueTask completeTask) { await completeTask; return new FlushResult(isCanceled: false, isCompleted: true); } } private Exception? ResolveCompleteReceiveException(Exception? error) { return _shutdownReadReason ?? _shutdownReason ?? error; } private Task FireStreamClosedAsync() { // Guard against scheduling this multiple times if (_streamClosed) { return Task.CompletedTask; } _streamClosed = true; ThreadPool.UnsafeQueueUserWorkItem(state => { state.CancelConnectionClosedToken(); state._waitForConnectionClosedTcs.TrySetResult(); }, this, preferLocal: false); return _waitForConnectionClosedTcs.Task; } private void CancelConnectionClosedToken() { try { _streamClosedTokenSource.Cancel(); } catch (Exception ex) { _log.LogError(0, ex, $"Unexpected exception in {nameof(QuicStreamContext)}.{nameof(CancelConnectionClosedToken)}."); } } private async Task DoSend() { Debug.Assert(_stream != null); Exception? shutdownReason = null; Exception? unexpectedError = null; var sendCompletedTask = WaitForWritesCompleted(); try { // Resolve `output` PipeReader via the IDuplexPipe interface prior to loop start for performance. var output = Output; while (true) { var result = await output.ReadAsync(); if (result.IsCanceled) { // WaitForWritesCompleted provides immediate notification that write-side of stream has completed. // If the stream or connection is aborted then exception will be available to rethrow. if (_writeAbortException != null) { ExceptionDispatchInfo.Throw(_writeAbortException); } break; } var buffer = result.Buffer; var end = buffer.End; var isCompleted = result.IsCompleted; if (!buffer.IsEmpty) { await _stream.WriteAsync(buffer, endStream: isCompleted); } output.AdvanceTo(end); if (isCompleted) { // Once the stream pipe is closed, shutdown the stream. break; } } } catch (QuicStreamAbortedException ex) { // Abort from peer. _error = ex.ErrorCode; QuicLog.StreamAbortedWrite(_log, this, ex.ErrorCode); // This could be ignored if _shutdownReason is already set. shutdownReason = new ConnectionResetException(ex.Message, ex); _clientAbort = true; } catch (QuicConnectionAbortedException ex) { // Abort from peer. _error = ex.ErrorCode; QuicLog.StreamAbortedWrite(_log, this, ex.ErrorCode); // This could be ignored if _shutdownReason is already set. shutdownReason = new ConnectionResetException(ex.Message, ex); _clientAbort = true; } catch (QuicOperationAbortedException ex) { // AbortWrite has been called for the stream. // Possibily might also get here from connection closing. // System.Net.Quic exception handling not finalized. shutdownReason = new ConnectionResetException(ex.Message, ex); } catch (Exception ex) { shutdownReason = ex; unexpectedError = ex; QuicLog.StreamError(_log, this, unexpectedError); } finally { ShutdownWrite(_shutdownWriteReason ?? _shutdownReason ?? shutdownReason); await sendCompletedTask; // Complete the output after completing stream sends Output.Complete(unexpectedError); // Cancel any pending flushes so that the input loop is un-paused Input.CancelPendingFlush(); } } public override void Abort(ConnectionAbortedException abortReason) { // This abort is called twice, make sure that doesn't happen. // Don't call _stream.Shutdown and _stream.Abort at the same time. if (_serverAborted) { return; } _serverAborted = true; _shutdownReason = abortReason; var resolvedErrorCode = _error ?? 0; QuicLog.StreamAbort(_log, this, resolvedErrorCode, abortReason.Message); lock (_shutdownLock) { if (_stream != null) { if (_stream.CanRead) { _stream.AbortRead(resolvedErrorCode); } if (_stream.CanWrite) { _stream.AbortWrite(resolvedErrorCode); } } } // Cancel ProcessSends loop after calling shutdown to ensure the correct _shutdownReason gets set. Output.CancelPendingRead(); } private void ShutdownWrite(Exception? shutdownReason) { Debug.Assert(_stream != null); try { lock (_shutdownLock) { // TODO: Exception is always allocated. Consider only allocating if receive hasn't completed. _shutdownReason = shutdownReason ?? new ConnectionAbortedException("The QUIC transport's send loop completed gracefully."); QuicLog.StreamShutdownWrite(_log, this, _shutdownReason.Message); _stream.Shutdown(); } } catch (Exception ex) { _log.LogWarning(ex, "Stream failed to gracefully shutdown."); // Ignore any errors from Shutdown() since we're tearing down the stream anyway. } } public override async ValueTask DisposeAsync() { if (_stream == null) { return; } _originalTransport.Input.Complete(); _originalTransport.Output.Complete(); await _processingTask; lock (_shutdownLock) { // CanReuse must not be calculated while draining stream. It is possible for // an abort to be received while any methods are still running. // It is safe to calculate CanReuse after processing is completed. // // Be conservative about what can be pooled. // Only pool bidirectional streams whose pipes have completed successfully and haven't been aborted. CanReuse = _stream.CanRead && _stream.CanWrite && _transportPipeReader.IsCompletedSuccessfully && _transportPipeWriter.IsCompletedSuccessfully && !_clientAbort && !_serverAborted && _shutdownReadReason == null && _shutdownWriteReason == null; if (!CanReuse) { DisposeCore(); } _stream.Dispose(); _stream = null!; } } public void Dispose() { if (!_connection.TryReturnStream(this)) { // Dispose when one of: // - Stream is not bidirection // - Stream didn't complete gracefully // - Pool is full DisposeCore(); } } // Called when the stream is no longer reused. public void DisposeCore() { _streamClosedTokenSource.Dispose(); } } }
/* * 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.Xml; using System.IO; using System.Collections.Generic; using System.Collections; using System.Reflection; using System.Threading; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Scripting; using OpenSim.Region.Framework.Scenes.Serialization; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.Framework.Scenes { public class SceneObjectPartInventory : IEntityInventory { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_inventoryFileName = String.Empty; private byte[] m_inventoryFileData = new byte[0]; private uint m_inventoryFileNameSerial = 0; /// <value> /// The part to which the inventory belongs. /// </value> private SceneObjectPart m_part; /// <summary> /// Serial count for inventory file , used to tell if inventory has changed /// no need for this to be part of Database backup /// </summary> protected uint m_inventorySerial = 0; /// <summary> /// Holds in memory prim inventory /// </summary> protected TaskInventoryDictionary m_items = new TaskInventoryDictionary(); /// <summary> /// Tracks whether inventory has changed since the last persistent backup /// </summary> internal bool HasInventoryChanged; /// <value> /// Inventory serial number /// </value> protected internal uint Serial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } /// <value> /// Raw inventory data /// </value> protected internal TaskInventoryDictionary Items { get { return m_items; } set { m_items = value; m_inventorySerial++; QueryScriptStates(); } } public int Count { get { lock (m_items) return m_items.Count; } } /// <summary> /// Constructor /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// </param> public SceneObjectPartInventory(SceneObjectPart part) { m_part = part; } /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> public void ForceInventoryPersistence() { HasInventoryChanged = true; } /// <summary> /// Reset UUIDs for all the items in the prim's inventory. /// </summary> /// <remarks> /// This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// </remarks> public void ResetInventoryIDs() { if (null == m_part) return; lock (m_items) { if (0 == m_items.Count) return; IList<TaskInventoryItem> items = GetInventoryItems(); m_items.Clear(); foreach (TaskInventoryItem item in items) { item.ResetIDs(m_part.UUID); m_items.Add(item.ItemID, item); } } } public void ResetObjectID() { lock (Items) { IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); Items.Clear(); foreach (TaskInventoryItem item in items) { item.ParentPartID = m_part.UUID; item.ParentID = m_part.UUID; Items.Add(item.ItemID, item); } } } /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> public void ChangeInventoryOwner(UUID ownerId) { lock (Items) { if (0 == Items.Count) { return; } } HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) item.LastOwnerID = item.OwnerID; item.OwnerID = ownerId; item.PermsMask = 0; item.PermsGranter = UUID.Zero; item.OwnerChanged = true; } } /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> public void ChangeInventoryGroup(UUID groupID) { lock (Items) { if (0 == Items.Count) { return; } } // Don't let this set the HasGroupChanged flag for attachments // as this happens during rez and we don't want a new asset // for each attachment each time if (!m_part.ParentGroup.IsAttachment) { HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (groupID != item.GroupID) item.GroupID = groupID; } } private void QueryScriptStates() { if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null) return; lock (Items) { foreach (TaskInventoryItem item in Items.Values) { bool running; if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running)) item.ScriptRunning = running; } } } public bool TryGetScriptInstanceRunning(UUID itemId, out bool running) { running = false; TaskInventoryItem item = GetInventoryItem(itemId); if (item == null) return false; return TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running); } public static bool TryGetScriptInstanceRunning(Scene scene, TaskInventoryItem item, out bool running) { running = false; if (item.InvType != (int)InventoryType.LSL) return false; IScriptModule[] engines = scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) // No engine at all return false; foreach (IScriptModule e in engines) { if (e.HasScript(item.ItemID, out running)) return true; } return false; } public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) { int scriptsValidForStarting = 0; List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); foreach (TaskInventoryItem item in scripts) if (CreateScriptInstance(item, startParam, postOnRez, engine, stateSource)) scriptsValidForStarting++; return scriptsValidForStarting; } public ArrayList GetScriptErrors(UUID itemID) { ArrayList ret = new ArrayList(); IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule e in engines) { if (e != null) { ArrayList errors = e.GetScriptErrors(itemID); foreach (Object line in errors) ret.Add(line); } } return ret; } /// <summary> /// Stop and remove all the scripts in this prim. /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); foreach (TaskInventoryItem item in scripts) RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); } /// <summary> /// Stop all the scripts in this prim. /// </summary> public void StopScriptInstances() { GetInventoryItems(InventoryType.LSL).ForEach(i => StopScriptInstance(i)); } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <returns>true if the script instance was created, false otherwise</returns> public bool CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource) { // m_log.DebugFormat("[PRIM INVENTORY]: Starting script {0} {1} in prim {2} {3} in {4}", // item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName); if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return false; m_part.AddFlag(PrimFlags.Scripted); if (m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) return false; if (stateSource == 2 && // Prim crossing m_part.ParentGroup.Scene.m_trustBinaries) { lock (m_items) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); return true; } AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); if (null == asset) { m_log.ErrorFormat( "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", item.Name, item.ItemID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID); return false; } else { if (m_part.ParentGroup.m_savedScriptState != null) item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID); lock (m_items) { m_items[item.ItemID].OldItemID = item.OldItemID; m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } string script = Utils.BytesToString(asset.Data); m_part.ParentGroup.Scene.EventManager.TriggerRezScript( m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); if (!item.ScriptRunning) m_part.ParentGroup.Scene.EventManager.TriggerStopScript( m_part.LocalId, item.ItemID); m_part.ParentGroup.AddActiveScriptCount(1); m_part.ScheduleFullUpdate(); return true; } } private UUID RestoreSavedScriptState(UUID loadedID, UUID oldID, UUID newID) { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines.Length == 0) // No engine at all return oldID; UUID stateID = oldID; if (!m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID)) stateID = loadedID; if (m_part.ParentGroup.m_savedScriptState.ContainsKey(stateID)) { XmlDocument doc = new XmlDocument(); doc.LoadXml(m_part.ParentGroup.m_savedScriptState[stateID]); ////////// CRUFT WARNING /////////////////////////////////// // // Old objects will have <ScriptState><State> ... // This format is XEngine ONLY // // New objects have <State Engine="...." ...><ScriptState>... // This can be passed to any engine // XmlNode n = doc.SelectSingleNode("ScriptState"); if (n != null) // Old format data { XmlDocument newDoc = new XmlDocument(); XmlElement rootN = newDoc.CreateElement("", "State", ""); XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", ""); uuidA.Value = stateID.ToString(); rootN.Attributes.Append(uuidA); XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", ""); engineA.Value = "XEngine"; rootN.Attributes.Append(engineA); newDoc.AppendChild(rootN); XmlNode stateN = newDoc.ImportNode(n, true); rootN.AppendChild(stateN); // This created document has only the minimun data // necessary for XEngine to parse it successfully m_part.ParentGroup.m_savedScriptState[stateID] = newDoc.OuterXml; } foreach (IScriptModule e in engines) { if (e != null) { if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[stateID])) break; } } m_part.ParentGroup.m_savedScriptState.Remove(stateID); } return stateID; } public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) { TaskInventoryItem item = GetInventoryItem(itemId); if (item != null) { return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); return false; } } /// <summary> /// Stop and remove a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) { bool scriptPresent = false; lock (m_items) { if (m_items.ContainsKey(itemId)) scriptPresent = true; } if (scriptPresent) { if (!sceneObjectBeingDeleted) m_part.RemoveScriptEvents(itemId); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId); m_part.ParentGroup.AddActiveScriptCount(-1); } else { m_log.WarnFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void StopScriptInstance(UUID itemId) { TaskInventoryItem scriptItem; lock (m_items) m_items.TryGetValue(itemId, out scriptItem); if (scriptItem != null) { StopScriptInstance(scriptItem); } else { m_log.WarnFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void StopScriptInstance(TaskInventoryItem item) { if (m_part.ParentGroup.Scene != null) m_part.ParentGroup.Scene.EventManager.TriggerStopScript(m_part.LocalId, item.ItemID); // At the moment, even stopped scripts are counted as active, which is probably wrong. // m_part.ParentGroup.AddActiveScriptCount(-1); } /// <summary> /// Check if the inventory holds an item with a given name. /// </summary> /// <param name="name"></param> /// <returns></returns> private bool InventoryContainsName(string name) { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) return true; } } return false; } /// <summary> /// For a given item name, return that name if it is available. Otherwise, return the next available /// similar name (which is currently the original name with the next available numeric suffix). /// </summary> /// <param name="name"></param> /// <returns></returns> private string FindAvailableInventoryName(string name) { if (!InventoryContainsName(name)) return name; int suffix=1; while (suffix < 256) { string tryName=String.Format("{0} {1}", name, suffix); if (!InventoryContainsName(tryName)) return tryName; suffix++; } return String.Empty; } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop) { AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) { List<TaskInventoryItem> il = GetInventoryItems(); foreach (TaskInventoryItem i in il) { if (i.Name == item.Name) { if (i.InvType == (int)InventoryType.LSL) RemoveScriptInstance(i.ItemID, false); RemoveInventoryItem(i.ItemID); break; } } AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. /// </summary> /// <param name="name">The name that the new item should have.</param> /// <param name="item"> /// The item itself. The name within this structure is ignored in favour of the name /// given in this method's arguments /// </param> /// <param name="allowedDrop"> /// Item was only added to inventory because AllowedDrop is set /// </param> protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop) { name = FindAvailableInventoryName(name); if (name == String.Empty) return; item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Name = name; item.GroupID = m_part.GroupID; lock (m_items) m_items.Add(item.ItemID, item); if (allowedDrop) m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); else m_part.TriggerScriptChangedEvent(Changed.INVENTORY); m_inventorySerial++; //m_inventorySerial += 2; HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } /// <summary> /// Restore a whole collection of items to the prim's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) { lock (m_items) { foreach (TaskInventoryItem item in items) { m_items.Add(item.ItemID, item); // m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } m_inventorySerial++; } } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(UUID itemId) { TaskInventoryItem item; lock (m_items) m_items.TryGetValue(itemId, out item); return item; } public TaskInventoryItem GetInventoryItem(string name) { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) return item; } } return null; } public List<TaskInventoryItem> GetInventoryItems(string name) { List<TaskInventoryItem> items = new List<TaskInventoryItem>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) items.Add(item); } } return items; } public SceneObjectGroup GetRezReadySceneObject(TaskInventoryItem item) { AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); if (null == rezAsset) { m_log.WarnFormat( "[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}", item.AssetID, item.Name, m_part.Name); return null; } string xmlData = Utils.BytesToString(rezAsset.Data); SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); group.ResetIDs(); SceneObjectPart rootPart = group.GetPart(group.UUID); // Since renaming the item in the inventory does not affect the name stored // in the serialization, transfer the correct name from the inventory to the // object itself before we rez. rootPart.Name = item.Name; rootPart.Description = item.Description; SceneObjectPart[] partList = group.Parts; group.SetGroup(m_part.GroupID, null); // TODO: Remove magic number badness if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number { if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart part in partList) { if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) part.EveryoneMask = item.EveryonePermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) part.GroupMask = item.GroupPermissions; } group.ApplyNextOwnerPermissions(); } } foreach (SceneObjectPart part in partList) { // TODO: Remove magic number badness if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number { part.LastOwnerID = part.OwnerID; part.OwnerID = item.OwnerID; part.Inventory.ChangeInventoryOwner(item.OwnerID); } if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) part.EveryoneMask = item.EveryonePermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) part.GroupMask = item.GroupPermissions; } rootPart.TrimPermissions(); return group; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { return UpdateInventoryItem(item, true, true); } public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents) { return UpdateInventoryItem(item, fireScriptEvents, true); } public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged) { TaskInventoryItem it = GetInventoryItem(item.ItemID); if (it != null) { // m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name); item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; // If group permissions have been set on, check that the groupID is up to date in case it has // changed since permissions were last set. if (item.GroupPermissions != (uint)PermissionMask.None) item.GroupID = m_part.GroupID; if (item.AssetID == UUID.Zero) item.AssetID = it.AssetID; lock (m_items) { m_items[item.ItemID] = item; m_inventorySerial++; } if (fireScriptEvents) m_part.TriggerScriptChangedEvent(Changed.INVENTORY); if (considerChanged) { HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; } return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", item.ItemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } return false; } /// <summary> /// Remove an item from this prim's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> public int RemoveInventoryItem(UUID itemID) { TaskInventoryItem item = GetInventoryItem(itemID); if (item != null) { int type = m_items[itemID].InvType; if (type == 10) // Script { m_part.RemoveScriptEvents(itemID); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); } m_items.Remove(itemID); m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; m_part.ParentGroup.HasGroupChanged = true; if (!ContainsScripts()) m_part.RemFlag(PrimFlags.Scripted); m_part.ScheduleFullUpdate(); return type; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", itemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } return -1; } private bool CreateInventoryFile() { // m_log.DebugFormat( // "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}", // m_part.Name, m_part.UUID, m_part.LocalId, m_inventorySerial); if (m_inventoryFileName == String.Empty || m_inventoryFileNameSerial < m_inventorySerial) { // Something changed, we need to create a new file m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; m_inventoryFileNameSerial = m_inventorySerial; InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { // m_log.DebugFormat( // "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}", // item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId); UUID ownerID = item.OwnerID; uint everyoneMask = 0; uint baseMask = item.BasePermissions; uint ownerMask = item.CurrentPermissions; uint groupMask = item.GroupPermissions; invString.AddItemStart(); invString.AddNameValueLine("item_id", item.ItemID.ToString()); invString.AddNameValueLine("parent_id", m_part.UUID.ToString()); invString.AddPermissionsStart(); invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask)); invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask)); invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask)); invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask)); invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions)); invString.AddNameValueLine("creator_id", item.CreatorID.ToString()); invString.AddNameValueLine("owner_id", ownerID.ToString()); invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString()); invString.AddNameValueLine("group_id", item.GroupID.ToString()); invString.AddSectionEnd(); invString.AddNameValueLine("asset_id", item.AssetID.ToString()); invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type)); invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType)); invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags)); invString.AddSaleStart(); invString.AddNameValueLine("sale_type", "not"); invString.AddNameValueLine("sale_price", "0"); invString.AddSectionEnd(); invString.AddNameValueLine("name", item.Name + "|"); invString.AddNameValueLine("desc", item.Description + "|"); invString.AddNameValueLine("creation_date", item.CreationDate.ToString()); invString.AddSectionEnd(); } } m_inventoryFileData = Utils.StringToBytes(invString.BuildString); return true; } // No need to recreate, the existing file is fine return false; } /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="xferManager"></param> public void RequestInventoryFile(IClientAPI client, IXfer xferManager) { lock (m_items) { // Don't send a inventory xfer name if there are no items. Doing so causes viewer 3 to crash when rezzing // a new script if any previous deletion has left the prim inventory empty. if (m_items.Count == 0) // No inventory { // m_log.DebugFormat( // "[PRIM INVENTORY]: Not sending inventory data for part {0} {1} {2} for {3} since no items", // m_part.Name, m_part.LocalId, m_part.UUID, client.Name); client.SendTaskInventory(m_part.UUID, 0, new byte[0]); return; } CreateInventoryFile(); // In principle, we should only do the rest if the inventory changed; // by sending m_inventorySerial to the client, it ought to know // that nothing changed and that it doesn't need to request the file. // Unfortunately, it doesn't look like the client optimizes this; // the client seems to always come back and request the Xfer, // no matter what value m_inventorySerial has. // FIXME: Could probably be > 0 here rather than > 2 if (m_inventoryFileData.Length > 2) { // Add the file for Xfer // m_log.DebugFormat( // "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}", // m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId); xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData); } // Tell the client we're ready to Xfer the file client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial, Util.StringToBytes256(m_inventoryFileName)); } } /// <summary> /// Process inventory backup /// </summary> /// <param name="datastore"></param> public void ProcessInventoryBackup(ISimulationDataService datastore) { if (HasInventoryChanged) { HasInventoryChanged = false; List<TaskInventoryItem> items = GetInventoryItems(); datastore.StorePrimInventory(m_part.UUID, items); } } public class InventoryStringBuilder { public string BuildString = String.Empty; public InventoryStringBuilder(UUID folderID, UUID parentID) { BuildString += "\tinv_object\t0\n\t{\n"; AddNameValueLine("obj_id", folderID.ToString()); AddNameValueLine("parent_id", parentID.ToString()); AddNameValueLine("type", "category"); AddNameValueLine("name", "Contents|"); AddSectionEnd(); } public void AddItemStart() { BuildString += "\tinv_item\t0\n"; AddSectionStart(); } public void AddPermissionsStart() { BuildString += "\tpermissions 0\n"; AddSectionStart(); } public void AddSaleStart() { BuildString += "\tsale_info\t0\n"; AddSectionStart(); } protected void AddSectionStart() { BuildString += "\t{\n"; } public void AddSectionEnd() { BuildString += "\t}\n"; } public void AddLine(string addLine) { BuildString += addLine; } public void AddNameValueLine(string name, string value) { BuildString += "\t\t"; BuildString += name + "\t"; BuildString += value + "\n"; } public void Close() { } } public uint MaskEffectivePermissions() { uint mask=0x7fffffff; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); if (item.InvType != (int)InventoryType.Object) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } else { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~(uint)PermissionMask.Modify; } } return mask; } public void ApplyNextOwnerPermissions() { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { // m_log.DebugFormat ( // "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}", // item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions); if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; item.OwnerChanged = true; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } } } public void ApplyGodPermissions(uint perms) { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { item.CurrentPermissions = perms; item.BasePermissions = perms; } } m_inventorySerial++; HasInventoryChanged = true; } /// <summary> /// Returns true if this part inventory contains any scripts. False otherwise. /// </summary> /// <returns></returns> public bool ContainsScripts() { lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { return true; } } } return false; } /// <summary> /// Returns the count of scripts in this parts inventory. /// </summary> /// <returns></returns> public int ScriptCount() { int count = 0; lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { count++; } } } return count; } /// <summary> /// Returns the count of running scripts in this parts inventory. /// </summary> /// <returns></returns> public int RunningScriptCount() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines.Length == 0) return 0; int count = 0; List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); foreach (TaskInventoryItem item in scripts) { foreach (IScriptModule engine in engines) { if (engine != null) { if (engine.GetScriptState(item.ItemID)) { count++; } } } } return count; } public List<UUID> GetInventoryList() { List<UUID> ret = new List<UUID>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) ret.Add(item.ItemID); } return ret; } public List<TaskInventoryItem> GetInventoryItems() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_items) ret = new List<TaskInventoryItem>(m_items.Values); return ret; } public List<TaskInventoryItem> GetInventoryItems(InventoryType type) { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_items) { foreach (TaskInventoryItem item in m_items.Values) if (item.InvType == (int)type) ret.Add(item); } return ret; } public Dictionary<UUID, string> GetScriptStates() { Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); if (m_part.ParentGroup.Scene == null) // Group not in a scene return ret; IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines.Length == 0) // No engine at all return ret; List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); foreach (TaskInventoryItem item in scripts) { foreach (IScriptModule e in engines) { if (e != null) { // m_log.DebugFormat( // "[PRIM INVENTORY]: Getting script state from engine {0} for {1} in part {2} in group {3} in {4}", // e.Name, item.Name, m_part.Name, m_part.ParentGroup.Name, m_part.ParentGroup.Scene.Name); string n = e.GetXMLState(item.ItemID); if (n != String.Empty) { if (!ret.ContainsKey(item.ItemID)) ret[item.ItemID] = n; break; } } } } return ret; } public void ResumeScripts() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines.Length == 0) return; List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); foreach (TaskInventoryItem item in scripts) { foreach (IScriptModule engine in engines) { if (engine != null) { // m_log.DebugFormat( // "[PRIM INVENTORY]: Resuming script {0} {1} for {2}, OwnerChanged {3}", // item.Name, item.ItemID, item.OwnerID, item.OwnerChanged); engine.ResumeScript(item.ItemID); if (item.OwnerChanged) engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER }); item.OwnerChanged = false; } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using Xunit; namespace Test { public class CaptureCollectionTests { [Fact] public static void CaptureCollection_GetEnumeratorTest_Negative() { CaptureCollection collection = CreateCollection(); IEnumerator enumerator = collection.GetEnumerator(); Capture current; Assert.Throws<InvalidOperationException>(() => current = (Capture)enumerator.Current); for (int i = 0; i < collection.Count; i++) { enumerator.MoveNext(); } enumerator.MoveNext(); Assert.Throws<InvalidOperationException>(() => current = (Capture)enumerator.Current); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => current = (Capture)enumerator.Current); } [Fact] public static void CaptureCollection_GetEnumeratorTest() { CaptureCollection collection = CreateCollection(); IEnumerator enumerator = collection.GetEnumerator(); for (int i = 0; i < collection.Count; i++) { enumerator.MoveNext(); Assert.Equal(enumerator.Current, collection[i]); } Assert.False(enumerator.MoveNext()); enumerator.Reset(); for (int i = 0; i < collection.Count; i++) { enumerator.MoveNext(); Assert.Equal(enumerator.Current, collection[i]); } } [Fact] public static void Indexer() { CaptureCollection collection = CreateCollection(); Assert.Equal("This ", collection[0].ToString()); Assert.Equal("is ", collection[1].ToString()); Assert.Equal("a ", collection[2].ToString()); Assert.Equal("sentence", collection[3].ToString()); } [Fact] public static void IndexerIListOfT() { IList<Capture> collection = CreateCollection(); Assert.Equal("This ", collection[0].ToString()); Assert.Equal("is ", collection[1].ToString()); Assert.Equal("a ", collection[2].ToString()); Assert.Equal("sentence", collection[3].ToString()); } [Fact] public static void IndexerIListNonGeneric() { IList collection = CreateCollection(); Assert.Equal("This ", collection[0].ToString()); Assert.Equal("is ", collection[1].ToString()); Assert.Equal("a ", collection[2].ToString()); Assert.Equal("sentence", collection[3].ToString()); } [Fact] public static void Contains() { ICollection<Capture> collection = CreateCollection(); foreach (Capture item in collection) { Assert.True(collection.Contains(item)); } foreach (Capture item in CreateCollection()) { Assert.False(collection.Contains(item)); } } [Fact] public static void ContainsNonGeneric() { IList collection = CreateCollection(); foreach (object item in collection) { Assert.True(collection.Contains(item)); } foreach (object item in CreateCollection()) { Assert.False(collection.Contains(item)); } Assert.False(collection.Contains(new object())); } [Fact] public static void IndexOf() { IList<Capture> collection = CreateCollection(); int i = 0; foreach (Capture item in collection) { Assert.Equal(i, collection.IndexOf(item)); i++; } foreach (Capture item in CreateCollection()) { Assert.Equal(-1, collection.IndexOf(item)); } } [Fact] public static void IndexOfNonGeneric() { IList collection = CreateCollection(); int i = 0; foreach (object item in collection) { Assert.Equal(i, collection.IndexOf(item)); i++; } foreach (object item in CreateCollection()) { Assert.Equal(-1, collection.IndexOf(item)); } Assert.Equal(-1, collection.IndexOf(new object())); } [Fact] public static void CopyToExceptions() { CaptureCollection collection = CreateCollection(); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(new Capture[1], -1)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new Capture[1], 0)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new Capture[1], 1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(new Capture[1], 2)); } [Fact] public static void CopyToNonGenericExceptions() { ICollection collection = CreateCollection(); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new Capture[10, 10], 0)); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new Capture[1], -1)); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new Capture[1], 0)); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new Capture[1], 1)); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new Capture[1], 2)); Assert.Throws<InvalidCastException>(() => collection.CopyTo(new int[collection.Count], 0)); } [Fact] public static void CopyTo() { string[] expected = new[] { "This ", "is ", "a ", "sentence" }; CaptureCollection collection = CreateCollection(); Capture[] array = new Capture[collection.Count]; collection.CopyTo(array, 0); Assert.Equal(expected, array.Select(c => c.ToString())); } [Fact] public static void CopyToNonGeneric() { string[] expected = new[] { "This ", "is ", "a ", "sentence" }; ICollection collection = CreateCollection(); Capture[] array = new Capture[collection.Count]; collection.CopyTo(array, 0); Assert.Equal(expected, array.Select(c => c.ToString())); } [Fact] public static void SyncRoot() { ICollection collection = CreateCollection(); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Fact] public static void IsNotSynchronized() { ICollection collection = CreateCollection(); Assert.False(collection.IsSynchronized); } [Fact] public void IsReadOnly() { IList<Capture> list = CreateCollection(); Assert.True(list.IsReadOnly); Assert.Throws<NotSupportedException>(() => list.Add(default(Capture))); Assert.Throws<NotSupportedException>(() => list.Clear()); Assert.Throws<NotSupportedException>(() => list.Insert(0, default(Capture))); Assert.Throws<NotSupportedException>(() => list.Remove(default(Capture))); Assert.Throws<NotSupportedException>(() => list.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => list[0] = default(Capture)); } [Fact] public static void IsReadOnlyNonGeneric() { IList list = CreateCollection(); Assert.True(list.IsReadOnly); Assert.True(list.IsFixedSize); Assert.Throws<NotSupportedException>(() => list.Add(default(Capture))); Assert.Throws<NotSupportedException>(() => list.Clear()); Assert.Throws<NotSupportedException>(() => list.Insert(0, default(Capture))); Assert.Throws<NotSupportedException>(() => list.Remove(default(Capture))); Assert.Throws<NotSupportedException>(() => list.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => list[0] = default(Capture)); } [Fact] public static void DebuggerAttributeTests() { DebuggerAttributes.ValidateDebuggerDisplayReferences(CreateCollection()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(CreateCollection()); } private static CaptureCollection CreateCollection() { Regex regex = new Regex(@"\b(\w+\s*)+\."); Match match = regex.Match("This is a sentence."); return match.Groups[1].Captures; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Material sourced from the bluePortal project (http://blueportal.codeplex.com). // Licensed under the Microsoft Public License (available at http://www.opensource.org/licenses/ms-pl.html). using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Reflection; using System.Web; using System.Web.Configuration; using System.Web.Security; using System.Web.UI; using System.Web.UI.Adapters; using System.Web.UI.WebControls; using System.Web.UI.WebControls.Adapters; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace CSSFriendly { public class WebControlAdapterExtender { private WebControl _adaptedControl = null; public WebControl AdaptedControl { get { System.Diagnostics.Debug.Assert(_adaptedControl != null, "CSS Friendly adapters internal error", "No control has been defined for the adapter extender"); return _adaptedControl; } } public bool AdapterEnabled { get { bool bReturn = true; // normally the adapters are enabled // Individual controls can use the expando property called AdapterEnabled // as a way to turn the adapters off. // <asp:TreeView runat="server" AdapterEnabled="false" /> if ((AdaptedControl != null) && (!String.IsNullOrEmpty(AdaptedControl.Attributes["AdapterEnabled"])) && (AdaptedControl.Attributes["AdapterEnabled"].IndexOf("false", StringComparison.OrdinalIgnoreCase) == 0)) { bReturn = false; } return bReturn; } } private bool _disableAutoAccessKey = false; // used when dealing with things like read-only textboxes that should not have access keys public bool AutoAccessKey { get { // Individual controls can use the expando property called AdapterEnabled // as a way to turn on/off the heurisitic for automatically setting the AccessKey // attribute in the rendered HTML. The default is shown below in the initialization // of the bReturn variable. // <asp:TreeView runat="server" AutoAccessKey="false" /> bool bReturn = true; // by default, the adapter will make access keys are available if (_disableAutoAccessKey || ((AdaptedControl != null) && (!String.IsNullOrEmpty(AdaptedControl.Attributes["AutoAccessKey"])) && (AdaptedControl.Attributes["AutoAccessKey"].IndexOf("false", StringComparison.OrdinalIgnoreCase) == 0))) { bReturn = false; } return bReturn; } } public WebControlAdapterExtender(WebControl adaptedControl) { _adaptedControl = adaptedControl; } public void RegisterScripts() { string folderPath = WebConfigurationManager.AppSettings.Get("CSSFriendly-JavaScript-Path"); if (String.IsNullOrEmpty(folderPath)) { folderPath = "~/JavaScript"; } string filePath = folderPath.EndsWith("/") ? folderPath + "AdapterUtils.js" : folderPath + "/AdapterUtils.js"; AdaptedControl.Page.ClientScript.RegisterClientScriptInclude(GetType(), GetType().ToString(), AdaptedControl.Page.ResolveUrl(filePath)); } public string ResolveUrl(string url) { string urlToResolve = url; int nPound = url.LastIndexOf("#"); int nSlash = url.LastIndexOf("/"); if ((nPound > -1) && (nSlash > -1) && ((nSlash + 1) == nPound)) { // We have been given a somewhat strange URL. It has a foreward slash (/) immediately followed // by a pound sign (#) like this xxx/#yyy. This sort of oddly shaped URL is what you get when // you use named anchors instead of pages in the url attribute of a sitemapnode in an ASP.NET // sitemap like this: // // <siteMapNode url="#Introduction" title="Introduction" description="Introduction" /> // // The intend of the sitemap author is clearly to create a link to a named anchor in the page // that looks like these: // // <a id="Introduction"></a> (XHTML 1.1 Strict compliant) // <a name="Introduction"></a> (more old fashioned but quite common in many pages) // // However, the sitemap interpretter in ASP.NET doesn't understand url values that start with // a pound. It prepends the current site's path in front of it before making it into a link // (typically for a TreeView or Menu). We'll undo that problem, however, by converting this // sort of oddly shaped URL back into what was intended: a simple reference to a named anchor // that is expected to be within the current page. urlToResolve = url.Substring(nPound); } else { urlToResolve = AdaptedControl.ResolveClientUrl(urlToResolve); } // And, just to be safe, we'll make sure there aren't any troublesome characters in whatever URL // we have decided to use at this point. string newUrl = AdaptedControl.Page.Server.HtmlEncode(urlToResolve); return newUrl; } public void RaiseAdaptedEvent(string eventName, EventArgs e) { string attr = "OnAdapted" + eventName; if ((AdaptedControl != null) && (!String.IsNullOrEmpty(AdaptedControl.Attributes[attr]))) { string delegateName = AdaptedControl.Attributes[attr]; Control methodOwner = AdaptedControl.Parent; MethodInfo method = methodOwner.GetType().GetMethod(delegateName); if (method == null) { methodOwner = AdaptedControl.Page; method = methodOwner.GetType().GetMethod(delegateName); } if (method != null) { object[] args = new object[2]; args[0] = AdaptedControl; args[1] = e; method.Invoke(methodOwner, args); } } } public void RenderBeginTag(HtmlTextWriter writer, string cssClass) { if (!String.IsNullOrEmpty(AdaptedControl.Attributes["CssSelectorClass"])) { WriteBeginDiv(writer, AdaptedControl.Attributes["CssSelectorClass"]); } WriteBeginDiv(writer, cssClass); } public void RenderEndTag(HtmlTextWriter writer) { WriteEndDiv(writer); if (!String.IsNullOrEmpty(AdaptedControl.Attributes["CssSelectorClass"])) { WriteEndDiv(writer); } } static public void RemoveProblemChildren(Control ctrl, List<ControlRestorationInfo> stashedControls) { RemoveProblemTypes(ctrl.Controls, stashedControls); } static public void RemoveProblemTypes(ControlCollection coll, List<ControlRestorationInfo> stashedControls) { foreach (Control ctrl in coll) { if (typeof(RequiredFieldValidator).IsAssignableFrom(ctrl.GetType()) || typeof(CompareValidator).IsAssignableFrom(ctrl.GetType()) || typeof(RegularExpressionValidator).IsAssignableFrom(ctrl.GetType()) || typeof(ValidationSummary).IsAssignableFrom(ctrl.GetType())) { ControlRestorationInfo cri = new ControlRestorationInfo(ctrl, coll); stashedControls.Add(cri); coll.Remove(ctrl); continue; } if (ctrl.HasControls()) { RemoveProblemTypes(ctrl.Controls, stashedControls); } } } static public void RestoreProblemChildren(List<ControlRestorationInfo> stashedControls) { foreach (ControlRestorationInfo cri in stashedControls) { cri.Restore(); } } public string MakeChildId(string postfix) { return AdaptedControl.ClientID + "_" + postfix; } static public string MakeNameFromId(string id) { string name = ""; for (int i=0; i<id.Length; i++) { char thisChar = id[i]; char prevChar = ((i - 1) > -1) ? id[i - 1] : ' '; char nextChar = ((i + 1) < id.Length) ? id[i + 1] : ' '; if (thisChar == '_') { if (prevChar == '_') { name += "_"; } else if (nextChar == '_') { name += "$_"; } else { name += "$"; } } else { name += thisChar; } } return name; } static public string MakeIdWithButtonType(string id, ButtonType type) { string idWithType = id; switch (type) { case ButtonType.Button: idWithType += "Button"; break; case ButtonType.Image: idWithType += "ImageButton"; break; case ButtonType.Link: idWithType += "LinkButton"; break; } return idWithType; } public string MakeChildName(string postfix) { return MakeNameFromId(MakeChildId(postfix)); } static public void WriteBeginDiv(HtmlTextWriter writer, string className) { writer.WriteLine(); writer.WriteBeginTag("div"); if (!String.IsNullOrEmpty(className)) { writer.WriteAttribute("class", className); } writer.Write(HtmlTextWriter.TagRightChar); writer.Indent++; } static public void WriteEndDiv(HtmlTextWriter writer) { writer.Indent--; writer.WriteLine(); writer.WriteEndTag("div"); } static public void WriteSpan(HtmlTextWriter writer, string className, string content) { if (!String.IsNullOrEmpty(content)) { writer.WriteLine(); writer.WriteBeginTag("span"); if (!String.IsNullOrEmpty(className)) { writer.WriteAttribute("class", className); } writer.Write(HtmlTextWriter.TagRightChar); writer.Write(content); writer.WriteEndTag("span"); } } static public void WriteImage(HtmlTextWriter writer, string url, string alt) { if (!String.IsNullOrEmpty(url)) { writer.WriteLine(); writer.WriteBeginTag("img"); writer.WriteAttribute("src", url); writer.WriteAttribute("alt", alt); writer.Write(HtmlTextWriter.SelfClosingTagEnd); } } static public void WriteLink(HtmlTextWriter writer, string className, string url, string title, string content) { if ((!String.IsNullOrEmpty(url)) && (!String.IsNullOrEmpty(content))) { writer.WriteLine(); writer.WriteBeginTag("a"); if (!String.IsNullOrEmpty(className)) { writer.WriteAttribute("class", className); } writer.WriteAttribute("href", url); writer.WriteAttribute("title", title); writer.Write(HtmlTextWriter.TagRightChar); writer.Write(content); writer.WriteEndTag("a"); } } // Can't be static because it uses MakeChildId public void WriteLabel(HtmlTextWriter writer, string className, string text, string forId) { if (!String.IsNullOrEmpty(text)) { writer.WriteLine(); writer.WriteBeginTag("label"); writer.WriteAttribute("for", MakeChildId(forId)); if (!String.IsNullOrEmpty(className)) { writer.WriteAttribute("class", className); } writer.Write(HtmlTextWriter.TagRightChar); if (AutoAccessKey) { writer.WriteBeginTag("em"); writer.Write(HtmlTextWriter.TagRightChar); writer.Write(text[0].ToString()); writer.WriteEndTag("em"); if (!String.IsNullOrEmpty(text)) { writer.Write(text.Substring(1)); } } else { writer.Write(text); } writer.WriteEndTag("label"); } } // Can't be static because it uses MakeChildId public void WriteTextBox(HtmlTextWriter writer, bool isPassword, string labelClassName, string labelText, string inputClassName, string id, string value) { WriteLabel(writer, labelClassName, labelText, id); writer.WriteLine(); writer.WriteBeginTag("input"); writer.WriteAttribute("type", isPassword ? "password" : "text"); if (!String.IsNullOrEmpty(inputClassName)) { writer.WriteAttribute("class", inputClassName); } writer.WriteAttribute("id", MakeChildId(id)); writer.WriteAttribute("name", MakeChildName(id)); writer.WriteAttribute("value", value); if (AutoAccessKey && (!String.IsNullOrEmpty(labelText))) { writer.WriteAttribute("accesskey", labelText[0].ToString().ToLower()); } writer.Write(HtmlTextWriter.SelfClosingTagEnd); } // Can't be static because it uses MakeChildId public void WriteReadOnlyTextBox(HtmlTextWriter writer, string labelClassName, string labelText, string inputClassName, string value) { bool oldDisableAutoAccessKey = _disableAutoAccessKey; _disableAutoAccessKey = true; WriteLabel(writer, labelClassName, labelText, ""); writer.WriteLine(); writer.WriteBeginTag("input"); writer.WriteAttribute("readonly", "true"); if (!String.IsNullOrEmpty(inputClassName)) { writer.WriteAttribute("class", inputClassName); } writer.WriteAttribute("value", value); writer.Write(HtmlTextWriter.SelfClosingTagEnd); _disableAutoAccessKey = oldDisableAutoAccessKey; } // Can't be static because it uses MakeChildId public void WriteCheckBox(HtmlTextWriter writer, string labelClassName, string labelText, string inputClassName, string id, bool isChecked) { writer.WriteLine(); writer.WriteBeginTag("input"); writer.WriteAttribute("type", "checkbox"); if (!String.IsNullOrEmpty(inputClassName)) { writer.WriteAttribute("class", inputClassName); } writer.WriteAttribute("id", MakeChildId(id)); writer.WriteAttribute("name", MakeChildName(id)); if (isChecked) { writer.WriteAttribute("checked", "checked"); } if (AutoAccessKey && (!String.IsNullOrEmpty(labelText))) { writer.WriteAttribute("accesskey", labelText[0].ToString()); } writer.Write(HtmlTextWriter.SelfClosingTagEnd); WriteLabel(writer, labelClassName, labelText, id); } // Can't be static because it uses MakeChildId public void WriteSubmit(HtmlTextWriter writer, ButtonType buttonType, string className, string id, string imageUrl, string javascript, string text) { writer.WriteLine(); string idWithType = id; switch (buttonType) { case ButtonType.Button: writer.WriteBeginTag("input"); writer.WriteAttribute("type", "submit"); writer.WriteAttribute("value", text); idWithType += "Button"; break; case ButtonType.Image: writer.WriteBeginTag("input"); writer.WriteAttribute("type", "image"); writer.WriteAttribute("src", imageUrl); idWithType += "ImageButton"; break; case ButtonType.Link: writer.WriteBeginTag("a"); idWithType += "LinkButton"; break; } if (!String.IsNullOrEmpty(className)) { writer.WriteAttribute("class", className); } writer.WriteAttribute("id", MakeChildId(idWithType)); writer.WriteAttribute("name", MakeChildName(idWithType)); if (!String.IsNullOrEmpty(javascript)) { string pureJS = javascript; if (pureJS.StartsWith("javascript:")) { pureJS = pureJS.Substring("javascript:".Length); } switch (buttonType) { case ButtonType.Button: writer.WriteAttribute("onclick", pureJS); break; case ButtonType.Image: writer.WriteAttribute("onclick", pureJS); break; case ButtonType.Link: writer.WriteAttribute("href", javascript); break; } } if (buttonType == ButtonType.Link) { writer.Write(HtmlTextWriter.TagRightChar); writer.Write(text); writer.WriteEndTag("a"); } else { writer.Write(HtmlTextWriter.SelfClosingTagEnd); } } static public void WriteRequiredFieldValidator(HtmlTextWriter writer, RequiredFieldValidator rfv, string className, string controlToValidate, string msg) { if (rfv != null) { rfv.CssClass = className; rfv.ControlToValidate = controlToValidate; rfv.ErrorMessage = msg; rfv.RenderControl(writer); } } static public void WriteRegularExpressionValidator(HtmlTextWriter writer, RegularExpressionValidator rev, string className, string controlToValidate, string msg, string expression) { if (rev != null) { rev.CssClass = className; rev.ControlToValidate = controlToValidate; rev.ErrorMessage = msg; rev.ValidationExpression = expression; rev.RenderControl(writer); } } static public void WriteCompareValidator(HtmlTextWriter writer, CompareValidator cv, string className, string controlToValidate, string msg, string controlToCompare) { if (cv != null) { cv.CssClass = className; cv.ControlToValidate = controlToValidate; cv.ErrorMessage = msg; cv.ControlToCompare = controlToCompare; cv.RenderControl(writer); } } static public void WriteTargetAttribute(HtmlTextWriter writer, string targetValue) { if ((writer != null) && (!String.IsNullOrEmpty(targetValue))) { // If the targetValue is _blank then we have an opportunity to use attributes other than "target" // which allows us to be compliant at the XHTML 1.1 Strict level. Specifically, we can use a combination // of "onclick" and "onkeypress" to achieve what we want to achieve when we used to render // target='blank'. // // If the targetValue is other than _blank then we fall back to using the "target" attribute. // This is a heuristic that can be refined over time. if (targetValue.Equals("_blank", StringComparison.OrdinalIgnoreCase)) { string js = "window.open(this.href, '_blank', ''); return false;"; writer.WriteAttribute("onclick", js); writer.WriteAttribute("onkeypress", js); } else { writer.WriteAttribute("target", targetValue); } } } } public class ControlRestorationInfo { private Control _ctrl = null; public Control Control { get { return _ctrl; } } private ControlCollection _coll = null; public ControlCollection Collection { get { return _coll; } } public bool IsValid { get { return (Control != null) && (Collection != null); } } public ControlRestorationInfo(Control ctrl, ControlCollection coll) { _ctrl = ctrl; _coll = coll; } public void Restore() { if (IsValid) { _coll.Add(_ctrl); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace NuGet.WebMatrix.DependentTests { public class MockPackageRepository : PackageRepositoryBase, ICollection<IPackage>, ILatestPackageLookup, IOperationAwareRepository, IPackageLookup { private readonly string _source; public string LastOperation { get; private set; } public string LastMainPackageId { get; private set; } public string LastMainPackageVersion { get; private set; } public MockPackageRepository() : this("") { } public MockPackageRepository(string source) { Packages = new Dictionary<string, List<IPackage>>(); _source = source; } public override string Source { get { return _source; } } public override bool SupportsPrereleasePackages { get { return true; } } internal Dictionary<string, List<IPackage>> Packages { get; set; } public override void AddPackage(IPackage package) { AddPackage(package.Id, package); } public override IQueryable<IPackage> GetPackages() { return Packages.Values.SelectMany(p => p).AsQueryable(); } public override void RemovePackage(IPackage package) { List<IPackage> packages; if (Packages.TryGetValue(package.Id, out packages)) { packages.Remove(package); } if (packages.Count == 0) { Packages.Remove(package.Id); } } private void AddPackage(string id, IPackage package) { List<IPackage> packages; if (!Packages.TryGetValue(id, out packages)) { packages = new List<IPackage>(); Packages.Add(id, packages); } packages.Add(package); } public void Add(IPackage item) { AddPackage(item); } public void Clear() { Packages.Clear(); } public bool Contains(IPackage item) { return this.Exists(item); } public void CopyTo(IPackage[] array, int arrayIndex) { throw new System.NotImplementedException(); } public int Count { get { return GetPackages().Count(); } } public bool IsReadOnly { get { return false; } } public bool Remove(IPackage item) { if (this.Exists(item)) { RemovePackage(item); return true; } return false; } public IEnumerator<IPackage> GetEnumerator() { return GetPackages().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool TryFindLatestPackageById(string id, out SemanticVersion latestVersion) { List<IPackage> packages; bool result = Packages.TryGetValue(id, out packages); if (result && packages.Count > 0) { packages.Sort((a, b) => b.Version.CompareTo(a.Version)); latestVersion = packages[0].Version; return true; } else { latestVersion = null; return false; } } public bool TryFindLatestPackageById(string id, bool includePrerelease, out IPackage package) { List<IPackage> packages; bool result = Packages.TryGetValue(id, out packages); if (result && packages.Count > 0) { // remove unlisted packages packages.RemoveAll(p => !p.IsListed()); if (!includePrerelease) { packages.RemoveAll(p => !p.IsReleaseVersion()); } if (packages.Count > 0) { packages.Sort((a, b) => b.Version.CompareTo(a.Version)); package = packages[0]; return true; } } package = null; return false; } public IDisposable StartOperation(string operation, string mainPackageId) { LastOperation = null; return new DisposableAction(() => { LastOperation = operation; }); } public bool Exists(string packageId, SemanticVersion version) { return FindPackage(packageId, version) != null; } public IPackage FindPackage(string packageId, SemanticVersion version) { List<IPackage> packages; if (Packages.TryGetValue(packageId, out packages)) { return packages.Find(p => p.Version.Equals(version)); } return null; } public IEnumerable<IPackage> FindPackagesById(string packageId) { List<IPackage> packages; if (Packages.TryGetValue(packageId, out packages)) { return packages; } return Enumerable.Empty<IPackage>(); } } }
// TypeGenerator.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Diagnostics; using System.IO; using ScriptSharp; using ScriptSharp.ScriptModel; namespace ScriptSharp.Generator { internal static class TypeGenerator { private static void GenerateClass(ScriptGenerator generator, ClassSymbol classSymbol) { ScriptTextWriter writer = generator.Writer; string name = classSymbol.FullGeneratedName; writer.Write("function "); writer.Write(name); writer.Write("("); if ((classSymbol.Constructor != null) && (classSymbol.Constructor.Parameters != null)) { bool firstParameter = true; foreach (ParameterSymbol parameterSymbol in classSymbol.Constructor.Parameters) { if (firstParameter == false) { writer.Write(", "); } writer.Write(parameterSymbol.GeneratedName); firstParameter = false; } } writer.WriteLine(") {"); writer.Indent++; if (generator.Options.EnableDocComments) { DocCommentGenerator.GenerateComment(generator, classSymbol); } foreach (MemberSymbol memberSymbol in classSymbol.Members) { if ((memberSymbol.Type == SymbolType.Field) && (memberSymbol.Visibility & MemberVisibility.Static) == 0) { FieldSymbol fieldSymbol = (FieldSymbol)memberSymbol; if (fieldSymbol.HasInitializer) { writer.Write("this."); writer.Write(fieldSymbol.GeneratedName); writer.Write(" = "); CodeGenerator.GenerateScript(generator, fieldSymbol); writer.Write(";"); writer.WriteLine(); } } } if (classSymbol.Constructor != null) { CodeGenerator.GenerateScript(generator, classSymbol.Constructor); } else if ((classSymbol.BaseClass != null) && (classSymbol.IsTestClass == false)) { writer.Write(classSymbol.BaseClass.FullGeneratedName); writer.Write(".call(this);"); writer.WriteLine(); } writer.Indent--; writer.WriteLine("}"); foreach (MemberSymbol memberSymbol in classSymbol.Members) { if ((memberSymbol.Type != SymbolType.Field) && (memberSymbol.Visibility & MemberVisibility.Static) != 0) { MemberGenerator.GenerateScript(generator, memberSymbol); } } if (classSymbol.IsStaticClass == false) { writer.Write("var "); writer.Write(name); writer.WriteLine("$ = {"); writer.Indent++; bool firstMember = true; foreach (MemberSymbol memberSymbol in classSymbol.Members) { if ((memberSymbol.Visibility & MemberVisibility.Static) == 0) { if (memberSymbol.Type == SymbolType.Field) { continue; } if ((memberSymbol is CodeMemberSymbol) && ((CodeMemberSymbol)memberSymbol).IsAbstract) { continue; } if (firstMember == false) { writer.WriteLine(","); } MemberGenerator.GenerateScript(generator, memberSymbol); firstMember = false; } } if (classSymbol.Indexer != null) { if (firstMember == false) { writer.WriteLine(","); } MemberGenerator.GenerateScript(generator, classSymbol.Indexer); } writer.Indent--; writer.WriteLine(); writer.Write("};"); writer.WriteLine(); } } private static void GenerateEnumeration(ScriptGenerator generator, EnumerationSymbol enumSymbol) { ScriptTextWriter writer = generator.Writer; string enumName = enumSymbol.FullGeneratedName; writer.Write("var "); writer.Write(enumSymbol.FullGeneratedName); writer.Write(" = {"); writer.Indent++; bool firstValue = true; foreach (MemberSymbol memberSymbol in enumSymbol.Members) { EnumerationFieldSymbol fieldSymbol = memberSymbol as EnumerationFieldSymbol; if (fieldSymbol == null) { continue; } if (firstValue == false) { writer.Write(", "); } writer.WriteLine(); writer.Write(fieldSymbol.GeneratedName); writer.Write(": "); if (enumSymbol.UseNamedValues) { writer.Write(Utility.QuoteString(enumSymbol.CreateNamedValue(fieldSymbol))); } else { writer.Write(fieldSymbol.Value); } firstValue = false; } writer.Indent--; writer.WriteLine(); writer.Write("};"); writer.WriteLine(); } private static void GenerateInterface(ScriptGenerator generator, InterfaceSymbol interfaceSymbol) { ScriptTextWriter writer = generator.Writer; string interfaceName = interfaceSymbol.FullGeneratedName; writer.Write("function "); writer.Write(interfaceName); writer.WriteLine("() { }"); } public static void GenerateClassConstructorScript(ScriptGenerator generator, ClassSymbol classSymbol) { // NOTE: This is emitted last in the script file, and separate from the initial class definition // because it needs to be emitted after the class registration. foreach (MemberSymbol memberSymbol in classSymbol.Members) { if ((memberSymbol.Type == SymbolType.Field) && ((memberSymbol.Visibility & MemberVisibility.Static) != 0)) { FieldSymbol fieldSymbol = (FieldSymbol)memberSymbol; if (fieldSymbol.IsConstant && ((memberSymbol.Visibility & (MemberVisibility.Public | MemberVisibility.Protected)) == 0)) { // PrivateInstance/Internal constant fields are omitted since they have been inlined continue; } if (fieldSymbol.HasInitializer) { MemberGenerator.GenerateScript(generator, memberSymbol); } } } if (classSymbol.StaticConstructor != null) { ScriptTextWriter writer = generator.Writer; SymbolImplementation implementation = classSymbol.StaticConstructor.Implementation; bool requiresFunctionScope = implementation.DeclaresVariables; if (requiresFunctionScope) { writer.WriteLine("(function() {"); writer.Indent++; } CodeGenerator.GenerateScript(generator, classSymbol.StaticConstructor); if (requiresFunctionScope) { writer.Indent--; writer.Write("})();"); writer.WriteLine(); } } } private static void GenerateExtensionMethods(ScriptGenerator generator, ClassSymbol classSymbol) { foreach (MemberSymbol memberSymbol in classSymbol.Members) { Debug.Assert(memberSymbol.Type == SymbolType.Method); Debug.Assert((memberSymbol.Visibility & MemberVisibility.Static) != 0); MemberGenerator.GenerateScript(generator, memberSymbol); } } private static void GenerateRecord(ScriptGenerator generator, RecordSymbol recordSymbol) { ScriptTextWriter writer = generator.Writer; string recordName = recordSymbol.FullGeneratedName; writer.Write("function "); writer.Write(recordName); writer.Write("("); if (recordSymbol.Constructor != null) { ConstructorSymbol ctorSymbol = recordSymbol.Constructor; if (ctorSymbol.Parameters != null) { bool firstParameter = true; foreach (ParameterSymbol parameterSymbol in ctorSymbol.Parameters) { if (firstParameter == false) { writer.Write(", "); } writer.Write(parameterSymbol.GeneratedName); firstParameter = false; } } } writer.Write(") {"); if (recordSymbol.Constructor != null) { writer.Indent++; writer.WriteLine(); writer.WriteLine("var $o = {};"); CodeGenerator.GenerateScript(generator, recordSymbol.Constructor); writer.Write("return $o;"); writer.WriteLine(); writer.Indent--; } else { writer.Write(" return {}; "); } writer.Write("}"); writer.WriteLine(); } public static void GenerateRegistrationScript(ScriptGenerator generator, TypeSymbol typeSymbol) { ClassSymbol classSymbol = typeSymbol as ClassSymbol; if ((classSymbol != null) && classSymbol.IsExtenderClass) { return; } ScriptTextWriter writer = generator.Writer; writer.Write(typeSymbol.GeneratedName); writer.Write(": "); switch (typeSymbol.Type) { case SymbolType.Class: writer.Write("[ "); writer.Write(typeSymbol.FullGeneratedName); writer.Write(", "); if (((ClassSymbol)typeSymbol).IsStaticClass == false) { writer.Write(typeSymbol.FullGeneratedName); writer.Write("$, "); } else { writer.Write("null, "); } if ((classSymbol.BaseClass == null) || classSymbol.IsTestClass) { // TODO: We need to introduce the notion of a base class that only exists in the metadata // and not at runtime. At that point this check of IsTestClass can be generalized. writer.Write("null"); } else { writer.Write(classSymbol.BaseClass.FullGeneratedName); } if (classSymbol.Interfaces != null) { foreach (InterfaceSymbol interfaceSymbol in classSymbol.Interfaces) { writer.Write(", "); writer.Write(interfaceSymbol.FullGeneratedName); } } writer.Write(" ]"); break; case SymbolType.Interface: writer.Write("[ "); writer.Write(typeSymbol.FullGeneratedName); writer.Write(" ]"); break; case SymbolType.Record: case SymbolType.Resources: case SymbolType.Enumeration: writer.Write(typeSymbol.FullGeneratedName); break; } } private static void GenerateResources(ScriptGenerator generator, ResourcesSymbol resourcesSymbol) { ScriptTextWriter writer = generator.Writer; string resourcesName = resourcesSymbol.FullGeneratedName; writer.Write("var "); writer.Write(resourcesName); writer.WriteLine(" = {"); writer.Indent++; bool firstValue = true; foreach (FieldSymbol member in resourcesSymbol.Members) { Debug.Assert(member.Value is string); if (firstValue == false) { writer.Write(","); writer.WriteLine(); } writer.Write(member.GeneratedName); writer.Write(": "); writer.Write(Utility.QuoteString((string)member.Value)); firstValue = false; } writer.Indent--; writer.WriteLine(); writer.Write("};"); writer.WriteLine(); } public static void GenerateScript(ScriptGenerator generator, TypeSymbol typeSymbol) { Debug.Assert(generator != null); Debug.Assert(typeSymbol != null); Debug.Assert(typeSymbol.IsApplicationType); if (typeSymbol.Type == SymbolType.Delegate) { // No-op ... there is currently nothing to generate for a particular delegate type return; } if ((typeSymbol.Type == SymbolType.Record) && (typeSymbol.IsPublic == false) && (((RecordSymbol)typeSymbol).Constructor == null)) { // Nothing to generate for internal records with no explicit ctor return; } if ((typeSymbol.Type == SymbolType.Class) && ((ClassSymbol)typeSymbol).IsModuleClass) { // No members on script modules, which only contain startup code return; } ScriptTextWriter writer = generator.Writer; writer.WriteLine("// " + typeSymbol.FullName); writer.WriteLine(); switch (typeSymbol.Type) { case SymbolType.Class: if (((ClassSymbol)typeSymbol).IsExtenderClass) { GenerateExtensionMethods(generator, (ClassSymbol)typeSymbol); } else { GenerateClass(generator, (ClassSymbol)typeSymbol); } break; case SymbolType.Interface: GenerateInterface(generator, (InterfaceSymbol)typeSymbol); break; case SymbolType.Enumeration: GenerateEnumeration(generator, (EnumerationSymbol)typeSymbol); break; case SymbolType.Record: GenerateRecord(generator, (RecordSymbol)typeSymbol); break; case SymbolType.Resources: GenerateResources(generator, (ResourcesSymbol)typeSymbol); break; } writer.WriteLine(); writer.WriteLine(); } } }
// 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.Linq.Expressions.Tests { public static class BinaryModuloTests { #region Test methods [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckByteModuloTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteModulo(array[i], array[j]); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckSByteModuloTest() { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteModulo(array[i], array[j]); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckUShortModuloTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckShortModuloTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckUIntModuloTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckIntModuloTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckULongModuloTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLongModuloTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatModuloTest(bool useInterpreter) { float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyFloatModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleModuloTest(bool useInterpreter) { double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDoubleModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalModuloTest(bool useInterpreter) { decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDecimalModulo(array[i], array[j], useInterpreter); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckCharModuloTest() { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharModulo(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteModulo(byte a, byte b) { Expression aExp = Expression.Constant(a, typeof(byte)); Expression bExp = Expression.Constant(b, typeof(byte)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifySByteModulo(sbyte a, sbyte b) { Expression aExp = Expression.Constant(a, typeof(sbyte)); Expression bExp = Expression.Constant(b, typeof(sbyte)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyUShortModulo(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Modulo( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyShortModulo(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Modulo( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyUIntModulo(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Modulo( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyIntModulo(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Modulo( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyULongModulo(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Modulo( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyLongModulo(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Modulo( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyFloatModulo(float a, float b, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Modulo( Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyDoubleModulo(double a, double b, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Modulo( Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyDecimalModulo(decimal a, decimal b, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.Modulo( Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyCharModulo(char a, char b) { Expression aExp = Expression.Constant(a, typeof(char)); Expression bExp = Expression.Constant(b, typeof(char)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.Modulo(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Modulo(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Modulo(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.Modulo(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Modulo(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e = Expression.Modulo(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a % b)", e.ToString()); } } }
//Created by Logan Apple in 2014 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; using Excel; namespace Prediction_Machine //Started 11/17/2014 { public partial class MainForm : Form { int inputcount = 0; //Created 11/19/2014 to be a count of the inputs. public MainForm() { InitializeComponent(); //UI: http://www.codeproject.com/Articles/138661/Metro-UI-Zune-like-Interface-form //Interesting idea to add: http://pastebin.com/PzhHtfMu (Added as of 11/22/2014 with some modifications) //Interesting idea to add: Dragable points (along the y-axis, not the x) for manual modification. (Added as of 11/26/2014) //Interesting idea to add: "Are you sure you want to exit?" dialog box if the chart has unsaved changes. //Interesting idea to add: http://www.codeproject.com/Tips/801032/Csharp-How-To-Read-xlsx-Excel-File-With-Lines-of //VERY interesting idea to add: Modifiers (These could operate as stopping points [where the data becomes slightly constant-ish], //general changes, etc.) in percents that begin acting within parameters -- rather, from point a to point b, where a can also //be the beginning and b the end. These modifiers would work from the settings form by it creating a label-textbox style in a panel //(within settingsform) for each. ModifyData would be a function in MainForm called by pressing a button in the settings form. Modifier //format is x1,x2,%. A user would potentially input something like 2,5,0.05 which would add 5 percent (from where each y value is //now) to the y values of 2 to 5 on the graph. Fully implemented as of 7:09 PM 11/29/2014. //Another interesting idea to add: Function creation. Have a textbox for the number of x(s) you wish to have in your function (+1 for the //final variable, the one without an x, that is), then, using its value, create that many textboxes. At the top (or bottom, outside of the //panel containing these textboxes) have a button that states: "Generate Function" which would craft a function from that information. Ex: //I wish 5 (x^4) inputs, so I enter that, then I input my values for each (a, b, c, d, and e in this scenario), and finally click the //generator button which (since it recognizes that there's 5 inputs) outputs (via a for loop for those 5 inputs) ax^4 + bx^3 + cx^2 + dx + e, //where those letters (excluding x, of course) are now my input numbers. After this, it will automatically graph said points by replacing x //with a for loop going from 0 to PredictValue (or whatever I named it). Semi-coded example: /* private void OnMakeMeAFunction_Click(object sender, EventArgs e) * { * double[] coefficients = new double[numofx]; * int i = 0; * foreach(input) * { * coefficients[i] = input.Text; * i += 1; * } * HereIsYourFunction.Text = "Function: "; * for(int x = 0; x < numofx; x++) HereIsYourFunction.Text += Convert.ToString(coefficients[x]) + "x^" + Convert.ToString(x) + " "; * * DataChart.Series[0].Points.Clear(); * for(int x = 0; x < PredictValue; x++) * { * int y = 0; * for(int x2 = 0; x2 < numofx; x2++) * { * y += coefficient[x2]*x^x2; * } * DataChart.Series[0].Points.AddXY(x, y); * } * } */ //Sets up the basic chart information: DataChart.ChartAreas[0].Axes[0].Title = "X"; DataChart.ChartAreas[0].Axes[1].Title = "Y"; DataChart.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; DataChart.Series[0].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle; DataChart.Series[0].IsVisibleInLegend = false; DataChart.MouseMove += DataChart_MouseMove; //For tooltips (and draggable points as of 11/26/2014). Added 1:04 PM 11/22/2014. Error.MouseEnter += Error_MouseEnter; //For tooltip. Added 5:21 PM 11/29/2014. Error.MouseLeave += Error_MouseLeave; //Also for tooltip. Added 5:30 PM 11/29/2014. } private void RenderData() //Created 11/17/2014 { Function.Text = ""; //Added 11/30/2014 6:12 PM to reset the function string. Error.Text = ""; //Added 11/30/2014 6:12 PM to reset the error string. for (int x = 0; x < DataChart.Series.Count; x++) { DataChart.Series[x].Points.Clear(); //Clears any points currently on the chart. if (x > 0) DataChart.Series.RemoveAt(x); } string[] inputs = new string[inputcount]; //This is the array for input data as strings to be later converted to doubles. int i = 0; //This counts the number of inputs accessed by the foreach loop. //This will render the input data and predict future data //See note in AddInput (11/19/2014 7:12 PM) //At about 6:54 PM I added in what is below (foreach loop, array, int, etc.) for looping through the input data. //Note int and array declarations were moved to the top of this function. foreach (TextBox input in InputContainer.Controls.OfType<TextBox>()) //Added 11/21/2014 { inputs[i] = (input as TextBox).Text; //Set the input's data to the corresponding place for it in the "inputs" array. i += 1; //Add 1 for each input. } //Currently, at the time of writing this (11/17/2014 7:03 PM), below is an example rendering. //At 9:08 AM 11/22/2014 that was changed to be the actual rendering loop. for (double x = 0; x < inputcount; x += 1) { DataChart.Series[0].Points.AddXY(x, inputs[(int)x]); //Note (9:11 AM 11/22/2014): After rendering the input data, the following data needs to be predicted //by calculating a function (2^x, etc.) of best fit for it. //That "if" statement to begin prediction is below. //(9:09 AM 11/26/2014) Decided to make the RenderData button doubleclick call PredictFurtherData() instead. } } private void AddInput(string name) //Created 11/19/2014 { //Below is what adds a textbox and label to the application for more inputs //Note: To graph everything, all of these inputs will have to be specified in a formula or something of the like //Note (cont.): Or a +/- % amount situation will have to be done in a foreach loop involving these inputs //Note (cont.): The first part of this note makes the most sense, however. if (name != "") { if (InputContainer.Controls.Count > 0) //If there is at least one input. { TextBox NewInput = new TextBox(); NewInput.Name = "Input" + (inputcount + 1); NewInput.Size = new System.Drawing.Size(181, 20); TextBox lasttextbox = this.Controls.Find("Input" + inputcount, true).FirstOrDefault() as TextBox; NewInput.Location = new System.Drawing.Point(lasttextbox.Location.X, lasttextbox.Location.Y + 50); NewInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; InputContainer.Controls.Add(NewInput); Label NewInputLbl = new Label(); NewInputLbl.Name = "Input" + (inputcount + 1) + "Label"; if (name.Substring(name.Length - 1) != ":") NewInputLbl.Text = name + ":"; else NewInputLbl.Text = name; NewInputLbl.Location = new System.Drawing.Point(11, NewInput.Location.Y - 20); InputContainer.Controls.Add(NewInputLbl); NewInputLbl.MouseDoubleClick += label_Click; //Added 11/22/2014 } else //If there are no inputs at the moment. { TextBox NewInput = new TextBox(); NewInput.Name = "Input" + (inputcount + 1); NewInput.Size = new System.Drawing.Size(181, 20); NewInput.Location = new System.Drawing.Point(14, 26); NewInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; InputContainer.Controls.Add(NewInput); Label NewInputLbl = new Label(); NewInputLbl.Name = "Input" + (inputcount + 1) + "Label"; if (name.Substring(name.Length - 1) != ":") NewInputLbl.Text = name + ":"; else NewInputLbl.Text = name; NewInputLbl.Location = new System.Drawing.Point(11, NewInput.Location.Y - 20); InputContainer.Controls.Add(NewInputLbl); NewInputLbl.MouseDoubleClick += label_Click; //Added 11/22/2014 } InputToAdd.Text = ""; //Clears the InputToAdd textbox text. inputcount += 1; //Adds 1 to the number of inputs. } else InputToAdd.Text = "Specify a name."; } private void AddInputButton_Click(object sender, EventArgs e) //Created 11/19/2014 { AddInput(InputToAdd.Text); //Adds an input. } private void RenderDataButton_Click(object sender, EventArgs e) //Created 11/19/2014 { RenderData(); } public void settingsToolStripMenuItem_Click(object sender, EventArgs e) //Created 11/20/2014 { Form Settings = new SettingsForm(this); //Opens the settings form for this form. Settings.Show(); } private void AlwaysTimer_Tick(object sender, EventArgs e) //Created 11/21/2014 { //This "AlwaysTimer" is to continuously call certain functions and methods since I found no other way to do so. this.BackColor = globalvariables.DefaultBackgroundColor; //What is below had to be added since I couldn't stop the buttons from inheriting MainForm's background color. AddInputButton.BackColor = Color.FromArgb(255, 255, 255); RenderDataButton.BackColor = Color.FromArgb(255, 255, 255); if (DataChart.Series[0].Points.Count <= 0) { predictToolStripMenuItem.Enabled = false; //Added 9:48 AM 11/26/2014 to check for points. loadChartAsAreaToolStripMenuItem.Enabled = false; //Added 3/15/2015 to allow for simplistic chart comparison. } else { predictToolStripMenuItem.Enabled = true; loadChartAsAreaToolStripMenuItem.Enabled = true; } if (DataChart.Series[0].Points.Count <= 3) cubicToolStripMenuItem.Enabled = false; //Added 11/27/2014 to make sure this regression is usable. else cubicToolStripMenuItem.Enabled = true; if (DataChart.Series[0].Points.Count <= 2) quadraticToolStripMenuItem.Enabled = false; //Added 11/27/2014 to make sure this regression is usable. else quadraticToolStripMenuItem.Enabled = true; if (DataChart.ChartAreas[0].AxisY.Minimum < 0) expToolStripMenuItem.Enabled = false; //Added 11/27/2014 to make sure this regression is usable. else expToolStripMenuItem.Enabled = true; if (DataChart.Series[0].Points.Count > 0) //Added 11/27/2014 to make sure this regression is usable. { if (DataChart.Series[0].Points.FindMinByValue("Y").YValues[0] <= 0) expToolStripMenuItem.Enabled = false; else expToolStripMenuItem.Enabled = true; } if (DataChart.Series.Count > 1) //Added 7:11 AM 3/15/2015 to allow the user to see the layers' names. { DataChart.Series[0].Name = this.Text; DataChart.Series[0].IsVisibleInLegend = true; } else DataChart.Series[0].IsVisibleInLegend = false; } private void newChartToolStripMenuItem_Click(object sender, EventArgs e) //Created 11/21/2014 { //This will allow for new charts to be made without overlapping series. //In fact, I'm removing the series label entirely. //Yep, I just did it right at 7:00 PM, today, 11/21/2014. Form newchart = new MainForm(); newchart.Text = "NewChart"; newchart.Show(); } //Note: This function is obsolete. private void PredictFurtherData() //Created 11/22/2014 { /* //http://www.xtremevbtalk.com/showthread.php?t=44870 (Comment added 1:13 PM 11/23/2014) //http://www.smokycogs.com/blog/maths-algorithms-in-c-sharp-linear-least-squares-fit/ (Comment added 1:13 PM 11/23/2014) //http://www.centerspace.net/blog/tag/c-exponential-regression/ (Comment added 6:24 AM 11/26/2014) //http://stackoverflow.com/questions/14523378/calculating-exponential-growth-equation-from-data-points-c-sharp (Comment added 6:27 AM 11/26/2014) //http://numerics.mathdotnet.com/docs/Regression.html (Comment added 6:28 AM 11/26/2014) [Note: THIS MIGHT BE THE MOST USEFUL.] //https://answers.yahoo.com/question/index?qid=20071210225406AAIOUlZ (For if I really wish to make this by hand.) (Comment added 6:29 AM 11/26/2014) //Calculate equation (Added 11/26/2014) int i = 0; string[] inputsy = new string[inputcount]; foreach (TextBox input in InputContainer.Controls.OfType<TextBox>()) { inputsy[i] = (input as TextBox).Text; //Set the input's data to the corresponding place for it in the "inputs" array. i += 1; //Add 1 for each input. } for (int e = 0; e < i; e++) { } */ DataChart.DataManipulator.FinancialFormula( FinancialFormula.Forecasting, "Exponential,20,false,false", "Series1:Y", "Series1:Y"); //For manual forecasting: http://forums.codeguru.com/showthread.php?461020-Forecast-function and http://support.microsoft.com/kb/828236 /*Added 6:19 AM 11/27/2014 double[] y_Values = new double[DataChart.Series[0].Points.Count]; double x_Avg = 0f; double y_Avg = 0f; double forecast = 0f; double b = 0f; double a = 0f; double X = 0f; // Forecast double tempTop = 0f; double tempBottom = 0f; // X for (int i = 0; i < DataChart.Series[0].Points.Count; i++) { x_Avg += i; } x_Avg /= DataChart.Series[0].Points.Count; // Y for (int i = 0; i < y_Values.Length; i++) { y_Values[i] = DataChart.Series[0].Points.ElementAt(i).YValues[0]; y_Avg += y_Values[i]; } y_Avg /= y_Values.Length; for (int i = 0; i < y_Values.Length; i++) { tempTop += (i - x_Avg) * (y_Values[i] - y_Avg); tempBottom += Math.Pow(((i - x_Avg)), 2f); b = tempTop / tempBottom; a = y_Avg - b * x_Avg; X = 30f; forecast = a + b * X; DataChart.Series[0].Points.AddXY(i, forecast); } */ } private void saveToolStripMenuItem_Click(object sender, EventArgs e) //Created 11/22/2014 9:31 AM { RenderData(); //To make sure all points are there. Function.Text = ""; Error.Text = ""; int i = 0; //This counts the number of inputs accessed by the foreach loop. int l = 0; //This counts the number of labels accessed by the foreach loop. string[] inputs = new string[inputcount]; //This is the array (a local copy) for input data as strings to be later converted to doubles. string[] labels = new string[inputcount]; //This is the array for the label names. string[] datatosave = new string[DataChart.Series[0].Points.Count]; //The "input data to be saved" array declaration. string[] settingstosave = new string[3]; //Added 11/27/2014 to save settings. settingstosave[0] = DataChart.ChartAreas[0].Axes[0].Title; settingstosave[1] = DataChart.ChartAreas[0].Axes[1].Title; settingstosave[2] = Convert.ToString(globalvariables.ToPredict); foreach (Label label in InputContainer.Controls.OfType<Label>()) { labels[l] = (label as Label).Text; //Set the labels's data to the corresponding place for it in the "labels" array. l += 1; //Add 1 for each input. } foreach (TextBox input in InputContainer.Controls.OfType<TextBox>()) { inputs[i] = (input as TextBox).Text; //Set the input's data to the corresponding place for it in the "inputs" array. if ((input as TextBox).Text == null || (input as TextBox).Text == "") (input as TextBox).Text = "0"; datatosave[(int)i] = labels[i] + "_" + Convert.ToString(i) + "_" + (input as TextBox).Text; //Add the input to the "datatosave" array. //Note (10:28 AM 11/22/2014): A ": " isn't added to the labels[i] as it already exists in the label string. //Note (10:36 AM 11/22/2014): I added in underscores to separate the information in each line. i += 1; //Add 1 for each input. } System.IO.File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory + this.Text + ".chart", datatosave); //Save the chart. System.IO.File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory + this.Text + ".settings", settingstosave); //Save the settings. } private void loadToolStripMenuItem_Click(object sender, EventArgs e) //Created 11/22/2014 9:31 AM { OpenFileDialog ChartLoader = new OpenFileDialog(); // Creates an instance of the chart loader. //Until the next comment, this sets the basic information for ChartLoader. ChartLoader.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; ChartLoader.Filter = "Chart Files (.chart)|*.chart"; ChartLoader.Multiselect = false; ChartLoader.FilterIndex = 1; DialogResult result = ChartLoader.ShowDialog(); if (result == DialogResult.OK) //Added 4:56 PM 11/23/2014 to account for if the user cancels loading a new file. { for (int x = 0; x < DataChart.Series.Count; x++) { DataChart.Series[x].Points.Clear(); //Clears any points currently on the chart. if (x > 0) DataChart.Series.RemoveAt(x); } Function.Text = ""; Error.Text = ""; for (int i = InputContainer.Controls.Count - 1; i >= 0; i--) //Remove all labels and textboxes (iterates through them backwards). { if (InputContainer.Controls[i] is Label || InputContainer.Controls[i] is TextBox) { InputContainer.Controls.Remove(InputContainer.Controls[i]); } } inputcount = 0; //Added 11/26/2014 to reset the number of inputs. //The data points are loaded. string[] lines = System.IO.File.ReadAllLines(ChartLoader.FileName); //Array for lines in the .chart file. char[] DelimiterChars = { '_' }; //Delimeters. foreach (string line in lines) { string[] perline = new string[3]; //Per line information. perline = line.Split(DelimiterChars); //Splits at "_". AddInput(perline[0]); //Adds an input for the current line. if (perline[2] == null || perline[2] == "") DataChart.Series[0].Points.AddXY(Convert.ToDouble(perline[1]), 0); //In case the y-value is null. else DataChart.Series[0].Points.AddXY(Convert.ToDouble(perline[1]), Convert.ToDouble(perline[2])); TextBox settext = InputContainer.Controls.Find("Input" + inputcount, true).FirstOrDefault() as TextBox; settext.Text = perline[2]; //Set the text of the textbox to the y-value of the point it refers to. } this.Text = System.IO.Path.GetFileName(ChartLoader.FileName).Replace(".chart", ""); //Added 8:16 AM 11/23/2014 //What is below was added at 10:29 AM on the 27th day of this year, 2014, in the 11th month of said year. string settingsfile = System.IO.Path.GetFileName(ChartLoader.FileName).Replace(".chart", ".settings"); if (System.IO.File.Exists(settingsfile)) { string[] lines2 = System.IO.File.ReadAllLines(settingsfile); DataChart.ChartAreas[0].Axes[0].Title = lines2[0]; DataChart.ChartAreas[0].Axes[1].Title = lines2[1]; globalvariables.ToPredict = Convert.ToInt32(lines2[2]); } } } private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) //Created 11/22/2014 9:31 AM { DataChart.SaveImage(AppDomain.CurrentDomain.BaseDirectory + this.Text + ".png", System.Drawing.Imaging.ImageFormat.Png); //Below is what opens the folder to show you the resulting image. System.Diagnostics.Process prc = new System.Diagnostics.Process(); prc.StartInfo.FileName = Environment.GetEnvironmentVariable("WINDIR") + @"\explorer.exe"; prc.StartInfo.Arguments = AppDomain.CurrentDomain.BaseDirectory; prc.Start(); } Point? prevPosition = null; //Sets the previous position to null. ToolTip tooltip = new ToolTip(); //Creates a new instance of the tooltip. void DataChart_MouseMove(object sender, MouseEventArgs e) //Created 11/22/2014 1:05 PM { var pos = e.Location; //Gets the mouse position and puts it into a variable. if (prevPosition.HasValue && pos == prevPosition.Value) return; tooltip.RemoveAll(); //Removes all tooltips. prevPosition = pos; //What is below (next 7 lines) was added at 7:07 AM 11/26/2014 to get a more specific mouse pos location DataChart.ChartAreas[0].CursorX.Interval = 0.1; DataChart.ChartAreas[0].CursorY.Interval = 0.1; DataChart.ChartAreas[0].CursorX.SetCursorPixelPosition(new Point(e.X, e.Y), true); DataChart.ChartAreas[0].CursorY.SetCursorPixelPosition(new Point(e.X, e.Y), true); double pX = DataChart.ChartAreas[0].CursorX.Position; //X Axis Coordinate of mouse double pY = DataChart.ChartAreas[0].CursorY.Position; //Y Axis Coordinate of mouse MousePos.Text = "(" + Convert.ToString(pX) + ", " + Convert.ToString(pY) + ")"; var results = DataChart.HitTest(pos.X, pos.Y, false, ChartElementType.DataPoint); foreach (var result in results) { if (result.ChartElementType == ChartElementType.DataPoint) { var point = result.Object as DataPoint; if (point != null) { double pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(point.XValue); double pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(point.YValues[0]); //This checks as to whether or not the cursor is close to the point by about 15 pixels if (Math.Abs(pos.X - pointXPixel) < 15 && Math.Abs(pos.Y - pointYPixel) < 15) { tooltip.Show("X=" + point.XValue + ", Y=" + point.YValues[0], this.DataChart, pos.X, pos.Y - 15); if (e.Button == MouseButtons.Left) //For draggable points. Added 11/26/2014. { double[] newpoints = new double[2] { pY, point.XValue }; //Array for the new x and y points for the modified point. DataChart.Series[0].Points.ElementAt(Convert.ToInt32(point.XValue)).YValues = newpoints; //Sets the point to the new coordinates. DataChart.Refresh(); //Refreshes and updates the Chart. if (DataChart.Series[0].Points.Count == inputcount) { TextBox textboxtomodify = InputContainer.Controls.Find("Input" + (point.XValue + 1), true).FirstOrDefault() as TextBox; //Finds the input for the changing point. textboxtomodify.Text = Convert.ToString(pY); //Changes the input of the point being changed. } } if (e.Button == MouseButtons.Right) //Added 7:38 3/15/2015 to allow the user to label specific points on the chart. { DataChart.Series[0].Points.ElementAt(Convert.ToInt32(pX)).Label = InputContainer.Controls.Find("Input" + (point.XValue + 1), true).FirstOrDefault().Text; DataChart.Refresh(); } } } } } } private void label_Click(object sender, MouseEventArgs e) //Created 6:27 PM 11/22/2014 { Label clickedLabel = sender as Label; if (e.Button == System.Windows.Forms.MouseButtons.Left) { if (clickedLabel != null) { string currenttext = clickedLabel.Text; //Set a string variable to the current text of the clicked label if (InputToAdd.Text != "") { if (currenttext.Substring(currenttext.Length) != ":") clickedLabel.Text = InputToAdd.Text + ":"; else clickedLabel.Text = InputToAdd.Text; //If there's a colon, just set the text to what's in the InputToAdd textbox InputToAdd.Text = ""; //Empty the textbox } } } else if (e.Button == System.Windows.Forms.MouseButtons.Middle) //Added 11/27/2014 to allow for input removal. { TextBox toremove = InputContainer.Controls.Find(clickedLabel.Name.Replace("Label", ""), true).FirstOrDefault() as TextBox; InputContainer.Controls.Remove(toremove); //Remove the textbox that goes with the label. InputContainer.Controls.Remove(clickedLabel); //Then remove the label itself. inputcount -= 1; //Subtract one from the inputcount since there's one less input. for (int i = InputContainer.Controls.Count - 1; i >= 0; i--) //Rename all labels and textboxes (iterates through them backwards). { if (InputContainer.Controls[i] is Label) InputContainer.Controls[i].Name = "Input" + i/2 + "Label"; else if (InputContainer.Controls[i] is TextBox) InputContainer.Controls[i].Name = "Input" + i/2; } } } private void savePredictToolStripMenuItem_Click(object sender, EventArgs e) //Created 9:56 AM 11/26/2014 { Function.Text = ""; Error.Text = ""; int p = 0; //This counts the number of points accessed by the foreach loop. string[] datatosave = new string[DataChart.Series[0].Points.Count]; //The "input data to be saved" array declaration. foreach (DataPoint point in DataChart.Series[0].Points) { datatosave[(int)p] = "PredictPoint" + p + "_" + Convert.ToString(p) + "_" + DataChart.Series[0].Points.ElementAt(p).YValues[0]; //Add the input to the "datatosave" array. p += 1; //Add 1 for each point. } System.IO.File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory + this.Text + "_Prediction.chart", datatosave); //Save the chart. RenderData(); } private void generateStatsToolStripMenuItem_Click(object sender, EventArgs e) //Added 11/26/2014 for statistical generation. { double averagerate = 0; //Variable for average rate. //Until after the "calculate r" comment, this was added 11/29/2014 to calculate r (Correlation Coefficient). int n = DataChart.Series[0].Points.Count; double sumxy = 0; double sumx = 0; double sumy = 0; double sumx2 = 0; double sumy2 = 0; for(int x = 0; x < DataChart.Series[0].Points.Count; x++) { sumxy = sumxy + (x*DataChart.Series[0].Points.ElementAt(x).YValues[0]); sumx = sumx + x; sumy = sumy + DataChart.Series[0].Points.ElementAt(x).YValues[0]; sumx2 = sumx2 + (x*x); sumy2 = sumy2 + (DataChart.Series[0].Points.ElementAt(x).YValues[0]*DataChart.Series[0].Points.ElementAt(x).YValues[0]); //Except for this. This was added on 12/24/2014 at 12:15 PM to get the average rate of change for the graph. if (x + 1 < DataChart.Series[0].Points.Count) averagerate += ((DataChart.Series[0].Points.ElementAt(x + 1).YValues[0] - DataChart.Series[0].Points.ElementAt(x).YValues[0]) / ((x + 1) - (x))); } double r = (n*sumxy - (sumx*sumy))/(Math.Sqrt((n*sumx2)-((sumx)*(sumx)))*Math.Sqrt((n*sumy2)-((sumy)*(sumy)))); //Calculate "r". averagerate /= DataChart.Series[0].Points.Count; //This is then the rates added together and then divided by the number of points, ergo rates. string[] datatosave = new string[7]; //Adds an array of the number of stats that will be saved. datatosave[0] = "Mean: " + Convert.ToString(DataChart.DataManipulator.Statistics.Mean("Series1")); datatosave[1] = "Variance: " + Convert.ToString(DataChart.DataManipulator.Statistics.Variance("Series1", false)); datatosave[2] = "Median: " + Convert.ToString(DataChart.DataManipulator.Statistics.Median("Series1")); datatosave[3] = "r: " + r; datatosave[4] = "r^2: " + (r*r); datatosave[5] = "Rate between the first and final points: " + Convert.ToString((DataChart.Series[0].Points.ElementAt(DataChart.Series[0].Points.Count - 1).YValues[0] - DataChart.Series[0].Points.ElementAt(0).YValues[0]) / (DataChart.Series[0].Points.Count - 1)); //Added 6:48 PM 11/30/2014 to calculate the rate of change (slope). datatosave[6] = "Average rate of the graph: " + Convert.ToString(averagerate); System.IO.File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory + this.Text + "_Statistics.txt", datatosave); } private void InputToAdd_KeyDown(object sender, KeyEventArgs e) //Added 11/27/2014 for ease of adding inputs { if (e.KeyValue == 13) AddInput(InputToAdd.Text); } private void expToolStripMenuItem_Click(object sender, EventArgs e) //Added 11/27/2014 for more regression options { TextBox toget = this.Controls.Find("Input1", true).FirstOrDefault() as TextBox; double originalpoint = Convert.ToDouble(toget.Text); //For later comparison. Added 11/29/2014. DataChart.DataManipulator.FinancialFormula( FinancialFormula.Forecasting, "Exponential," + globalvariables.ToPredict + ",false,false", DataChart.Series[0].Name + ":Y", DataChart.Series[0].Name + ":Y"); //What is below was added 11/28/2014 for displaying the function. double a = DataChart.Series[0].Points.ElementAt(0).YValues[0]; double thirdvalue = DataChart.Series[0].Points.ElementAt(3).YValues[0]; double b = Math.Sqrt(thirdvalue / a); Function.Text = "Function: " + a + "(" + b + ")^x"; Error.Text = "Difference: " + Convert.ToString(100 - ((originalpoint / a) * 100)) + "%"; //Added to calculate the approximate difference between the original and predicted graphs. } private void quadraticToolStripMenuItem_Click(object sender, EventArgs e) //Added 11/27/2014 for more regression options { TextBox toget = this.Controls.Find("Input1", true).FirstOrDefault() as TextBox; double originalpoint = Convert.ToDouble(toget.Text); //For later comparison. Added 11/29/2014. DataChart.DataManipulator.FinancialFormula( FinancialFormula.Forecasting, "3," + globalvariables.ToPredict + ",false,false", DataChart.Series[0].Name + ":Y", DataChart.Series[0].Name + ":Y"); //What is below was added 11/28/2014 for displaying the function. double y1 = DataChart.Series[0].Points.ElementAt(0).YValues[0] - DataChart.Series[0].Points.ElementAt(1).YValues[0]; double y2 = DataChart.Series[0].Points.ElementAt(2).YValues[0] - DataChart.Series[0].Points.ElementAt(1).YValues[0]; //At 0: c //At 1: a + b + c //At 2: 4a + 2b + c //4a + 2b + c - a - b - c = y2 //3a + b = y2 //c - a - b - c = y1 //-a - b = y1 //a = (-y1 - b) //b = (-y1 - a) //3a - y1 - a = y2 //2a = y2 + y1 //-3y1 - 2b = y2 //-2b = y2 + 3y1 //b = (y2 + 3y1) / -2 double a = (y2 + y1) / 2; double b = (y2 + (3 * y1)) / -2; double c = DataChart.Series[0].Points.ElementAt(0).YValues[0]; Function.Text = "Function: " + a + "x^2 + " + b + "x + " + c; Error.Text = "Difference: " + Convert.ToString(100 - ((originalpoint / c) * 100)) + "%"; //Added to calculate the approximate difference between the original and predicted graphs. } private void cubicToolStripMenuItem_Click(object sender, EventArgs e) //Added 11/27/2014 for more regression options { TextBox toget = this.Controls.Find("Input1", true).FirstOrDefault() as TextBox; double originalpoint = Convert.ToDouble(toget.Text); //For later comparison. Added 11/29/2014. DataChart.DataManipulator.FinancialFormula( FinancialFormula.Forecasting, "4," + globalvariables.ToPredict + ",false,false", DataChart.Series[0].Name + ":Y", DataChart.Series[0].Name + ":Y"); //http://math.stackexchange.com/questions/168855/given-four-points-on-a-cubic-function-curve-how-can-i-find-the-curves-function //What is below was added 11/29/2014 for displaying the function. double y1 = DataChart.Series[0].Points.ElementAt(2).YValues[0] - DataChart.Series[0].Points.ElementAt(1).YValues[0]; double y2 = DataChart.Series[0].Points.ElementAt(3).YValues[0] - DataChart.Series[0].Points.ElementAt(2).YValues[0]; double y3 = DataChart.Series[0].Points.ElementAt(4).YValues[0] - DataChart.Series[0].Points.ElementAt(3).YValues[0]; //At 1: a + b + c + d //At 2: 8a + 4b + 2c + d //At 3: 27a + 9b + 3c + d //At 4: 64a + 16b + 4c + d //8a + 4b + 2c + d - a - b - c - d //7a + 3b + c = y1 //27a + 9b + 3c + d - 8a - 4b - 2c - d //19a + 5b + c = y2 //64a + 16b + 4c + d - 27a - 9b - 3c - d //37a + 7b + c = y3 //19a + 5b + c - 7a - 3b - c //12a + 2b = (y2 - y1) //a (to plug in) = ((y2 - y1) - 2b) / 12 //b (to plug in) = ((y2 - y1)) - 12a) / 2 //37a + 7b + c - 19a - 5b - c //18a + 2b = (y3 - y2) //a = ((y3 - y2) - 2b) / 18 //b = ((y3 - y2) - 18a) / 2 //Subtract one from the other: (for a) //18a + 2b - 12a - 2b = (y3 - y2) - (y2 - y1) //6a = (y3 - y2) - (y2 - y1) //a = ((y3 - y2) - (y2 - y1)) / 6 //OR use the prior method -- that is, plugging it in: (for a) //18a + (y2 - y1) - 12a = (y3 - y2) //6a = ((y3 - y2) - (y2 - y1)) //a = ((y3 - y2) - (y2 - y1)) / 6 //Subtract one from the other: (for b) [This obviously doesn't work.] //18a + 2b - 12a - 2b = (y3 - y2) - (y2 - y1) //0 = ((y3 - y2) - (y2 - y1)) / 6a //OR (rather I have to) use the prior method -- that is, plugging it in: (for b) //18(((y2 - y1) - 2b) / 12) + 2b = (y3 - y2) //-3b - (3y1)/2 + (3y2)/2 + 2b = (y3 - y2) //-b - (3y1)/2 + (3y2)/2 = (y3 - y2) //-b = (y3 - y2) + (3y1)/2 - (3y2)/2 //b = ((y3 - y2) + (3y1)/2 - (3y2)/2) / -1 //For c, just plug in the variables: //7a + 3b + c = y1 //c = y1 - 7a - 3b double a = ((y3 - y2) - (y2 - y1)) / 6; double b = ((y3 - y2) + (3*y1)/2 - (3*y2)/2) / -1; double c = y1 - 7*a - 3*b; double d = DataChart.Series[0].Points.ElementAt(0).YValues[0]; //Logically, this would also work: double c = DataChart.Series[0].Points.ElementAt(1).YValues[0] - a - b - d; Function.Text = "Function: " + Math.Round(a, 10) + "x^3 + " + Math.Round(b, 10) + "x^2 + " + Math.Round(c, 10) + "x + " + Math.Round(d, 10); Error.Text = "Difference: " + Convert.ToString(100 - ((originalpoint / d) * 100)) + "%"; //Added to calculate the approximate difference between the original and predicted graphs. } private void linearToolStripMenuItem_Click(object sender, EventArgs e) //Added 11/27/2014 for more regression options { TextBox toget = this.Controls.Find("Input1", true).FirstOrDefault() as TextBox; double originalpoint = Convert.ToDouble(toget.Text); //For later comparison. Added 11/29/2014. DataChart.DataManipulator.FinancialFormula( FinancialFormula.Forecasting, "2,"+ globalvariables.ToPredict + ",false,false", DataChart.Series[0].Name + ":Y", DataChart.Series[0].Name + ":Y"); //What is below was added 11/28/2014 for displaying the function. double b = DataChart.Series[0].Points.ElementAt(0).YValues[0]; double a = DataChart.Series[0].Points.ElementAt(1).YValues[0] - b; Function.Text = "Function: " + a + "x + " + b; Error.Text = "Difference: " + Convert.ToString(100 - ((originalpoint / b) * 100)) + "%"; //Added to calculate the approximate difference between the original and predicted graphs. } private void loadSpreadsheetToolStripMenuItem_Click(object sender, EventArgs e) //Added 9:49 AM 11/28/2014 to load Excel spreadsheets { OpenFileDialog SpreadLoader = new OpenFileDialog(); // Creates an instance of the spreadsheet loader. SpreadLoader.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; SpreadLoader.Filter = "Excel Spreadsheets (.xlsx)|*.xlsx"; SpreadLoader.Multiselect = false; SpreadLoader.FilterIndex = 1; DialogResult result = SpreadLoader.ShowDialog(); if (result == DialogResult.OK) { Function.Text = ""; Error.Text = ""; DataChart.Series[0].Points.Clear(); //Clears any points currently on the chart. for (int i = InputContainer.Controls.Count - 1; i >= 0; i--) //Remove all labels and textboxes (iterates through them backwards). { if (InputContainer.Controls[i] is Label || InputContainer.Controls[i] is TextBox) { InputContainer.Controls.Remove(InputContainer.Controls[i]); } } inputcount = 0; //Added 11/26/2014 to reset the number of inputs. int cellcount = 0; //The data points are loaded. if (Workbook.Worksheets(SpreadLoader.FileName) != null) { foreach (var spreadsheet in Workbook.Worksheets(SpreadLoader.FileName)) //For every worksheet, create a new chart. { MainForm newchart = new MainForm(); newchart.Show(); cellcount = 0; foreach (var row in spreadsheet.Rows) foreach (var cell in row.Cells) if (cell != null && cell.ColumnIndex == 0) newchart.AddInput(Convert.ToString(cell.Text)); else if (cell != null && cell.ColumnIndex == 1) { cellcount += 1; TextBox textboxtoset = newchart.Controls.Find("Input" + cellcount, true).FirstOrDefault() as TextBox; if (textboxtoset != null) textboxtoset.Text = Convert.ToString(cell.Text); } newchart.Text = System.IO.Path.GetFileName(SpreadLoader.FileName).Replace(".xlsx", ""); //Added 8:16 AM 11/23/2014 } } } } private void Formula_MouseDoubleClick(object sender, MouseEventArgs e) //Added 11/28/2014 for copying functions { if (e.Button == System.Windows.Forms.MouseButtons.Left) { System.Windows.Clipboard.SetText(Function.Text); } } ToolTip errorhover = new ToolTip(); private void Error_MouseEnter(object sender, EventArgs e) //Created 11/29/2014 { errorhover.Show("This is the difference between the original y-value at 0 and the current one.", this, Error.Location.X, Error.Location.Y); } private void Error_MouseLeave(object sender, EventArgs e) //Created 11/29/2014 { errorhover.Hide(this); } public void ModifyData(int x1, int x2, double mod) //Created 11/29/2014 { for(int x = x1; x < x2; x++) //The magic. (AKA: looping from x1 to x2 and shifting the data accordingly.) { if (x2 > DataChart.Series[0].Points.Count) x2 = DataChart.Series[0].Points.Count; //If x2 is greater than the number of points, change it to the number of points. if (x1 < 0) x1 = 0; //If x1 is less than 0, set it to 0. if (x1 < DataChart.Series[0].Points.Count && x1 >= 0) //If x1 is within 0 to Number of Points then do do the magic! { DataChart.Series[0].Points.ElementAt(x).YValues[0] = DataChart.Series[0].Points.ElementAt(x).YValues[0] + (DataChart.Series[0].Points.ElementAt(x).YValues[0] * mod); DataChart.Refresh(); if (x <= inputcount && DataChart.Series[0].Points.Count <= inputcount) //If we are using the original chart, modify the inputs to match the updated points. { TextBox settext = this.Controls.Find("Input" + x, true).FirstOrDefault() as TextBox; settext.Text = Convert.ToString(DataChart.Series[0].Points.ElementAt(x).YValues[0] + (DataChart.Series[0].Points.ElementAt(x).YValues[0] * mod)); } } } } private void loadChartAsAreaToolStripMenuItem_Click(object sender, EventArgs e) //Added 3/15/2015 to allow for simplistic chart comparison. { OpenFileDialog ChartLoader = new OpenFileDialog(); // Creates an instance of the chart loader. //Until the next comment, this sets the basic information for ChartLoader. ChartLoader.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; ChartLoader.Filter = "Chart Files (.chart)|*.chart"; ChartLoader.Multiselect = false; ChartLoader.FilterIndex = 1; DialogResult result = ChartLoader.ShowDialog(); if (result == DialogResult.OK) { string layer = System.IO.Path.GetFileName(ChartLoader.FileName).Replace(".chart", ""); if (DataChart.Series.IndexOf(layer) == -1) DataChart.Series.Add(layer); else Error.Text = "That series of data already exists in the chart."; DataChart.Series[layer].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; DataChart.Series[layer].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle; DataChart.Series[layer].IsVisibleInLegend = true; //The data points are loaded. string[] lines = System.IO.File.ReadAllLines(ChartLoader.FileName); //Array for lines in the .chart file. char[] DelimiterChars = { '_' }; //Delimeters. foreach (string line in lines) { string[] perline = new string[3]; //Per line information. perline = line.Split(DelimiterChars); //Splits at "_". if (perline[2] == null || perline[2] == "") DataChart.Series[layer].Points.AddXY(Convert.ToDouble(perline[1]), 0); //In case the y-value is null. else DataChart.Series[layer].Points.AddXY(Convert.ToDouble(perline[1]), Convert.ToDouble(perline[2])); } } } } public class globalvariables //Created 11/20/2014 6:18 PM [Moved from class MainForm to namespace at 6:22 PM] { public static Color DefaultBackgroundColor = Color.FromArgb(255, 255, 255); public static int ToPredict = 20; //Added 11/28/2014 } }
//------------------------------------------------------------------------------ // <copyright file="PerformanceCounter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Diagnostics { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Collections; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Threading; /// <devdoc> /// Performance Counter component. /// This class provides support for NT Performance counters. /// It handles both the existing counters (accesible by Perf Registry Interface) /// and user defined (extensible) counters. /// This class is a part of a larger framework, that includes the perf dll object and /// perf service. /// </devdoc> [ InstallerType("System.Diagnostics.PerformanceCounterInstaller," + AssemblyRef.SystemConfigurationInstall), SRDescription(SR.PerformanceCounterDesc), HostProtection(Synchronization = true, SharedState = true) ] public sealed class PerformanceCounter : Component, ISupportInitialize { private string machineName; private string categoryName; private string counterName; private string instanceName; private PerformanceCounterInstanceLifetime instanceLifetime = PerformanceCounterInstanceLifetime.Global; private bool isReadOnly; private bool initialized = false; private string helpMsg = null; private int counterType = -1; // Cached old sample private CounterSample oldSample = CounterSample.Empty; // Cached IP Shared Performanco counter private SharedPerformanceCounter sharedCounter; [Obsolete("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")] public static int DefaultFileMappingSize = 524288; private Object m_InstanceLockObject; private Object InstanceLockObject { get { if (m_InstanceLockObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref m_InstanceLockObject, o, null); } return m_InstanceLockObject; } } /// <devdoc> /// The defaut constructor. Creates the perf counter object /// </devdoc> public PerformanceCounter() { machineName = "."; categoryName = String.Empty; counterName = String.Empty; instanceName = String.Empty; this.isReadOnly = true; GC.SuppressFinalize(this); } /// <devdoc> /// Creates the Performance Counter Object /// </devdoc> public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) { this.MachineName = machineName; this.CategoryName = categoryName; this.CounterName = counterName; this.InstanceName = instanceName; this.isReadOnly = true; Initialize(); GC.SuppressFinalize(this); } internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit) { this.MachineName = machineName; this.CategoryName = categoryName; this.CounterName = counterName; this.InstanceName = instanceName; this.isReadOnly = true; this.initialized = true; GC.SuppressFinalize(this); } /// <devdoc> /// Creates the Performance Counter Object on local machine. /// </devdoc> public PerformanceCounter(string categoryName, string counterName, string instanceName) : this(categoryName, counterName, instanceName, true) { } /// <devdoc> /// Creates the Performance Counter Object on local machine. /// </devdoc> public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) { if(!readOnly) { VerifyWriteableCounterAllowed(); } this.MachineName = "."; this.CategoryName = categoryName; this.CounterName = counterName; this.InstanceName = instanceName; this.isReadOnly = readOnly; Initialize(); GC.SuppressFinalize(this); } /// <devdoc> /// Creates the Performance Counter Object, assumes that it's a single instance /// </devdoc> public PerformanceCounter(string categoryName, string counterName) : this(categoryName, counterName, true) { } /// <devdoc> /// Creates the Performance Counter Object, assumes that it's a single instance /// </devdoc> public PerformanceCounter(string categoryName, string counterName, bool readOnly) : this(categoryName, counterName, "", readOnly) { } /// <devdoc> /// Returns the performance category name for this performance counter /// </devdoc> [ ReadOnly(true), DefaultValue(""), TypeConverter("System.Diagnostics.Design.CategoryValueConverter, " + AssemblyRef.SystemDesign), SRDescription(SR.PCCategoryName), SettingsBindable(true) ] public string CategoryName { get { return categoryName; } set { if (value == null) throw new ArgumentNullException("value"); if (categoryName == null || String.Compare(categoryName, value, StringComparison.OrdinalIgnoreCase) != 0) { categoryName = value; Close(); } } } /// <devdoc> /// Returns the description message for this performance counter /// </devdoc> [ ReadOnly(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.PC_CounterHelp) ] public string CounterHelp { get { string currentCategoryName = categoryName; string currentMachineName = machineName; PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); Initialize(); if (helpMsg == null) helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, this.counterName); return helpMsg; } } /// <devdoc> /// Sets/returns the performance counter name for this performance counter /// </devdoc> [ ReadOnly(true), DefaultValue(""), TypeConverter("System.Diagnostics.Design.CounterNameConverter, " + AssemblyRef.SystemDesign), SRDescription(SR.PCCounterName), SettingsBindable(true) ] public string CounterName { get { return counterName; } set { if (value == null) throw new ArgumentNullException("value"); if (counterName == null || String.Compare(counterName, value, StringComparison.OrdinalIgnoreCase) != 0) { counterName = value; Close(); } } } /// <devdoc> /// Sets/Returns the counter type for this performance counter /// </devdoc> [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.PC_CounterType) ] public PerformanceCounterType CounterType { get { if (counterType == -1) { string currentCategoryName = categoryName; string currentMachineName = machineName; // This is the same thing that NextSample does, except that it doesn't try to get the actual counter // value. If we wanted the counter value, we would need to have an instance name. PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); Initialize(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName); CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(this.counterName); this.counterType = counterSample.CounterType; } return(PerformanceCounterType) counterType; } } [ DefaultValue(PerformanceCounterInstanceLifetime.Global), SRDescription(SR.PCInstanceLifetime), ] public PerformanceCounterInstanceLifetime InstanceLifetime { get { return instanceLifetime; } set { if (value > PerformanceCounterInstanceLifetime.Process || value < PerformanceCounterInstanceLifetime.Global) throw new ArgumentOutOfRangeException("value"); if (initialized) throw new InvalidOperationException(SR.GetString(SR.CantSetLifetimeAfterInitialized)); instanceLifetime = value; } } /// <devdoc> /// Sets/returns an instance name for this performance counter /// </devdoc> [ ReadOnly(true), DefaultValue(""), TypeConverter("System.Diagnostics.Design.InstanceNameConverter, " + AssemblyRef.SystemDesign), SRDescription(SR.PCInstanceName), SettingsBindable(true) ] public string InstanceName { get { return instanceName; } set { if (value == null && instanceName == null) return; if ((value == null && instanceName != null) || (value != null && instanceName == null) || String.Compare(instanceName, value, StringComparison.OrdinalIgnoreCase) != 0) { instanceName = value; Close(); } } } /// <devdoc> /// Returns true if counter is read only (system counter, foreign extensible counter or remote counter) /// </devdoc> [ Browsable(false), DefaultValue(true), MonitoringDescription(SR.PC_ReadOnly) ] public bool ReadOnly { get { return isReadOnly; } set { if (value != this.isReadOnly) { if(value == false) { VerifyWriteableCounterAllowed(); } this.isReadOnly = value; Close(); } } } /// <devdoc> /// Set/returns the machine name for this performance counter /// </devdoc> [ Browsable(false), DefaultValue("."), SRDescription(SR.PCMachineName), SettingsBindable(true) ] public string MachineName { get { return machineName; } set { if (!SyntaxCheck.CheckMachineName(value)) throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", value)); if (machineName != value) { machineName = value; Close(); } } } /// <devdoc> /// Directly accesses the raw value of this counter. If counter type is of a 32-bit size, it will truncate /// the value given to 32 bits. This can be significantly more performant for scenarios where /// the raw value is sufficient. Note that this only works for custom counters created using /// this component, non-custom counters will throw an exception if this property is accessed. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.PC_RawValue) ] public long RawValue { get { if (ReadOnly) { //No need to initialize or Demand, since NextSample already does. return NextSample().RawValue; } else { Initialize(); return this.sharedCounter.Value; } } set { if (ReadOnly) ThrowReadOnly(); Initialize(); this.sharedCounter.Value = value; } } /// <devdoc> /// </devdoc> public void BeginInit() { this.Close(); } /// <devdoc> /// Frees all the resources allocated by this counter /// </devdoc> public void Close() { this.helpMsg = null; this.oldSample = CounterSample.Empty; this.sharedCounter = null; this.initialized = false; this.counterType = -1; } /// <devdoc> /// Frees all the resources allocated for all performance /// counters, frees File Mapping used by extensible counters, /// unloads dll's used to read counters. /// </devdoc> public static void CloseSharedResources() { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, ".", "*"); permission.Demand(); PerformanceCounterLib.CloseAllLibraries(); } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void Dispose(bool disposing) { // safe to call while finalizing or disposing // if (disposing) { //Dispose managed and unmanaged resources Close(); } base.Dispose(disposing); } /// <devdoc> /// Decrements counter by one using an efficient atomic operation. /// </devdoc> public long Decrement() { if (ReadOnly) ThrowReadOnly(); Initialize(); return this.sharedCounter.Decrement(); } /// <devdoc> /// </devdoc> public void EndInit() { Initialize(); } /// <devdoc> /// Increments the value of this counter. If counter type is of a 32-bit size, it'll truncate /// the value given to 32 bits. This method uses a mutex to guarantee correctness of /// the operation in case of multiple writers. This method should be used with caution because of the negative /// impact on performance due to creation of the mutex. /// </devdoc> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public long IncrementBy(long value) { if (isReadOnly) ThrowReadOnly(); Initialize(); return this.sharedCounter.IncrementBy(value); } /// <devdoc> /// Increments counter by one using an efficient atomic operation. /// </devdoc> public long Increment() { if (isReadOnly) ThrowReadOnly(); Initialize(); return this.sharedCounter.Increment(); } private void ThrowReadOnly() { throw new InvalidOperationException(SR.GetString(SR.ReadOnlyCounter)); } private static void VerifyWriteableCounterAllowed() { if(EnvironmentHelpers.IsAppContainerProcess) { throw new NotSupportedException(SR.GetString(SR.PCNotSupportedUnderAppContainer)); } } private void Initialize() { // Keep this method small so the JIT will inline it. if (!initialized && !DesignMode) { InitializeImpl(); } } /// <devdoc> /// Intializes required resources /// </devdoc> //[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private void InitializeImpl() { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(InstanceLockObject, ref tookLock); if (!initialized) { string currentCategoryName = categoryName; string currentMachineName = machineName; if (currentCategoryName == String.Empty) throw new InvalidOperationException(SR.GetString(SR.CategoryNameMissing)); if (this.counterName == String.Empty) throw new InvalidOperationException(SR.GetString(SR.CounterNameMissing)); if (this.ReadOnly) { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, counterName)) throw new InvalidOperationException(SR.GetString(SR.CounterExists, currentCategoryName, counterName)); PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName); if (categoryType == PerformanceCounterCategoryType.MultiInstance) { if (String.IsNullOrEmpty(instanceName)) throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, currentCategoryName)); } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) { if (!String.IsNullOrEmpty(instanceName)) throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, currentCategoryName)); } if (instanceLifetime != PerformanceCounterInstanceLifetime.Global) throw new InvalidOperationException(SR.GetString(SR.InstanceLifetimeProcessonReadOnly)); this.initialized = true; } else { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, currentMachineName, currentCategoryName); permission.Demand(); if (currentMachineName != "." && String.Compare(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0) throw new InvalidOperationException(SR.GetString(SR.RemoteWriting)); SharedUtils.CheckNtEnvironment(); if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName)) throw new InvalidOperationException(SR.GetString(SR.NotCustomCounter)); // check category type PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName); if (categoryType == PerformanceCounterCategoryType.MultiInstance) { if (String.IsNullOrEmpty(instanceName)) throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, currentCategoryName)); } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) { if (!String.IsNullOrEmpty(instanceName)) throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, currentCategoryName)); } if (String.IsNullOrEmpty(instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process) throw new InvalidOperationException(SR.GetString(SR.InstanceLifetimeProcessforSingleInstance)); this.sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), counterName.ToLower(CultureInfo.InvariantCulture), instanceName.ToLower(CultureInfo.InvariantCulture), instanceLifetime); this.initialized = true; } } } finally { if (tookLock) Monitor.Exit(InstanceLockObject); } } // Will cause an update, raw value /// <devdoc> /// Obtains a counter sample and returns the raw value for it. /// </devdoc> public CounterSample NextSample() { string currentCategoryName = categoryName; string currentMachineName = machineName; PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); Initialize(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName); CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(this.counterName); this.counterType = counterSample.CounterType; if (!categorySample.IsMultiInstance) { if (instanceName != null && instanceName.Length != 0) throw new InvalidOperationException(SR.GetString(SR.InstanceNameProhibited, this.instanceName)); return counterSample.GetSingleValue(); } else { if (instanceName == null || instanceName.Length == 0) throw new InvalidOperationException(SR.GetString(SR.InstanceNameRequired)); return counterSample.GetInstanceValue(this.instanceName); } } /// <devdoc> /// Obtains a counter sample and returns the calculated value for it. /// NOTE: For counters whose calculated value depend upon 2 counter reads, /// the very first read will return 0.0. /// </devdoc> public float NextValue() { //No need to initialize or Demand, since NextSample already does. CounterSample newSample = NextSample(); float retVal = 0.0f; retVal = CounterSample.Calculate(oldSample, newSample); oldSample = newSample; return retVal; } /// <devdoc> /// Removes this counter instance from the shared memory /// </devdoc> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void RemoveInstance() { if (isReadOnly) throw new InvalidOperationException(SR.GetString(SR.ReadOnlyRemoveInstance)); Initialize(); sharedCounter.RemoveInstance(this.instanceName.ToLower(CultureInfo.InvariantCulture), instanceLifetime); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Zero.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace IotHub.Tests.ScenarioTests { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using IotHub.Tests.Helpers; using Microsoft.Azure.Management.IotHub; using Microsoft.Azure.Management.IotHub.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; public class IotHubLifeCycleTests : IotHubTestBase { [Fact] public void TestIotHubCreateLifeCycle() { using (MockContext context = MockContext.Start(this.GetType())) { this.Initialize(context); // Create Resource Group var resourceGroup = this.CreateResourceGroup(IotHubTestUtilities.DefaultResourceGroupName); // Check if Hub Exists and Delete var operationInputs = new OperationInputs() { Name = IotHubTestUtilities.DefaultIotHubName }; var iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); if (!(bool)iotHubNameAvailabilityInfo.NameAvailable) { this.iotHubClient.IotHubResource.Delete( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); Assert.True(iotHubNameAvailabilityInfo.NameAvailable); } //CreateEH and AuthRule var properties = new IotHubProperties(); properties.Routing = this.GetIotHubRoutingProperties(resourceGroup); var iotHub = this.CreateIotHub(resourceGroup, IotHubTestUtilities.DefaultLocation, IotHubTestUtilities.DefaultIotHubName, properties); Assert.NotNull(iotHub); Assert.Equal(IotHubSku.S1, iotHub.Sku.Name); Assert.Equal(IotHubTestUtilities.DefaultIotHubName, iotHub.Name); // Add and Get Tags IDictionary<string, string> tags = new Dictionary<string, string>(); tags.Add("key1", "value1"); tags.Add("key2", "value2"); var tag = new TagsResource(tags); iotHub = this.iotHubClient.IotHubResource.Update(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, tag); Assert.NotNull(iotHub); Assert.True(iotHub.Tags.Count().Equals(2)); Assert.Equal("value2", iotHub.Tags["key2"]); var subscriptionQuota = this.iotHubClient.ResourceProviderCommon.GetSubscriptionQuota(); Assert.Equal(2, subscriptionQuota.Value.Count); Assert.Equal(1, subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("freeIotHubCount")).Limit); Assert.Equal(100, subscriptionQuota.Value.FirstOrDefault(x => x.Name.Value.Equals("paidIotHubCount")).Limit); var endpointHealth = this.iotHubClient.IotHubResource.GetEndpointHealth(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.Equal(4, endpointHealth.Count()); Assert.Contains(endpointHealth, q => q.EndpointId.Equals("events", StringComparison.OrdinalIgnoreCase)); TestAllRoutesInput testAllRoutesInput = new TestAllRoutesInput(RoutingSource.DeviceMessages, new RoutingMessage(), new RoutingTwin()); TestAllRoutesResult testAllRoutesResult = this.iotHubClient.IotHubResource.TestAllRoutes(testAllRoutesInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName); Assert.Equal(4, testAllRoutesResult.Routes.Count); TestRouteInput testRouteInput = new TestRouteInput(properties.Routing.Routes[0], new RoutingMessage(), new RoutingTwin()); TestRouteResult testRouteResult = this.iotHubClient.IotHubResource.TestRoute(testRouteInput, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.DefaultResourceGroupName); Assert.Equal("true", testRouteResult.Result); // Get quota metrics var quotaMetrics = this.iotHubClient.IotHubResource.GetQuotaMetrics( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.True(quotaMetrics.Count() > 0); Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalMessages", StringComparison.OrdinalIgnoreCase) && q.CurrentValue == 0 && q.MaxValue == 400000); Assert.Contains(quotaMetrics, q => q.Name.Equals("TotalDeviceCount", StringComparison.OrdinalIgnoreCase) && q.CurrentValue == 0 && q.MaxValue == 1000000); // Get all Iot Hubs in a resource group var iotHubs = this.iotHubClient.IotHubResource.ListByResourceGroup(IotHubTestUtilities.DefaultResourceGroupName); Assert.True(iotHubs.Count() > 0); // Get all Iot Hubs in a subscription var iotHubBySubscription = this.iotHubClient.IotHubResource.ListBySubscription(); Assert.True(iotHubBySubscription.Count() > 0); // Get Registry Stats var regStats = this.iotHubClient.IotHubResource.GetStats(IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.True(regStats.TotalDeviceCount.Value.Equals(0)); Assert.True(regStats.EnabledDeviceCount.Value.Equals(0)); Assert.True(regStats.DisabledDeviceCount.Value.Equals(0)); // Get Valid Skus var skus = this.iotHubClient.IotHubResource.GetValidSkus( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.Equal(3, skus.Count()); // Get All Iothub Keys var keys = this.iotHubClient.IotHubResource.ListKeys( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.True(keys.Count() > 0); Assert.Contains(keys, k => k.KeyName.Equals("iothubowner", StringComparison.OrdinalIgnoreCase)); // Get specific IotHub Key var key = this.iotHubClient.IotHubResource.GetKeysForKeyName( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, "iothubowner"); Assert.Equal("iothubowner", key.KeyName); // Get All EH consumer groups var ehConsumerGroups = this.iotHubClient.IotHubResource.ListEventHubConsumerGroups( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName); Assert.True(ehConsumerGroups.Count() > 0); Assert.Contains(ehConsumerGroups, e => e.Name.Equals("$Default", StringComparison.OrdinalIgnoreCase)); // Add EH consumer group var ehConsumerGroup = this.iotHubClient.IotHubResource.CreateEventHubConsumerGroup( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName, "testConsumerGroup"); Assert.Equal("testConsumerGroup", ehConsumerGroup.Name); // Get EH consumer group ehConsumerGroup = this.iotHubClient.IotHubResource.GetEventHubConsumerGroup( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName, "testConsumerGroup"); Assert.Equal("testConsumerGroup", ehConsumerGroup.Name); // Delete EH consumer group this.iotHubClient.IotHubResource.DeleteEventHubConsumerGroup( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName, IotHubTestUtilities.EventsEndpointName, "testConsumerGroup"); // Get all of the available IoT Hub REST API operations var operationList = this.iotHubClient.Operations.List(); Assert.True(operationList.Count() > 0); Assert.Contains(operationList, e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase)); // Get IoT Hub REST API read operation var hubReadOperation = operationList.Where(e => e.Name.Equals("Microsoft.Devices/iotHubs/Read", StringComparison.OrdinalIgnoreCase)); Assert.True(hubReadOperation.Count().Equals(1)); Assert.Equal("Microsoft Devices", hubReadOperation.First().Display.Provider, ignoreCase: true); Assert.Equal("Get IotHub(s)", hubReadOperation.First().Display.Operation, ignoreCase: true); // Initiate manual failover var iotHubBeforeFailover = this.iotHubClient.IotHubResource.Get( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); var failoverInput = new FailoverInput(IotHubTestUtilities.DefaultFailoverLocation); this.iotHubClient.IotHub.ManualFailover(IotHubTestUtilities.DefaultIotHubName, failoverInput, IotHubTestUtilities.DefaultResourceGroupName); var iotHubAfterFailover = this.iotHubClient.IotHubResource.Get( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultIotHubName); Assert.Equal("primary", iotHubBeforeFailover.Properties.Locations[0].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultLocation.ToLower(), iotHubBeforeFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower()); Assert.Equal("secondary", iotHubBeforeFailover.Properties.Locations[1].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultFailoverLocation.ToLower(), iotHubBeforeFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower()); Assert.Equal("primary", iotHubAfterFailover.Properties.Locations[0].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultFailoverLocation.ToLower(), iotHubAfterFailover.Properties.Locations[0].Location.Replace(" ", "").ToLower()); Assert.Equal("secondary", iotHubAfterFailover.Properties.Locations[1].Role.ToLower()); Assert.Equal(IotHubTestUtilities.DefaultLocation.ToLower(), iotHubAfterFailover.Properties.Locations[1].Location.Replace(" ", "").ToLower()); } } [Fact] public void TestIotHubUpdateLifeCycle() { using (MockContext context = MockContext.Start(this.GetType())) { this.Initialize(context); // Create Resource Group var resourceGroup = this.CreateResourceGroup(IotHubTestUtilities.DefaultUpdateResourceGroupName); // Check if Hub Exists and Delete var operationInputs = new OperationInputs() { Name = IotHubTestUtilities.DefaultUpdateIotHubName }; var iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); if (!(bool)iotHubNameAvailabilityInfo.NameAvailable) { this.iotHubClient.IotHubResource.Delete( IotHubTestUtilities.DefaultResourceGroupName, IotHubTestUtilities.DefaultUpdateIotHubName); iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); Assert.True(iotHubNameAvailabilityInfo.NameAvailable); } var iotHub = this.CreateIotHub(resourceGroup, IotHubTestUtilities.DefaultLocation, IotHubTestUtilities.DefaultUpdateIotHubName, null); Assert.NotNull(iotHub); Assert.Equal(IotHubSku.S1, iotHub.Sku.Name); Assert.Equal(IotHubTestUtilities.DefaultUpdateIotHubName, iotHub.Name); // Update capacity iotHub.Sku.Capacity += 1; var retIotHub = this.UpdateIotHub(resourceGroup, iotHub, IotHubTestUtilities.DefaultUpdateIotHubName); Assert.NotNull(retIotHub); Assert.Equal(IotHubSku.S1, retIotHub.Sku.Name); Assert.Equal(iotHub.Sku.Capacity, retIotHub.Sku.Capacity); Assert.Equal(IotHubTestUtilities.DefaultUpdateIotHubName, retIotHub.Name); // Update IotHub with routing rules iotHub.Properties.Routing = this.GetIotHubRoutingProperties(resourceGroup); retIotHub = this.UpdateIotHub(resourceGroup, iotHub, IotHubTestUtilities.DefaultUpdateIotHubName); Assert.NotNull(retIotHub); Assert.Equal(IotHubTestUtilities.DefaultUpdateIotHubName, retIotHub.Name); Assert.Equal(4, retIotHub.Properties.Routing.Routes.Count); Assert.Equal(1, retIotHub.Properties.Routing.Endpoints.EventHubs.Count); Assert.Equal(1, retIotHub.Properties.Routing.Endpoints.ServiceBusTopics.Count); Assert.Equal(1, retIotHub.Properties.Routing.Endpoints.ServiceBusQueues.Count); Assert.Equal("route1", retIotHub.Properties.Routing.Routes[0].Name); // Get an Iot Hub var iotHubDesc = this.iotHubClient.IotHubResource.Get( IotHubTestUtilities.DefaultUpdateResourceGroupName, IotHubTestUtilities.DefaultUpdateIotHubName); Assert.NotNull(iotHubDesc); Assert.Equal(IotHubSku.S1, iotHubDesc.Sku.Name); Assert.Equal(iotHub.Sku.Capacity, iotHubDesc.Sku.Capacity); Assert.Equal(IotHubTestUtilities.DefaultUpdateIotHubName, iotHubDesc.Name); // Update Again // perform a dummy update iotHubDesc.Properties.Routing.Endpoints.EventHubs[0].ResourceGroup = "1"; retIotHub = this.UpdateIotHub(resourceGroup, iotHubDesc, IotHubTestUtilities.DefaultUpdateIotHubName); Assert.NotNull(retIotHub); Assert.Equal(IotHubTestUtilities.DefaultUpdateIotHubName, retIotHub.Name); Assert.Equal(4, retIotHub.Properties.Routing.Routes.Count); Assert.Equal(1, retIotHub.Properties.Routing.Endpoints.EventHubs.Count); Assert.Equal(1, retIotHub.Properties.Routing.Endpoints.ServiceBusTopics.Count); Assert.Equal(1, retIotHub.Properties.Routing.Endpoints.ServiceBusQueues.Count); Assert.Equal("route1", retIotHub.Properties.Routing.Routes[0].Name); } } [Fact] public void TestIotHubCertificateLifeCycle() { using (MockContext context = MockContext.Start(this.GetType())) { this.Initialize(context); // Create Resource Group var resourceGroup = this.CreateResourceGroup(IotHubTestUtilities.DefaultCertificateResourceGroupName); // Check if Hub Exists and Delete var operationInputs = new OperationInputs() { Name = IotHubTestUtilities.DefaultCertificateIotHubName }; var iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); if (!(bool)iotHubNameAvailabilityInfo.NameAvailable) { this.iotHubClient.IotHubResource.Delete( IotHubTestUtilities.DefaultCertificateResourceGroupName, IotHubTestUtilities.DefaultCertificateIotHubName); iotHubNameAvailabilityInfo = this.iotHubClient.IotHubResource.CheckNameAvailability(operationInputs); Assert.True(iotHubNameAvailabilityInfo.NameAvailable); } // Create Hub var iotHub = this.CreateIotHub(resourceGroup, IotHubTestUtilities.DefaultLocation, IotHubTestUtilities.DefaultCertificateIotHubName, null); // Upload Certificate to the Hub var newCertificateDescription = this.CreateCertificate(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName, IotHubTestUtilities.DefaultIotHubCertificateName, IotHubTestUtilities.DefaultIotHubCertificateContent); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateName, newCertificateDescription.Name); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateSubject, newCertificateDescription.Properties.Subject); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateThumbprint, newCertificateDescription.Properties.Thumbprint); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateType, newCertificateDescription.Type); Assert.False(newCertificateDescription.Properties.IsVerified); // Get all certificates var certificateList = this.GetCertificates(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName); Assert.True(certificateList.Value.Count().Equals(1)); // Get certificate var certificate = this.GetCertificate(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName, IotHubTestUtilities.DefaultIotHubCertificateName); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateName, certificate.Name); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateSubject, certificate.Properties.Subject); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateThumbprint, certificate.Properties.Thumbprint); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateType, certificate.Type); Assert.False(certificate.Properties.IsVerified); var certificateWithNonceDescription = this.GenerateVerificationCode(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName, IotHubTestUtilities.DefaultIotHubCertificateName, certificate.Etag); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateName, certificateWithNonceDescription.Name); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateSubject, certificateWithNonceDescription.Properties.Subject); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateThumbprint, certificateWithNonceDescription.Properties.Thumbprint); Assert.Equal(IotHubTestUtilities.DefaultIotHubCertificateType, certificateWithNonceDescription.Type); Assert.False(certificateWithNonceDescription.Properties.IsVerified); Assert.NotNull(certificateWithNonceDescription.Properties.VerificationCode); // Delete certificate this.DeleteCertificate(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName, IotHubTestUtilities.DefaultIotHubCertificateName, certificateWithNonceDescription.Etag); // Get all certificate after delete var certificateListAfterDelete = this.GetCertificates(resourceGroup, IotHubTestUtilities.DefaultCertificateIotHubName); Assert.True(certificateListAfterDelete.Value.Count().Equals(0)); } } RoutingProperties GetIotHubRoutingProperties(ResourceGroup resourceGroup) { var ehConnectionString = this.CreateExternalEH(resourceGroup, location); var sbTopicConnectionString = this.CreateExternalQueueAndTopic(resourceGroup, location); var sbConnectionString = sbTopicConnectionString.Item1; var topicConnectionString = sbTopicConnectionString.Item2; // Create Hub var routingProperties = new RoutingProperties() { Endpoints = new RoutingEndpoints() { EventHubs = new List<RoutingEventHubProperties>() { new RoutingEventHubProperties() { Name = "eh1", ConnectionString = ehConnectionString } }, ServiceBusQueues = new List<RoutingServiceBusQueueEndpointProperties>() { new RoutingServiceBusQueueEndpointProperties() { Name = "sb1", ConnectionString = sbConnectionString } }, ServiceBusTopics = new List<RoutingServiceBusTopicEndpointProperties>() { new RoutingServiceBusTopicEndpointProperties() { Name = "tp1", ConnectionString = topicConnectionString } } }, Routes = new List<RouteProperties>() { new RouteProperties() { Condition = "true", EndpointNames = new List<string>() {"events"}, IsEnabled = true, Name = "route1", Source = "DeviceMessages" }, new RouteProperties() { Condition = "true", EndpointNames = new List<string>() {"eh1"}, IsEnabled = true, Name = "route2", Source = "DeviceMessages" }, new RouteProperties() { Condition = "true", EndpointNames = new List<string>() {"sb1"}, IsEnabled = true, Name = "route3", Source = "DeviceMessages" }, new RouteProperties() { Condition = "true", EndpointNames = new List<string>() {"tp1"}, IsEnabled = true, Name = "route4", Source = "DeviceMessages" } } }; return routingProperties; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security; using System.Runtime.InteropServices; using Microsoft.Win32; namespace Microsoft.PowerShell.xTimeZone { [StructLayoutAttribute(LayoutKind.Sequential)] public struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; [MarshalAs(UnmanagedType.U2)] public short Month; [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; [MarshalAs(UnmanagedType.U2)] public short Day; [MarshalAs(UnmanagedType.U2)] public short Hour; [MarshalAs(UnmanagedType.U2)] public short Minute; [MarshalAs(UnmanagedType.U2)] public short Second; [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public int Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string StandardName; public SystemTime StandardDate; [MarshalAs(UnmanagedType.I4)] public int StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string DaylightName; public SystemTime DaylightDate; [MarshalAs(UnmanagedType.I4)] public int DaylightBias; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DynamicTimeZoneInformation { public int Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SystemTime StandardDate; public int StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SystemTime DaylightDate; public int DaylightBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string TimeZoneKeyName; [MarshalAs(UnmanagedType.U1)] public bool DynamicDaylightTimeDisabled; } [StructLayout(LayoutKind.Sequential)] public struct RegistryTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public int Bias; [MarshalAs(UnmanagedType.I4)] public int StandardBias; [MarshalAs(UnmanagedType.I4)] public int DaylightBias; public SystemTime StandardDate; public SystemTime DaylightDate; public RegistryTimeZoneInformation(TimeZoneInformation tzi) { this.Bias = tzi.Bias; this.StandardDate = tzi.StandardDate; this.StandardBias = tzi.StandardBias; this.DaylightDate = tzi.DaylightDate; this.DaylightBias = tzi.DaylightBias; } public RegistryTimeZoneInformation(byte[] bytes) { if ((bytes == null) || (bytes.Length != 0x2c)) { throw new ArgumentException("Argument_InvalidREG_TZI_FORMAT"); } this.Bias = BitConverter.ToInt32(bytes, 0); this.StandardBias = BitConverter.ToInt32(bytes, 4); this.DaylightBias = BitConverter.ToInt32(bytes, 8); this.StandardDate.Year = BitConverter.ToInt16(bytes, 12); this.StandardDate.Month = BitConverter.ToInt16(bytes, 14); this.StandardDate.DayOfWeek = BitConverter.ToInt16(bytes, 0x10); this.StandardDate.Day = BitConverter.ToInt16(bytes, 0x12); this.StandardDate.Hour = BitConverter.ToInt16(bytes, 20); this.StandardDate.Minute = BitConverter.ToInt16(bytes, 0x16); this.StandardDate.Second = BitConverter.ToInt16(bytes, 0x18); this.StandardDate.Milliseconds = BitConverter.ToInt16(bytes, 0x1a); this.DaylightDate.Year = BitConverter.ToInt16(bytes, 0x1c); this.DaylightDate.Month = BitConverter.ToInt16(bytes, 30); this.DaylightDate.DayOfWeek = BitConverter.ToInt16(bytes, 0x20); this.DaylightDate.Day = BitConverter.ToInt16(bytes, 0x22); this.DaylightDate.Hour = BitConverter.ToInt16(bytes, 0x24); this.DaylightDate.Minute = BitConverter.ToInt16(bytes, 0x26); this.DaylightDate.Second = BitConverter.ToInt16(bytes, 40); this.DaylightDate.Milliseconds = BitConverter.ToInt16(bytes, 0x2a); } } public class TokenPrivilegesAccess { [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, ref int tokenhandle); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern int GetCurrentProcess(); [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid); [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGE Newstate, int bufferlength, int PreivousState, int Returnlength); public const int TOKEN_ASSIGN_PRIMARY = 0x00000001; public const int TOKEN_DUPLICATE = 0x00000002; public const int TOKEN_IMPERSONATE = 0x00000004; public const int TOKEN_QUERY = 0x00000008; public const int TOKEN_QUERY_SOURCE = 0x00000010; public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; public const int TOKEN_ADJUST_GROUPS = 0x00000040; public const int TOKEN_ADJUST_DEFAULT = 0x00000080; public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002; public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004; public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000; public static bool EnablePrivilege(string privilege) { try { int token = 0; int retVal = 0; TOKEN_PRIVILEGE TP = new TOKEN_PRIVILEGE(); LUID LD = new LUID(); retVal = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); retVal = LookupPrivilegeValue(null, privilege, ref LD); TP.PrivilegeCount = 1; var luidAndAtt = new LUID_AND_ATTRIBUTES(); luidAndAtt.Attributes = SE_PRIVILEGE_ENABLED; luidAndAtt.Luid = LD; TP.Privilege = luidAndAtt; retVal = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0); return true; } catch { return false; } } public static bool DisablePrivilege(string privilege) { try { int token = 0; int retVal = 0; TOKEN_PRIVILEGE TP = new TOKEN_PRIVILEGE(); LUID LD = new LUID(); retVal = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); retVal = LookupPrivilegeValue(null, privilege, ref LD); TP.PrivilegeCount = 1; // TP.Attributes should be none (not set) to disable privilege var luidAndAtt = new LUID_AND_ATTRIBUTES(); luidAndAtt.Luid = LD; TP.Privilege = luidAndAtt; retVal = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0); return true; } catch { return false; } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LUID { internal uint LowPart; internal uint HighPart; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LUID_AND_ATTRIBUTES { internal LUID Luid; internal uint Attributes; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TOKEN_PRIVILEGE { internal uint PrivilegeCount; internal LUID_AND_ATTRIBUTES Privilege; } public class TimeZone { public const int ERROR_ACCESS_DENIED = 0x005; public const int CORSEC_E_MISSING_STRONGNAME = -2146233317; [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool SetTimeZoneInformation([In] ref TimeZoneInformation lpTimeZoneInformation); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool SetDynamicTimeZoneInformation([In] ref DynamicTimeZoneInformation lpTimeZoneInformation); public static void Set(string name) { var regTimeZones = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones"); // Print out all the possible time-zones. //foreach(var subKey in regTimeZones.GetSubKeyNames()) //{ // Console.WriteLine(subKey); //} var subKey = regTimeZones.GetSubKeyNames().Where(s => s == name).First(); string daylightName = (string)regTimeZones.OpenSubKey(subKey).GetValue("Dlt"); string standardName = (string)regTimeZones.OpenSubKey(subKey).GetValue("Std"); byte[] tzi = (byte[])regTimeZones.OpenSubKey(subKey).GetValue("TZI"); var regTzi = new RegistryTimeZoneInformation(tzi); TokenPrivilegesAccess.EnablePrivilege("SeTimeZonePrivilege"); bool didSet; if (Environment.OSVersion.Version.Major < 6) { var tz = new TimeZoneInformation(); tz.Bias = regTzi.Bias; tz.DaylightBias = regTzi.DaylightBias; tz.StandardBias = regTzi.StandardBias; tz.DaylightDate = regTzi.DaylightDate; tz.StandardDate = regTzi.StandardDate; tz.DaylightName = daylightName; tz.StandardName = standardName; didSet = TimeZone.SetTimeZoneInformation(ref tz); } else { var tz = new DynamicTimeZoneInformation(); tz.Bias = regTzi.Bias; tz.DaylightBias = regTzi.DaylightBias; tz.StandardBias = regTzi.StandardBias; tz.DaylightDate = regTzi.DaylightDate; tz.StandardDate = regTzi.StandardDate; tz.DaylightName = daylightName; tz.StandardName = standardName; tz.TimeZoneKeyName = subKey; tz.DynamicDaylightTimeDisabled = false; didSet = TimeZone.SetDynamicTimeZoneInformation(ref tz); } int lastError = Marshal.GetLastWin32Error(); TokenPrivilegesAccess.DisablePrivilege("SeTimeZonePrivilege"); if (! didSet) { if (lastError == TimeZone.ERROR_ACCESS_DENIED) { throw new SecurityException("Access denied changing System Timezone."); } else if (lastError == TimeZone.CORSEC_E_MISSING_STRONGNAME) { throw new SystemException("Application is not signed."); } else { throw new SystemException("Win32Error: " + lastError + "\nHRESULT: " + Marshal.GetHRForLastWin32Error()); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; namespace LinFu.DynamicProxy { internal class DefaultMethodEmitter : IMethodBodyEmitter { private static MethodInfo getInterceptor = null; private static MethodInfo getGenericMethodFromHandle = typeof(MethodBase).GetMethod("GetMethodFromHandle", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) }, null); private static MethodInfo getMethodFromHandle = typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) }); private static MethodInfo getTypeFromHandle = typeof (Type).GetMethod("GetTypeFromHandle"); private static MethodInfo handlerMethod = typeof (IInterceptor).GetMethod("Intercept"); private static ConstructorInfo infoConstructor; private static PropertyInfo interceptorProperty = typeof (IProxy).GetProperty("Interceptor"); private static ConstructorInfo notImplementedConstructor = typeof (NotImplementedException).GetConstructor(new Type[0]); private static Dictionary<string, OpCode> stindMap = new StindMap(); private IArgumentHandler _argumentHandler; static DefaultMethodEmitter() { getInterceptor = interceptorProperty.GetGetMethod(); Type[] constructorTypes = new Type[] { typeof (object), typeof (MethodInfo), typeof (StackTrace), typeof (Type[]), typeof (object[]) }; infoConstructor = typeof (InvocationInfo).GetConstructor(constructorTypes); } public DefaultMethodEmitter() : this(new DefaultArgumentHandler()) { } public DefaultMethodEmitter(IArgumentHandler argumentHandler) { _argumentHandler = argumentHandler; } public void EmitMethodBody(ILGenerator IL, MethodInfo method, FieldInfo field) { bool isStatic = false; ParameterInfo[] parameters = method.GetParameters(); IL.DeclareLocal(typeof (object[])); IL.DeclareLocal(typeof (InvocationInfo)); IL.DeclareLocal(typeof (Type[])); IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Callvirt, getInterceptor); // if (interceptor == null) // throw new NullReferenceException(); Label skipThrow = IL.DefineLabel(); IL.Emit(OpCodes.Dup); IL.Emit(OpCodes.Ldnull); IL.Emit(OpCodes.Bne_Un, skipThrow); IL.Emit(OpCodes.Newobj, notImplementedConstructor); IL.Emit(OpCodes.Throw); IL.MarkLabel(skipThrow); // Push the 'this' pointer onto the stack IL.Emit(OpCodes.Ldarg_0); // Push the MethodInfo onto the stack Type declaringType = method.DeclaringType; IL.Emit(OpCodes.Ldtoken, method); if (declaringType.IsGenericType) { IL.Emit(OpCodes.Ldtoken, declaringType); IL.Emit(OpCodes.Call, getGenericMethodFromHandle); } else { IL.Emit(OpCodes.Call, getMethodFromHandle); } IL.Emit(OpCodes.Castclass, typeof (MethodInfo)); PushStackTrace(IL); PushGenericArguments(method, IL); _argumentHandler.PushArguments(parameters, IL, isStatic); // InvocationInfo info = new InvocationInfo(...); IL.Emit(OpCodes.Newobj, infoConstructor); IL.Emit(OpCodes.Stloc_1); IL.Emit(OpCodes.Ldloc_1); IL.Emit(OpCodes.Callvirt, handlerMethod); SaveRefArguments(IL, parameters); PackageReturnType(method, IL); IL.Emit(OpCodes.Ret); } private static void SaveRefArguments(ILGenerator IL, ParameterInfo[] parameters) { // Save the arguments returned from the handler method MethodInfo getArguments = typeof (InvocationInfo).GetMethod("get_Arguments"); IL.Emit(OpCodes.Ldloc_1); IL.Emit(OpCodes.Call, getArguments); IL.Emit(OpCodes.Stloc_0); foreach (ParameterInfo param in parameters) { string typeName = param.ParameterType.Name; bool isRef = param.ParameterType.IsByRef && typeName.EndsWith("&"); if (!isRef) continue; // Load the destination address IL.Emit(OpCodes.Ldarg, param.Position + 1); // Load the argument value IL.Emit(OpCodes.Ldloc_0); IL.Emit(OpCodes.Ldc_I4, param.Position); var ldelemInstruction = OpCodes.Ldelem_Ref; IL.Emit(ldelemInstruction); var unboxedType = param.ParameterType.IsByRef ? param.ParameterType.GetElementType() : param.ParameterType; IL.Emit(OpCodes.Unbox_Any, unboxedType); OpCode stind = GetStindInstruction(param.ParameterType); IL.Emit(stind); } } private static OpCode GetStindInstruction(Type parameterType) { if (parameterType.IsClass && !parameterType.Name.EndsWith("&")) return OpCodes.Stind_Ref; string typeName = parameterType.Name; if (!stindMap.ContainsKey(typeName) && parameterType.IsByRef) return OpCodes.Stind_Ref; Debug.Assert(stindMap.ContainsKey(typeName)); OpCode result = stindMap[typeName]; return result; } private void PushStackTrace(ILGenerator IL) { // NOTE: The stack trace has been disabled for performance reasons IL.Emit(OpCodes.Ldnull); } private void PushGenericArguments(MethodInfo method, ILGenerator IL) { Type[] typeParameters = method.GetGenericArguments(); // If this is a generic method, we need to store // the generic method arguments int genericTypeCount = typeParameters == null ? 0 : typeParameters.Length; // Type[] genericTypeArgs = new Type[genericTypeCount]; IL.Emit(OpCodes.Ldc_I4, genericTypeCount); IL.Emit(OpCodes.Newarr, typeof (Type)); if (genericTypeCount == 0) return; for (int index = 0; index < genericTypeCount; index++) { Type currentType = typeParameters[index]; IL.Emit(OpCodes.Dup); IL.Emit(OpCodes.Ldc_I4, index); IL.Emit(OpCodes.Ldtoken, currentType); IL.Emit(OpCodes.Call, getTypeFromHandle); IL.Emit(OpCodes.Stelem_Ref); } } private void PackageReturnType(MethodInfo method, ILGenerator IL) { Type returnType = method.ReturnType; // Unbox the return value if necessary if (returnType == typeof (void)) { IL.Emit(OpCodes.Pop); return; } IL.Emit(OpCodes.Unbox_Any, returnType); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Tests.Compute; using NUnit.Framework; /// <summary> /// Services tests. /// </summary> public class ServicesTest { /** */ private const string SvcName = "Service1"; /** */ private const string CacheName = "cache1"; /** */ private const int AffKey = 25; /** */ protected IIgnite Grid1; /** */ protected IIgnite Grid2; /** */ protected IIgnite Grid3; /** */ protected IIgnite[] Grids; [TestFixtureTearDown] public void FixtureTearDown() { StopGrids(); } /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { StartGrids(); EventsTestHelper.ListenResult = true; } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { Services.Cancel(SvcName); TestUtils.AssertHandleRegistryIsEmpty(1000, Grid1, Grid2, Grid3); } catch (Exception) { // Restart grids to cleanup StopGrids(); throw; } finally { EventsTestHelper.AssertFailures(); if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes")) StopGrids(); // clean events for other tests } } /// <summary> /// Tests deployment. /// </summary> [Test] public void TestDeploy([Values(true, false)] bool binarizable) { var cfg = new ServiceConfiguration { Name = SvcName, MaxPerNodeCount = 3, TotalCount = 3, NodeFilter = new NodeFilter {NodeId = Grid1.GetCluster().GetLocalNode().Id}, Service = binarizable ? new TestIgniteServiceBinarizable() : new TestIgniteServiceSerializable() }; Services.Deploy(cfg); CheckServiceStarted(Grid1, 3); } /// <summary> /// Tests cluster singleton deployment. /// </summary> [Test] public void TestDeployClusterSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployClusterSingleton(SvcName, svc); var svc0 = Services.GetServiceProxy<ITestIgniteService>(SvcName); // Check that only one node has the service. foreach (var grid in Grids) { if (grid.GetCluster().GetLocalNode().Id == svc0.NodeId) CheckServiceStarted(grid); else Assert.IsNull(grid.GetServices().GetService<TestIgniteServiceSerializable>(SvcName)); } } /// <summary> /// Tests node singleton deployment. /// </summary> [Test] public void TestDeployNodeSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployNodeSingleton(SvcName, svc); Assert.AreEqual(1, Grid1.GetServices().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(1, Grid2.GetServices().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(0, Grid3.GetServices().GetServices<ITestIgniteService>(SvcName).Count); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingleton() { var svc = new TestIgniteServiceBinarizable(); Services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, AffKey); var affNode = Grid1.GetAffinity(CacheName).MapKeyToNode(AffKey); var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(affNode.Id, prx.NodeId); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingletonBinarizable() { var services = Services.WithKeepBinary(); var svc = new TestIgniteServiceBinarizable(); var affKey = new BinarizableObject {Val = AffKey}; services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, affKey); var prx = services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.IsTrue(prx.Initialized); } /// <summary> /// Tests multiple deployment. /// </summary> [Test] public void TestDeployMultiple() { var svc = new TestIgniteServiceSerializable(); Services.DeployMultiple(SvcName, svc, Grids.Length * 5, 5); foreach (var grid in Grids.Where(x => !x.GetConfiguration().ClientMode)) CheckServiceStarted(grid, 5); } /// <summary> /// Tests cancellation. /// </summary> [Test] public void TestCancel() { for (var i = 0; i < 10; i++) { Services.DeployNodeSingleton(SvcName + i, new TestIgniteServiceBinarizable()); Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); } Services.Cancel(SvcName + 0); AssertNoService(SvcName + 0); Services.Cancel(SvcName + 1); AssertNoService(SvcName + 1); for (var i = 2; i < 10; i++) Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); Services.CancelAll(); for (var i = 0; i < 10; i++) AssertNoService(SvcName + i); } /// <summary> /// Tests service proxy. /// </summary> [Test] public void TestGetServiceProxy([Values(true, false)] bool binarizable) { // Test proxy without a service var ex = Assert.Throws<IgniteException>(()=> Services.GetServiceProxy<ITestIgniteService>(SvcName)); Assert.AreEqual("Failed to find deployed service: " + SvcName, ex.Message); // Deploy to grid2 & grid3 var svc = binarizable ? new TestIgniteServiceBinarizable {TestProperty = 17} : new TestIgniteServiceSerializable {TestProperty = 17}; Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id, Grid1.GetCluster().GetLocalNode().Id) .GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is no local instance on grid3 Assert.IsNull(Grid3.GetServices().GetService<ITestIgniteService>(SvcName)); // Get proxy var prx = Grid3.GetServices().GetServiceProxy<ITestIgniteService>(SvcName); // Check proxy properties Assert.IsNotNull(prx); Assert.AreEqual(prx.GetType(), svc.GetType()); Assert.AreEqual(prx.ToString(), svc.ToString()); Assert.AreEqual(17, prx.TestProperty); Assert.IsTrue(prx.Initialized); Assert.IsTrue(prx.Executed); Assert.IsFalse(prx.Cancelled); Assert.AreEqual(SvcName, prx.LastCallContextName); // Check err method Assert.Throws<ServiceInvocationException>(() => prx.ErrMethod(123)); // Check local scenario (proxy should not be created for local instance) Assert.IsTrue(ReferenceEquals(Grid2.GetServices().GetService<ITestIgniteService>(SvcName), Grid2.GetServices().GetServiceProxy<ITestIgniteService>(SvcName))); // Check sticky = false: call multiple times, check that different nodes get invoked var invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(2, invokedIds.Count); // Check sticky = true: all calls should be to the same node prx = Grid3.GetServices().GetServiceProxy<ITestIgniteService>(SvcName, true); invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(1, invokedIds.Count); // Proxy does not work for cancelled service. Services.CancelAll(); Assert.Throws<ServiceInvocationException>(() => { Assert.IsTrue(prx.Cancelled); }); } /// <summary> /// Tests the duck typing: proxy interface can be different from actual service interface, /// only called method signature should be compatible. /// </summary> [Test] public void TestDuckTyping([Values(true, false)] bool local) { var svc = new TestIgniteServiceBinarizable {TestProperty = 33}; // Deploy locally or to the remote node var nodeId = (local ? Grid1 : Grid2).GetCluster().GetLocalNode().Id; var cluster = Grid1.GetCluster().ForNodeIds(nodeId); cluster.GetServices().DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.GetServiceProxy<ITestIgniteServiceProxyInterface>(SvcName); // NodeId signature is the same as in service Assert.AreEqual(nodeId, prx.NodeId); // Method signature is different from service signature (object -> object), but is compatible. Assert.AreEqual(15, prx.Method(15)); // TestProperty is object in proxy and int in service, getter works.. Assert.AreEqual(33, prx.TestProperty); // .. but setter does not var ex = Assert.Throws<ServiceInvocationException>(() => { prx.TestProperty = new object(); }); Assert.AreEqual("Specified cast is not valid.", ex.InnerException.Message); } /// <summary> /// Tests service descriptors. /// </summary> [Test] public void TestServiceDescriptors() { Services.DeployKeyAffinitySingleton(SvcName, new TestIgniteServiceSerializable(), CacheName, 1); var descriptors = Services.GetServiceDescriptors(); Assert.AreEqual(1, descriptors.Count); var desc = descriptors.Single(); Assert.AreEqual(SvcName, desc.Name); Assert.AreEqual(CacheName, desc.CacheName); Assert.AreEqual(1, desc.AffinityKey); Assert.AreEqual(1, desc.MaxPerNodeCount); Assert.AreEqual(1, desc.TotalCount); Assert.AreEqual(typeof(TestIgniteServiceSerializable), desc.Type); Assert.AreEqual(Grid1.GetCluster().GetLocalNode().Id, desc.OriginNodeId); var top = desc.TopologySnapshot; var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(1, top.Count); Assert.AreEqual(prx.NodeId, top.Keys.Single()); Assert.AreEqual(1, top.Values.Single()); } /// <summary> /// Tests the client binary flag. /// </summary> [Test] public void TestWithKeepBinaryClient() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject {Val = 11}; var res = (IBinaryObject) prx.Method(obj); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); res = (IBinaryObject) prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); } /// <summary> /// Tests the server binary flag. /// </summary> [Test] public void TestWithKeepBinaryServer() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithServerKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithServerKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject { Val = 11 }; var res = (BinarizableObject) prx.Method(obj); Assert.AreEqual(11, res.Val); res = (BinarizableObject)prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Val); } /// <summary> /// Tests server and client binary flag. /// </summary> [Test] public void TestWithKeepBinaryBoth() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithKeepBinary().WithServerKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepBinary().WithServerKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject { Val = 11 }; var res = (IBinaryObject)prx.Method(obj); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); res = (IBinaryObject)prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); } /// <summary> /// Tests exception in Initialize. /// </summary> [Test] public void TestInitException() { var svc = new TestIgniteServiceSerializable { ThrowInit = true }; var ex = Assert.Throws<IgniteException>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); Assert.IsTrue(ex.InnerException.Message.Contains("PlatformCallbackUtils.serviceInit(Native Method)")); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests exception in Execute. /// </summary> [Test] public void TestExecuteException() { var svc = new TestIgniteServiceSerializable { ThrowExecute = true }; Services.DeployMultiple(SvcName, svc, Grids.Length, 1); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); // Execution failed, but service exists. Assert.IsNotNull(svc0); Assert.IsFalse(svc0.Executed); } /// <summary> /// Tests exception in Cancel. /// </summary> [Test] public void TestCancelException() { var svc = new TestIgniteServiceSerializable { ThrowCancel = true }; Services.DeployMultiple(SvcName, svc, 2, 1); CheckServiceStarted(Grid1); Services.CancelAll(); // Cancellation failed, but service is removed. AssertNoService(); } [Test] public void TestMarshalExceptionOnRead() { var svc = new TestIgniteServiceBinarizableErr(); var ex = Assert.Throws<IgniteException>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } [Test] public void TestMarshalExceptionOnWrite() { var svc = new TestIgniteServiceBinarizableErr {ThrowOnWrite = true}; var ex = Assert.Throws<Exception>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } [Test] public void TestCallJavaService() { const string javaSvcName = "javaService"; // Deploy Java service Grid1.GetCompute() .ExecuteJavaTask<object>("org.apache.ignite.platform.PlatformDeployServiceTask", javaSvcName); // Verify decriptor var descriptor = Services.GetServiceDescriptors().Single(x => x.Name == javaSvcName); Assert.AreEqual(javaSvcName, descriptor.Name); Assert.Throws<ServiceInvocationException>(() => { // ReSharper disable once UnusedVariable var type = descriptor.Type; }); var svc = Services.GetServiceProxy<IJavaService>(javaSvcName, false); var binSvc = Services.WithKeepBinary().WithServerKeepBinary() .GetServiceProxy<IJavaService>(javaSvcName, false); // Basics Assert.IsTrue(svc.isInitialized()); Assert.IsTrue(TestUtils.WaitForCondition(() => svc.isExecuted(), 500)); Assert.IsFalse(svc.isCancelled()); // Primitives Assert.AreEqual(4, svc.test((byte) 3)); Assert.AreEqual(5, svc.test((short) 4)); Assert.AreEqual(6, svc.test(5)); Assert.AreEqual(6, svc.test((long) 5)); Assert.AreEqual(3.8f, svc.test(2.3f)); Assert.AreEqual(5.8, svc.test(3.3)); Assert.IsFalse(svc.test(true)); Assert.AreEqual('b', svc.test('a')); Assert.AreEqual("Foo!", svc.test("Foo")); // Nullables (Java wrapper types) Assert.AreEqual(4, svc.testWrapper(3)); Assert.AreEqual(5, svc.testWrapper((short?) 4)); Assert.AreEqual(6, svc.testWrapper((int?)5)); Assert.AreEqual(6, svc.testWrapper((long?) 5)); Assert.AreEqual(3.8f, svc.testWrapper(2.3f)); Assert.AreEqual(5.8, svc.testWrapper(3.3)); Assert.AreEqual(false, svc.testWrapper(true)); Assert.AreEqual('b', svc.testWrapper('a')); // Arrays Assert.AreEqual(new byte[] {2, 3, 4}, svc.testArray(new byte[] {1, 2, 3})); Assert.AreEqual(new short[] {2, 3, 4}, svc.testArray(new short[] {1, 2, 3})); Assert.AreEqual(new[] {2, 3, 4}, svc.testArray(new[] {1, 2, 3})); Assert.AreEqual(new long[] {2, 3, 4}, svc.testArray(new long[] {1, 2, 3})); Assert.AreEqual(new float[] {2, 3, 4}, svc.testArray(new float[] {1, 2, 3})); Assert.AreEqual(new double[] {2, 3, 4}, svc.testArray(new double[] {1, 2, 3})); Assert.AreEqual(new[] {"a1", "b1"}, svc.testArray(new [] {"a", "b"})); Assert.AreEqual(new[] {'c', 'd'}, svc.testArray(new[] {'b', 'c'})); Assert.AreEqual(new[] {false, true, false}, svc.testArray(new[] {true, false, true})); // Nulls Assert.AreEqual(9, svc.testNull(8)); Assert.IsNull(svc.testNull(null)); // params / varargs Assert.AreEqual(5, svc.testParams(1, 2, 3, 4, "5")); Assert.AreEqual(0, svc.testParams()); // Overloads Assert.AreEqual(3, svc.test(2, "1")); Assert.AreEqual(3, svc.test("1", 2)); // Binary Assert.AreEqual(7, svc.testBinarizable(new PlatformComputeBinarizable {Field = 6}).Field); // Binary collections var arr = new [] {10, 11, 12}.Select(x => new PlatformComputeBinarizable {Field = x}).ToArray<object>(); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableCollection(arr) .OfType<PlatformComputeBinarizable>().Select(x => x.Field).ToArray()); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableArray(arr).OfType<PlatformComputeBinarizable>().Select(x => x.Field).ToArray()); // Binary object Assert.AreEqual(15, binSvc.testBinaryObject( Grid1.GetBinary().ToBinary<IBinaryObject>(new PlatformComputeBinarizable {Field = 6})) .GetField<int>("Field")); Services.Cancel(javaSvcName); } /// <summary> /// Tests the footer setting. /// </summary> [Test] public void TestFooterSetting() { foreach (var grid in Grids) { Assert.AreEqual(CompactFooter, ((Ignite)grid).Marshaller.CompactFooter); Assert.AreEqual(CompactFooter, grid.GetConfiguration().BinaryConfiguration.CompactFooter); } } /// <summary> /// Starts the grids. /// </summary> private void StartGrids() { if (Grid1 != null) return; Grid1 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid1.xml")); Grid2 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid2.xml")); Grid3 = Ignition.Start(GetConfiguration("config\\compute\\compute-grid3.xml")); Grids = new[] { Grid1, Grid2, Grid3 }; } /// <summary> /// Stops the grids. /// </summary> private void StopGrids() { Grid1 = Grid2 = Grid3 = null; Grids = null; Ignition.StopAll(true); } /// <summary> /// Checks that service has started on specified grid. /// </summary> private static void CheckServiceStarted(IIgnite grid, int count = 1) { var services = grid.GetServices().GetServices<TestIgniteServiceSerializable>(SvcName); Assert.AreEqual(count, services.Count); var svc = services.First(); Assert.IsNotNull(svc); Assert.IsTrue(svc.Initialized); Thread.Sleep(100); // Service runs in a separate thread, wait for it to execute. Assert.IsTrue(svc.Executed); Assert.IsFalse(svc.Cancelled); Assert.AreEqual(grid.GetCluster().GetLocalNode().Id, svc.NodeId); } /// <summary> /// Gets the Ignite configuration. /// </summary> private IgniteConfiguration GetConfiguration(string springConfigUrl) { if (!CompactFooter) springConfigUrl = ComputeApiTestFullFooter.ReplaceFooterSetting(springConfigUrl); return new IgniteConfiguration { SpringConfigUrl = springConfigUrl, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), BinaryConfiguration = new BinaryConfiguration( typeof (TestIgniteServiceBinarizable), typeof (TestIgniteServiceBinarizableErr), typeof (PlatformComputeBinarizable), typeof (BinarizableObject)) }; } /// <summary> /// Asserts that there is no service on any grid with given name. /// </summary> /// <param name="name">The name.</param> private void AssertNoService(string name = SvcName) { foreach (var grid in Grids) Assert.IsTrue( // ReSharper disable once AccessToForEachVariableInClosure TestUtils.WaitForCondition(() => grid.GetServices() .GetService<ITestIgniteService>(name) == null, 5000)); } /// <summary> /// Gets the services. /// </summary> protected virtual IServices Services { get { return Grid1.GetServices(); } } /// <summary> /// Gets a value indicating whether compact footers should be used. /// </summary> protected virtual bool CompactFooter { get { return true; } } /// <summary> /// Test service interface for proxying. /// </summary> private interface ITestIgniteService { int TestProperty { get; set; } /** */ bool Initialized { get; } /** */ bool Cancelled { get; } /** */ bool Executed { get; } /** */ Guid NodeId { get; } /** */ string LastCallContextName { get; } /** */ object Method(object arg); /** */ object ErrMethod(object arg); } /// <summary> /// Test service interface for proxy usage. /// Has some of the original interface members with different signatures. /// </summary> private interface ITestIgniteServiceProxyInterface { /** */ Guid NodeId { get; } /** */ object TestProperty { get; set; } /** */ int Method(int arg); } #pragma warning disable 649 /// <summary> /// Test serializable service. /// </summary> [Serializable] private class TestIgniteServiceSerializable : IService, ITestIgniteService { /** */ [InstanceResource] private IIgnite _grid; /** <inheritdoc /> */ public int TestProperty { get; set; } /** <inheritdoc /> */ public bool Initialized { get; private set; } /** <inheritdoc /> */ public bool Cancelled { get; private set; } /** <inheritdoc /> */ public bool Executed { get; private set; } /** <inheritdoc /> */ public Guid NodeId { get { return _grid.GetCluster().GetLocalNode().Id; } } /** <inheritdoc /> */ public string LastCallContextName { get; private set; } /** */ public bool ThrowInit { get; set; } /** */ public bool ThrowExecute { get; set; } /** */ public bool ThrowCancel { get; set; } /** */ public object Method(object arg) { return arg; } /** */ public object ErrMethod(object arg) { throw new ArgumentNullException("arg", "ExpectedException"); } /** <inheritdoc /> */ public void Init(IServiceContext context) { if (ThrowInit) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Initialized = true; } /** <inheritdoc /> */ public void Execute(IServiceContext context) { if (ThrowExecute) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Assert.IsTrue(Initialized); Assert.IsFalse(Cancelled); Executed = true; } /** <inheritdoc /> */ public void Cancel(IServiceContext context) { if (ThrowCancel) throw new Exception("Expected exception"); CheckContext(context); Assert.IsTrue(context.IsCancelled); Cancelled = true; } /// <summary> /// Checks the service context. /// </summary> private void CheckContext(IServiceContext context) { LastCallContextName = context.Name; if (context.AffinityKey != null && !(context.AffinityKey is int)) { var binaryObj = context.AffinityKey as IBinaryObject; var key = binaryObj != null ? binaryObj.Deserialize<BinarizableObject>() : (BinarizableObject) context.AffinityKey; Assert.AreEqual(AffKey, key.Val); } Assert.IsNotNull(_grid); Assert.IsTrue(context.Name.StartsWith(SvcName)); Assert.AreNotEqual(Guid.Empty, context.ExecutionId); } } /// <summary> /// Test binary service. /// </summary> private class TestIgniteServiceBinarizable : TestIgniteServiceSerializable, IBinarizable { /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("TestProp", TestProperty); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { TestProperty = reader.ReadInt("TestProp"); } } /// <summary> /// Test binary service with exceptions in marshalling. /// </summary> private class TestIgniteServiceBinarizableErr : TestIgniteServiceSerializable, IBinarizable { /** */ public bool ThrowOnWrite { get; set; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("TestProp", TestProperty); if (ThrowOnWrite) throw new Exception("Expected exception"); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { TestProperty = reader.ReadInt("TestProp"); throw new Exception("Expected exception"); } } /// <summary> /// Test node filter. /// </summary> [Serializable] private class NodeFilter : IClusterNodeFilter { /// <summary> /// Gets or sets the node identifier. /// </summary> public Guid NodeId { get; set; } /** <inheritdoc /> */ public bool Invoke(IClusterNode node) { return node.Id == NodeId; } } /// <summary> /// Binary object. /// </summary> private class BinarizableObject { public int Val { get; set; } } /// <summary> /// Java service proxy interface. /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] private interface IJavaService { /** */ bool isCancelled(); /** */ bool isInitialized(); /** */ bool isExecuted(); /** */ byte test(byte x); /** */ short test(short x); /** */ int test(int x); /** */ long test(long x); /** */ float test(float x); /** */ double test(double x); /** */ char test(char x); /** */ string test(string x); /** */ bool test(bool x); /** */ byte? testWrapper(byte? x); /** */ short? testWrapper(short? x); /** */ int? testWrapper(int? x); /** */ long? testWrapper(long? x); /** */ float? testWrapper(float? x); /** */ double? testWrapper(double? x); /** */ char? testWrapper(char? x); /** */ bool? testWrapper(bool? x); /** */ byte[] testArray(byte[] x); /** */ short[] testArray(short[] x); /** */ int[] testArray(int[] x); /** */ long[] testArray(long[] x); /** */ float[] testArray(float[] x); /** */ double[] testArray(double[] x); /** */ char[] testArray(char[] x); /** */ string[] testArray(string[] x); /** */ bool[] testArray(bool[] x); /** */ int test(int x, string y); /** */ int test(string x, int y); /** */ int? testNull(int? x); /** */ int testParams(params object[] args); /** */ PlatformComputeBinarizable testBinarizable(PlatformComputeBinarizable x); /** */ object[] testBinarizableArray(object[] x); /** */ ICollection testBinarizableCollection(ICollection x); /** */ IBinaryObject testBinaryObject(IBinaryObject x); } /// <summary> /// Interop class. /// </summary> private class PlatformComputeBinarizable { /** */ public int Field { get; set; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Deployment; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Resource; /// <summary> /// Holder for user-provided compute job. /// </summary> internal class ComputeJobHolder : IBinaryWriteAware { /** Actual job. */ private readonly IComputeJob _job; /** Owning grid. */ private readonly Ignite _ignite; /** Result (set for local jobs only). */ private volatile ComputeJobResultImpl _jobRes; /// <summary> /// Default ctor for marshalling. /// </summary> /// <param name="reader"></param> public ComputeJobHolder(BinaryReader reader) { Debug.Assert(reader != null); _ignite = reader.Marshaller.Ignite; _job = reader.ReadObject<IComputeJob>(); } /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="job">Job.</param> public ComputeJobHolder(Ignite grid, IComputeJob job) { Debug.Assert(grid != null); Debug.Assert(job != null); _ignite = grid; _job = job; } /// <summary> /// Executes local job. /// </summary> /// <param name="cancel">Cancel flag.</param> public void ExecuteLocal(bool cancel) { object res; bool success; Execute0(cancel, out res, out success); _jobRes = new ComputeJobResultImpl( success ? res : null, success ? null : new IgniteException("Compute job has failed on local node, " + "examine InnerException for details.", (Exception) res), _job, _ignite.GetLocalNode().Id, cancel ); } /// <summary> /// Execute job serializing result to the stream. /// </summary> /// <param name="cancel">Whether the job must be cancelled.</param> /// <param name="stream">Stream.</param> public void ExecuteRemote(PlatformMemoryStream stream, bool cancel) { // 1. Execute job. object res; bool success; using (PeerAssemblyResolver.GetInstance(_ignite, Guid.Empty)) { Execute0(cancel, out res, out success); } // 2. Try writing result to the stream. ClusterGroupImpl prj = _ignite.ClusterGroup; BinaryWriter writer = prj.Marshaller.StartMarshal(stream); try { // 3. Marshal results. BinaryUtils.WriteInvocationResult(writer, success, res); } finally { // 4. Process metadata. prj.FinishMarshal(writer); } } /// <summary> /// Cancel the job. /// </summary> public void Cancel() { _job.Cancel(); } /// <summary> /// Serialize the job to the stream. /// </summary> /// <param name="stream">Stream.</param> /// <returns>True if successfull.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User job can throw any exception")] internal bool Serialize(IBinaryStream stream) { ClusterGroupImpl prj = _ignite.ClusterGroup; BinaryWriter writer = prj.Marshaller.StartMarshal(stream); try { writer.Write(this); return true; } catch (Exception e) { writer.WriteString("Failed to marshal job [job=" + _job + ", errType=" + e.GetType().Name + ", errMsg=" + e.Message + ']'); return false; } finally { // 4. Process metadata. prj.FinishMarshal(writer); } } /// <summary> /// Job. /// </summary> internal IComputeJob Job { get { return _job; } } /// <summary> /// Job result. /// </summary> internal ComputeJobResultImpl JobResult { get { return _jobRes; } } /// <summary> /// Internal job execution routine. /// </summary> /// <param name="cancel">Cancel flag.</param> /// <param name="res">Result.</param> /// <param name="success">Success flag.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User job can throw any exception")] private void Execute0(bool cancel, out object res, out bool success) { // 1. Inject resources. IComputeResourceInjector injector = _job as IComputeResourceInjector; if (injector != null) injector.Inject(_ignite); else ResourceProcessor.Inject(_job, _ignite); // 2. Execute. try { if (cancel) _job.Cancel(); res = _job.Execute(); success = true; } catch (Exception e) { res = e; success = false; } } /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { BinaryWriter writer0 = (BinaryWriter) writer.GetRawWriter(); writer0.WithDetach(w => w.WriteObject(_job)); } /// <summary> /// Create job instance. /// </summary> /// <param name="grid">Grid.</param> /// <param name="stream">Stream.</param> /// <returns></returns> internal static ComputeJobHolder CreateJob(Ignite grid, IBinaryStream stream) { try { return grid.Marshaller.StartUnmarshal(stream).ReadObject<ComputeJobHolder>(); } catch (Exception e) { throw new IgniteException("Failed to deserialize the job [errType=" + e.GetType().Name + ", errMsg=" + e.Message + ']'); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ConversationThreadPostsCollectionRequest. /// </summary> public partial class ConversationThreadPostsCollectionRequest : BaseRequest, IConversationThreadPostsCollectionRequest { /// <summary> /// Constructs a new ConversationThreadPostsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ConversationThreadPostsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Post to the collection via POST. /// </summary> /// <param name="post">The Post to add.</param> /// <returns>The created Post.</returns> public System.Threading.Tasks.Task<Post> AddAsync(Post post) { return this.AddAsync(post, CancellationToken.None); } /// <summary> /// Adds the specified Post to the collection via POST. /// </summary> /// <param name="post">The Post to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Post.</returns> public System.Threading.Tasks.Task<Post> AddAsync(Post post, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Post>(post, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IConversationThreadPostsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IConversationThreadPostsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<ConversationThreadPostsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Expand(Expression<Func<Post, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Select(Expression<Func<Post, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IConversationThreadPostsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; using System.Collections.Generic; using System.Linq; using Imported.PeanutButter.Utils; namespace NExpect { /// <summary> /// Facilitates better difference highlighting per type /// </summary> public static class DifferenceHighlighting { private static readonly Dictionary<Type, List<Func<object, object, string>>> DifferenceHighlighters = new(); static DifferenceHighlighting() { AddDifferenceHighlighter<string>( CompareWhitespaceAndNewlines ); AddDifferenceHighlighter<string>( CompareCaseInsensitive ); AddDifferenceHighlighter<string>( HighlightFirstPositionOfDifference ); } private static string HighlightFirstPositionOfDifference( string left, string right ) { if (left is null || right is null) { return null; } var idx = FindIndexOfFirstDifference(left, right); var depth = 5; var from = idx - depth; if (from < 0) { from = 0; } var len = depth; if (from + len >= left.Length) { len = left.Length - from; } len = TruncateToNextNewLineIfTooClose(left, from, len); var arrowBodyLength = idx > depth ? depth : idx; if (arrowBodyLength > left.Length) { arrowBodyLength = left.Length; } var arrowBody = new String('-', arrowBodyLength); return $@"first difference found at character { idx } { left.Substring(from, len) } { arrowBody }^"; } private static int TruncateToNextNewLineIfTooClose( string left, int from, int len ) { var nextNewLine = left.IndexOf('\n', from); var nextLineFeed = left.IndexOf('\r', from); var closestLineEnding = Math.Min(nextNewLine, nextLineFeed); if (closestLineEnding < 0) { return len; } if (closestLineEnding < from + len) { len = closestLineEnding - from; } return len; } private static int FindIndexOfFirstDifference(string left, string right) { var charZip = left.ToCharArray().Zip(right.ToCharArray(), (c1, c2) => Tuple.Create(c1, c2)); var idx = 0; foreach (var pair in charZip) { if (pair.Item1 != pair.Item2) { break; } idx++; } return idx; } private static string CompareCaseInsensitive( string left, string right ) { if (left is null || right is null) { return null; } var caseDiff = string.Equals( left, right, StringComparison.InvariantCultureIgnoreCase ); return caseDiff ? "values have different casing" : null; } private static string CompareWhitespaceAndNewlines( string left, string right ) { if (left is null || right is null) { return null; } return FindNewLineIssues(left, right) ?? FindWhitespaceIssues(left, right); } private static string FindWhitespaceIssues(string left, string right) { var whitespaceDiff = left.RegexReplace("\\s*", " ") == right.RegexReplace("\\s*", " "); return whitespaceDiff ? "(values have whitespace differences)" : null; } private static string FindNewLineIssues(string left, string right) { var newlineDiff = left.RegexReplace("\r\n", "\n") == right.RegexReplace("\r\n", "\n"); return newlineDiff ? "(values have different line endings (CRLF vs LF))" : null; } /// <summary> /// Add a new difference highlighter, which will have output added /// to any existing difference highlighters /// </summary> /// <param name="generator"></param> /// <typeparam name="T"></typeparam> public static void AddDifferenceHighlighter<T>( Func<T, T, string> generator ) { lock (DifferenceHighlighters) { if (!DifferenceHighlighters.TryGetValue(typeof(T), out var highlighters)) { DifferenceHighlighters[typeof(T)] = highlighters = new List<Func<object, object, string>>(); } highlighters.Add((left, right) => { var leftCast = Cast<T>(left); var rightCast = Cast<T>(right); return generator(leftCast, rightCast); }); } } private static T Cast<T>(object value) { try { return (T)value; } catch { return default; } } internal static string ProvideMoreInfoFor<T>( T actual, T expected ) { lock (DifferenceHighlighters) { if (!DifferenceHighlighters.TryGetValue(typeof(T), out var highlighters)) { return null; } return string.Join(Environment.NewLine, highlighters .Select(h => TryInvoke(h, actual, expected)) .Where(line => line is not null) ); } } private static string TryInvoke<T>( Func<object, object, string> func, T actual, T expected ) { try { return func?.Invoke(actual, expected); } catch (Exception ex) { return $"Exception encountered whilst running difference highlighter: {ex.Message}"; } } } }
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 AssociationsOther.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; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Arch.CMessaging.Client.Newtonsoft.Json.Linq; using Arch.CMessaging.Client.Newtonsoft.Json; namespace Avro { /// <summary> /// Base class for all schema types /// </summary> public abstract class Schema { /// <summary> /// Enum for schema types /// </summary> public enum Type { Null, Boolean, Int, Long, Float, Double, Bytes, String, Record, Enumeration, Array, Map, Union, Fixed, Error } /// <summary> /// Schema type property /// </summary> public Type Tag { get; private set; } /// <summary> /// Additional JSON attributes apart from those defined in the AVRO spec /// </summary> internal PropertyMap Props { get; private set; } /// <summary> /// Constructor for schema class /// </summary> /// <param name="type"></param> protected Schema(Type type, PropertyMap props) { this.Tag = type; this.Props = props; } /// <summary> /// The name of this schema. If this is a named schema such as an enum, it returns the fully qualified /// name for the schema. For other schemas, it returns the type of the schema. /// </summary> public abstract string Name { get; } /// <summary> /// Static class to return new instance of schema object /// </summary> /// <param name="jtok">JSON object</param> /// <param name="names">list of named schemas already read</param> /// <param name="encspace">enclosing namespace of the schema</param> /// <returns>new Schema object</returns> internal static Schema ParseJson(JToken jtok, SchemaNames names, string encspace) { if (null == jtok) throw new ArgumentNullException("j", "j cannot be null."); if (jtok.Type == JTokenType.String) // primitive schema with no 'type' property or primitive or named type of a record field { string value = (string)jtok; PrimitiveSchema ps = PrimitiveSchema.NewInstance(value); if (null != ps) return ps; NamedSchema schema = null; if (names.TryGetValue(value, null, encspace, out schema)) return schema; throw new SchemaParseException("Undefined name: " + value); } if (jtok is JArray) // union schema with no 'type' property or union type for a record field return UnionSchema.NewInstance(jtok as JArray, null, names, encspace); if (jtok is JObject) // JSON object with open/close parenthesis, it must have a 'type' property { JObject jo = jtok as JObject; JToken jtype = jo["type"]; if (null == jtype) throw new SchemaParseException("Property type is required"); var props = Schema.GetProperties(jtok); if (jtype.Type == JTokenType.String) { string type = (string)jtype; if (type.Equals("array")) return ArraySchema.NewInstance(jtok, props, names, encspace); if (type.Equals("map")) return MapSchema.NewInstance(jtok, props, names, encspace); Schema schema = PrimitiveSchema.NewInstance((string)type, props); if (null != schema) return schema; return NamedSchema.NewInstance(jo, props, names, encspace); } else if (jtype.Type == JTokenType.Array) return UnionSchema.NewInstance(jtype as JArray, props, names, encspace); } throw new AvroTypeException("Invalid JSON for schema: " + jtok); } /// <summary> /// Parses a given JSON string to create a new schema object /// </summary> /// <param name="json">JSON string</param> /// <returns>new Schema object</returns> public static Schema Parse(string json) { if (string.IsNullOrEmpty(json)) throw new ArgumentNullException("json", "json cannot be null."); return Parse(json.Trim(), new SchemaNames(), null); // standalone schema, so no enclosing namespace } /// <summary> /// Parses a JSON string to create a new schema object /// </summary> /// <param name="json">JSON string</param> /// <param name="names">list of named schemas already read</param> /// <param name="encspace">enclosing namespace of the schema</param> /// <returns>new Schema object</returns> internal static Schema Parse(string json, SchemaNames names, string encspace) { Schema sc = PrimitiveSchema.NewInstance(json); if (null != sc) return sc; try { bool IsArray = json.StartsWith("[") && json.EndsWith("]"); JContainer j = IsArray ? (JContainer)JArray.Parse(json) : (JContainer)JObject.Parse(json); return ParseJson(j, names, encspace); } catch (Arch.CMessaging.Client.Newtonsoft.Json.JsonSerializationException ex) { throw new SchemaParseException("Could not parse. " + ex.Message + Environment.NewLine + json); } } /// <summary> /// Static function to parse custom properties (not defined in the Avro spec) from the given JSON object /// </summary> /// <param name="jtok">JSON object to parse</param> /// <returns>Property map if custom properties were found, null if no custom properties found</returns> internal static PropertyMap GetProperties(JToken jtok) { var props = new PropertyMap(); props.Parse(jtok); if (props.Count > 0) return props; else return null; } /// <summary> /// Returns the canonical JSON representation of this schema. /// </summary> /// <returns>The canonical JSON representation of this schema.</returns> public override string ToString() { System.IO.StringWriter sw = new System.IO.StringWriter(); Arch.CMessaging.Client.Newtonsoft.Json.JsonTextWriter writer = new Arch.CMessaging.Client.Newtonsoft.Json.JsonTextWriter(sw); if (this is PrimitiveSchema || this is UnionSchema) { writer.WriteStartObject(); writer.WritePropertyName("type"); } WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space if (this is PrimitiveSchema || this is UnionSchema) writer.WriteEndObject(); return sw.ToString(); } /// <summary> /// Writes opening { and 'type' property /// </summary> /// <param name="writer">JSON writer</param> private void writeStartObject(JsonTextWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("type"); writer.WriteValue(GetTypeString(this.Tag)); } /// <summary> /// Returns symbol name for the given schema type /// </summary> /// <param name="type">schema type</param> /// <returns>symbol name</returns> public static string GetTypeString(Type type) { if (type != Type.Enumeration) return type.ToString().ToLower(); return "enum"; } /// <summary> /// Default implementation for writing schema properties in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the schema</param> protected internal virtual void WriteJsonFields(JsonTextWriter writer, SchemaNames names, string encspace) { } /// <summary> /// Writes schema object in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the schema</param> protected internal virtual void WriteJson(JsonTextWriter writer, SchemaNames names, string encspace) { writeStartObject(writer); WriteJsonFields(writer, names, encspace); if (null != this.Props) Props.WriteJson(writer); writer.WriteEndObject(); } /// <summary> /// Returns the schema's custom property value given the property name /// </summary> /// <param name="key">custom property name</param> /// <returns>custom property value</returns> public string GetProperty(string key) { if (null == this.Props) return null; string v; return (this.Props.TryGetValue(key, out v)) ? v : null; } /// <summary> /// Hash code function /// </summary> /// <returns></returns> public override int GetHashCode() { return Tag.GetHashCode() + getHashCode(Props); } /// <summary> /// Returns true if and only if data written using writerSchema can be read using the current schema /// according to the Avro resolution rules. /// </summary> /// <param name="writerSchema">The writer's schema to match against.</param> /// <returns>True if and only if the current schema matches the writer's.</returns> public virtual bool CanRead(Schema writerSchema) { return Tag == writerSchema.Tag; } /// <summary> /// Compares two objects, null is equal to null /// </summary> /// <param name="o1">first object</param> /// <param name="o2">second object</param> /// <returns>true if two objects are equal, false otherwise</returns> protected static bool areEqual(object o1, object o2) { return o1 == null ? o2 == null : o1.Equals(o2); } /// <summary> /// Hash code helper function /// </summary> /// <param name="obj"></param> /// <returns></returns> protected static int getHashCode(object obj) { return obj == null ? 0 : obj.GetHashCode(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ // Uncomment to turn on logging of non-dictionary strings written to binary writers. // This can help identify element/attribute name/ns that could be written as XmlDictionaryStrings to get better compactness and performance. // #define LOG_NON_DICTIONARY_WRITES namespace System.Xml { using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.Text; public interface IXmlBinaryWriterInitializer { void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream); } class XmlBinaryNodeWriter : XmlStreamNodeWriter { IXmlDictionary dictionary; XmlBinaryWriterSession session; bool inAttribute; bool inList; bool wroteAttributeValue; AttributeValue attributeValue; const int maxBytesPerChar = 3; int textNodeOffset; public XmlBinaryNodeWriter() { // Sanity check on node values Fx.Assert(XmlBinaryNodeType.MaxAttribute < XmlBinaryNodeType.MinElement && XmlBinaryNodeType.MaxElement < XmlBinaryNodeType.MinText && (int)XmlBinaryNodeType.MaxText < 256, "NodeTypes enumeration messed up"); } public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) { this.dictionary = dictionary; this.session = session; this.inAttribute = false; this.inList = false; this.attributeValue.Clear(); this.textNodeOffset = -1; SetOutput(stream, ownsStream, null); } void WriteNode(XmlBinaryNodeType nodeType) { WriteByte((byte)nodeType); textNodeOffset = -1; } void WroteAttributeValue() { if (wroteAttributeValue && !inList) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlOnlySingleValue))); wroteAttributeValue = true; } void WriteTextNode(XmlBinaryNodeType nodeType) { if (inAttribute) WroteAttributeValue(); Fx.Assert(nodeType >= XmlBinaryNodeType.MinText && nodeType <= XmlBinaryNodeType.MaxText && ((byte)nodeType & 1) == 0, "Invalid nodeType"); WriteByte((byte)nodeType); textNodeOffset = this.BufferOffset - 1; } byte[] GetTextNodeBuffer(int size, out int offset) { if (inAttribute) WroteAttributeValue(); byte[] buffer = GetBuffer(size, out offset); textNodeOffset = offset; return buffer; } void WriteTextNodeWithLength(XmlBinaryNodeType nodeType, int length) { Fx.Assert(nodeType == XmlBinaryNodeType.Chars8Text || nodeType == XmlBinaryNodeType.Bytes8Text || nodeType == XmlBinaryNodeType.UnicodeChars8Text, ""); int offset; byte[] buffer = GetTextNodeBuffer(5, out offset); if (length < 256) { buffer[offset + 0] = (byte)nodeType; buffer[offset + 1] = (byte)length; Advance(2); } else if (length < 65536) { buffer[offset + 0] = (byte)(nodeType + 1 * 2); // WithEndElements interleave buffer[offset + 1] = (byte)length; length >>= 8; buffer[offset + 2] = (byte)length; Advance(3); } else { buffer[offset + 0] = (byte)(nodeType + 2 * 2); // WithEndElements interleave buffer[offset + 1] = (byte)length; length >>= 8; buffer[offset + 2] = (byte)length; length >>= 8; buffer[offset + 3] = (byte)length; length >>= 8; buffer[offset + 4] = (byte)length; Advance(5); } } void WriteTextNodeWithInt64(XmlBinaryNodeType nodeType, Int64 value) { int offset; byte[] buffer = GetTextNodeBuffer(9, out offset); buffer[offset + 0] = (byte)nodeType; buffer[offset + 1] = (byte)value; value >>= 8; buffer[offset + 2] = (byte)value; value >>= 8; buffer[offset + 3] = (byte)value; value >>= 8; buffer[offset + 4] = (byte)value; value >>= 8; buffer[offset + 5] = (byte)value; value >>= 8; buffer[offset + 6] = (byte)value; value >>= 8; buffer[offset + 7] = (byte)value; value >>= 8; buffer[offset + 8] = (byte)value; Advance(9); } public override void WriteDeclaration() { } public override void WriteStartElement(string prefix, string localName) { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortElement); WriteName(localName); } else { char ch = prefix[0]; if (prefix.Length == 1 && ch >= 'a' && ch <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixElementA, ch - 'a'); WriteName(localName); } else { WriteNode(XmlBinaryNodeType.Element); WriteName(prefix); WriteName(localName); } } } void WritePrefixNode(XmlBinaryNodeType nodeType, int ch) { WriteNode((XmlBinaryNodeType)((int)nodeType + ch)); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { int key; if (!TryGetKey(localName, out key)) { #if LOG_NON_DICTIONARY_WRITES XmlBinaryWriter.OnNonDictionaryWrite("WriteStartElement", true, localName.Value, "..."); #endif WriteStartElement(prefix, localName.Value); } else { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryElement); WriteDictionaryString(localName, key); } else { char ch = prefix[0]; if (prefix.Length == 1 && ch >= 'a' && ch <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryElementA, ch - 'a'); WriteDictionaryString(localName, key); } else { WriteNode(XmlBinaryNodeType.DictionaryElement); WriteName(prefix); WriteDictionaryString(localName, key); } } } } public override void WriteEndStartElement(bool isEmpty) { if (isEmpty) { WriteEndElement(); } } public override void WriteEndElement(string prefix, string localName) { WriteEndElement(); } void WriteEndElement() { if (textNodeOffset != -1) { byte[] buffer = this.StreamBuffer; XmlBinaryNodeType nodeType = (XmlBinaryNodeType)buffer[textNodeOffset]; Fx.Assert(nodeType >= XmlBinaryNodeType.MinText && nodeType <= XmlBinaryNodeType.MaxText && ((byte)nodeType & 1) == 0, ""); buffer[textNodeOffset] = (byte)(nodeType + 1); textNodeOffset = -1; } else { WriteNode(XmlBinaryNodeType.EndElement); } } public override void WriteStartAttribute(string prefix, string localName) { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortAttribute); WriteName(localName); } else { char ch = prefix[0]; if (prefix.Length == 1 && ch >= 'a' && ch <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixAttributeA, ch - 'a'); WriteName(localName); } else { WriteNode(XmlBinaryNodeType.Attribute); WriteName(prefix); WriteName(localName); } } inAttribute = true; wroteAttributeValue = false; } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { int key; if (!TryGetKey(localName, out key)) { #if LOG_NON_DICTIONARY_WRITES XmlBinaryWriter.OnNonDictionaryWrite("WriteStartAttribute", true, localName.Value, "..."); #endif WriteStartAttribute(prefix, localName.Value); } else { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryAttribute); WriteDictionaryString(localName, key); } else { char ch = prefix[0]; if (prefix.Length == 1 && ch >= 'a' && ch <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryAttributeA, ch - 'a'); WriteDictionaryString(localName, key); } else { WriteNode(XmlBinaryNodeType.DictionaryAttribute); WriteName(prefix); WriteDictionaryString(localName, key); } } inAttribute = true; wroteAttributeValue = false; } } public override void WriteEndAttribute() { inAttribute = false; if (!wroteAttributeValue) { attributeValue.WriteTo(this); } textNodeOffset = -1; } public override void WriteXmlnsAttribute(string prefix, string ns) { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortXmlnsAttribute); WriteName(ns); } else { WriteNode(XmlBinaryNodeType.XmlnsAttribute); WriteName(prefix); WriteName(ns); } } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { int key; if (!TryGetKey(ns, out key)) { WriteXmlnsAttribute(prefix, ns.Value); } else { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryXmlnsAttribute); WriteDictionaryString(ns, key); } else { WriteNode(XmlBinaryNodeType.DictionaryXmlnsAttribute); WriteName(prefix); WriteDictionaryString(ns, key); } } } bool TryGetKey(XmlDictionaryString s, out int key) { key = -1; if (s.Dictionary == dictionary) { key = s.Key * 2; return true; } XmlDictionaryString t; if (dictionary != null && dictionary.TryLookup(s, out t)) { Fx.Assert(t.Dictionary == dictionary, ""); key = t.Key * 2; return true; } if (session == null) return false; int sessionKey; if (!session.TryLookup(s, out sessionKey)) { if (!session.TryAdd(s, out sessionKey)) return false; } key = sessionKey * 2 + 1; return true; } void WriteDictionaryString(XmlDictionaryString s, int key) { WriteMultiByteInt32(key); } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe void WriteName(string s) { int length = s.Length; if (length == 0) { WriteByte(0); } else { fixed (char* pch = s) { UnsafeWriteName(pch, length); } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")] [SecurityCritical] unsafe void UnsafeWriteName(char* chars, int charCount) { if (charCount < 128 / maxBytesPerChar) { // Optimize if we know we can fit the converted string in the buffer // so we don't have to make a pass to count the bytes // 1 byte for the length int offset; byte[] buffer = GetBuffer(1 + charCount * maxBytesPerChar, out offset); int length = UnsafeGetUTF8Chars(chars, charCount, buffer, offset + 1); Fx.Assert(length < 128, ""); buffer[offset] = (byte)length; Advance(1 + length); } else { int byteCount = UnsafeGetUTF8Length(chars, charCount); WriteMultiByteInt32(byteCount); UnsafeWriteUTF8Chars(chars, charCount); } } void WriteMultiByteInt32(int i) { int offset; byte[] buffer = GetBuffer(5, out offset); int startOffset = offset; while ((i & 0xFFFFFF80) != 0) { buffer[offset++] = (byte)((i & 0x7F) | 0x80); i >>= 7; } buffer[offset++] = (byte)i; Advance(offset - startOffset); } public override void WriteComment(string value) { WriteNode(XmlBinaryNodeType.Comment); WriteName(value); } public override void WriteCData(string value) { WriteText(value); } void WriteEmptyText() { WriteTextNode(XmlBinaryNodeType.EmptyText); } public override void WriteBoolText(bool value) { if (value) { WriteTextNode(XmlBinaryNodeType.TrueText); } else { WriteTextNode(XmlBinaryNodeType.FalseText); } } public override void WriteInt32Text(int value) { if (value >= -128 && value < 128) { if (value == 0) { WriteTextNode(XmlBinaryNodeType.ZeroText); } else if (value == 1) { WriteTextNode(XmlBinaryNodeType.OneText); } else { int offset; byte[] buffer = GetTextNodeBuffer(2, out offset); buffer[offset + 0] = (byte)XmlBinaryNodeType.Int8Text; buffer[offset + 1] = (byte)value; Advance(2); } } else if (value >= -32768 && value < 32768) { int offset; byte[] buffer = GetTextNodeBuffer(3, out offset); buffer[offset + 0] = (byte)XmlBinaryNodeType.Int16Text; buffer[offset + 1] = (byte)value; value >>= 8; buffer[offset + 2] = (byte)value; Advance(3); } else { int offset; byte[] buffer = GetTextNodeBuffer(5, out offset); buffer[offset + 0] = (byte)XmlBinaryNodeType.Int32Text; buffer[offset + 1] = (byte)value; value >>= 8; buffer[offset + 2] = (byte)value; value >>= 8; buffer[offset + 3] = (byte)value; value >>= 8; buffer[offset + 4] = (byte)value; Advance(5); } } public override void WriteInt64Text(Int64 value) { if (value >= int.MinValue && value <= int.MaxValue) { WriteInt32Text((int)value); } else { WriteTextNodeWithInt64(XmlBinaryNodeType.Int64Text, value); } } public override void WriteUInt64Text(UInt64 value) { if (value <= Int64.MaxValue) { WriteInt64Text((Int64)value); } else { WriteTextNodeWithInt64(XmlBinaryNodeType.UInt64Text, (Int64)value); } } void WriteInt64(Int64 value) { int offset; byte[] buffer = GetBuffer(8, out offset); buffer[offset + 0] = (byte)value; value >>= 8; buffer[offset + 1] = (byte)value; value >>= 8; buffer[offset + 2] = (byte)value; value >>= 8; buffer[offset + 3] = (byte)value; value >>= 8; buffer[offset + 4] = (byte)value; value >>= 8; buffer[offset + 5] = (byte)value; value >>= 8; buffer[offset + 6] = (byte)value; value >>= 8; buffer[offset + 7] = (byte)value; Advance(8); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count) { if (inAttribute) { attributeValue.WriteBase64Text(trailBytes, trailByteCount, base64Buffer, base64Offset, base64Count); } else { int length = trailByteCount + base64Count; if (length > 0) { WriteTextNodeWithLength(XmlBinaryNodeType.Bytes8Text, length); if (trailByteCount > 0) { int offset; byte[] buffer = GetBuffer(trailByteCount, out offset); for (int i = 0; i < trailByteCount; i++) buffer[offset + i] = trailBytes[i]; Advance(trailByteCount); } if (base64Count > 0) { WriteBytes(base64Buffer, base64Offset, base64Count); } } else { WriteEmptyText(); } } } public override void WriteText(XmlDictionaryString value) { if (inAttribute) { attributeValue.WriteText(value); } else { int key; if (!TryGetKey(value, out key)) { WriteText(value.Value); } else { WriteTextNode(XmlBinaryNodeType.DictionaryText); WriteDictionaryString(value, key); } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteText(string value) { if (inAttribute) { attributeValue.WriteText(value); } else { if (value.Length > 0) { fixed (char* pch = value) { UnsafeWriteText(pch, value.Length); } } else { WriteEmptyText(); } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteText(char[] chars, int offset, int count) { if (inAttribute) { attributeValue.WriteText(new string(chars, offset, count)); } else { if (count > 0) { fixed (char* pch = &chars[offset]) { UnsafeWriteText(pch, count); } } else { WriteEmptyText(); } } } public override void WriteText(byte[] chars, int charOffset, int charCount) { WriteTextNodeWithLength(XmlBinaryNodeType.Chars8Text, charCount); WriteBytes(chars, charOffset, charCount); } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")] [SecurityCritical] unsafe void UnsafeWriteText(char* chars, int charCount) { // Callers should handle zero Fx.Assert(charCount > 0, ""); if (charCount == 1) { char ch = chars[0]; if (ch == '0') { WriteTextNode(XmlBinaryNodeType.ZeroText); return; } if (ch == '1') { WriteTextNode(XmlBinaryNodeType.OneText); return; } } if (charCount <= byte.MaxValue / maxBytesPerChar) { // Optimize if we know we can fit the converted string in the buffer // so we don't have to make a pass to count the bytes int offset; byte[] buffer = GetBuffer(1 + 1 + charCount * maxBytesPerChar, out offset); int length = UnsafeGetUTF8Chars(chars, charCount, buffer, offset + 2); if (length / 2 <= charCount) { buffer[offset] = (byte)XmlBinaryNodeType.Chars8Text; } else { buffer[offset] = (byte)XmlBinaryNodeType.UnicodeChars8Text; length = UnsafeGetUnicodeChars(chars, charCount, buffer, offset + 2); } textNodeOffset = offset; Fx.Assert(length <= byte.MaxValue, ""); buffer[offset + 1] = (byte)length; Advance(2 + length); } else { int byteCount = UnsafeGetUTF8Length(chars, charCount); if (byteCount / 2 > charCount) { WriteTextNodeWithLength(XmlBinaryNodeType.UnicodeChars8Text, charCount * 2); UnsafeWriteUnicodeChars(chars, charCount); } else { WriteTextNodeWithLength(XmlBinaryNodeType.Chars8Text, byteCount); UnsafeWriteUTF8Chars(chars, charCount); } } } public override void WriteEscapedText(string value) { WriteText(value); } public override void WriteEscapedText(XmlDictionaryString value) { WriteText(value); } public override void WriteEscapedText(char[] chars, int offset, int count) { WriteText(chars, offset, count); } public override void WriteEscapedText(byte[] chars, int offset, int count) { WriteText(chars, offset, count); } public override void WriteCharEntity(int ch) { if (ch > char.MaxValue) { SurrogateChar sch = new SurrogateChar(ch); char[] chars = new char[2] { sch.HighChar, sch.LowChar, }; WriteText(chars, 0, 2); } else { char[] chars = new char[1] { (char)ch }; WriteText(chars, 0, 1); } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteFloatText(float f) { long l; if (f >= long.MinValue && f <= long.MaxValue && (l = (long)f) == f) { WriteInt64Text(l); } else { int offset; byte[] buffer = GetTextNodeBuffer(1 + sizeof(float), out offset); byte* bytes = (byte*)&f; buffer[offset + 0] = (byte)XmlBinaryNodeType.FloatText; buffer[offset + 1] = bytes[0]; buffer[offset + 2] = bytes[1]; buffer[offset + 3] = bytes[2]; buffer[offset + 4] = bytes[3]; Advance(1 + sizeof(float)); } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteDoubleText(double d) { float f; if (d >= float.MinValue && d <= float.MaxValue && (f = (float)d) == d) { WriteFloatText(f); } else { int offset; byte[] buffer = GetTextNodeBuffer(1 + sizeof(double), out offset); byte* bytes = (byte*)&d; buffer[offset + 0] = (byte)XmlBinaryNodeType.DoubleText; buffer[offset + 1] = bytes[0]; buffer[offset + 2] = bytes[1]; buffer[offset + 3] = bytes[2]; buffer[offset + 4] = bytes[3]; buffer[offset + 5] = bytes[4]; buffer[offset + 6] = bytes[5]; buffer[offset + 7] = bytes[6]; buffer[offset + 8] = bytes[7]; Advance(1 + sizeof(double)); } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteDecimalText(decimal d) { int offset; byte[] buffer = GetTextNodeBuffer(1 + sizeof(decimal), out offset); byte* bytes = (byte*)&d; buffer[offset++] = (byte)XmlBinaryNodeType.DecimalText; for (int i = 0; i < sizeof(decimal); i++) { buffer[offset++] = bytes[i]; } Advance(1 + sizeof(decimal)); } public override void WriteDateTimeText(DateTime dt) { WriteTextNodeWithInt64(XmlBinaryNodeType.DateTimeText, dt.ToBinary()); } public override void WriteUniqueIdText(UniqueId value) { if (value.IsGuid) { int offset; byte[] buffer = GetTextNodeBuffer(17, out offset); buffer[offset] = (byte)XmlBinaryNodeType.UniqueIdText; value.TryGetGuid(buffer, offset + 1); Advance(17); } else { WriteText(value.ToString()); } } public override void WriteGuidText(Guid guid) { int offset; byte[] buffer = GetTextNodeBuffer(17, out offset); buffer[offset] = (byte)XmlBinaryNodeType.GuidText; Buffer.BlockCopy(guid.ToByteArray(), 0, buffer, offset + 1, 16); Advance(17); } public override void WriteTimeSpanText(TimeSpan value) { WriteTextNodeWithInt64(XmlBinaryNodeType.TimeSpanText, value.Ticks); } public override void WriteStartListText() { Fx.Assert(!inList, ""); inList = true; WriteNode(XmlBinaryNodeType.StartListText); } public override void WriteListSeparator() { } public override void WriteEndListText() { Fx.Assert(inList, ""); inList = false; wroteAttributeValue = true; WriteNode(XmlBinaryNodeType.EndListText); } public void WriteArrayNode() { WriteNode(XmlBinaryNodeType.Array); } void WriteArrayInfo(XmlBinaryNodeType nodeType, int count) { WriteNode(nodeType); WriteMultiByteInt32(count); } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")] [SecurityCritical] unsafe public void UnsafeWriteArray(XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteArrayInfo(nodeType, count); UnsafeWriteArray(array, (int)(arrayMax - array)); } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")] [SecurityCritical] unsafe void UnsafeWriteArray(byte* array, int byteCount) { base.UnsafeWriteBytes(array, byteCount); } public void WriteDateTimeArray(DateTime[] array, int offset, int count) { WriteArrayInfo(XmlBinaryNodeType.DateTimeTextWithEndElement, count); for (int i = 0; i < count; i++) { WriteInt64(array[offset + i].ToBinary()); } } public void WriteGuidArray(Guid[] array, int offset, int count) { WriteArrayInfo(XmlBinaryNodeType.GuidTextWithEndElement, count); for (int i = 0; i < count; i++) { byte[] buffer = array[offset + i].ToByteArray(); WriteBytes(buffer, 0, 16); } } public void WriteTimeSpanArray(TimeSpan[] array, int offset, int count) { WriteArrayInfo(XmlBinaryNodeType.TimeSpanTextWithEndElement, count); for (int i = 0; i < count; i++) { WriteInt64(array[offset + i].Ticks); } } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { if (prefix.Length == 0) { WriteText(localName); } else { char ch = prefix[0]; int key; if (prefix.Length == 1 && (ch >= 'a' && ch <= 'z') && TryGetKey(localName, out key)) { WriteTextNode(XmlBinaryNodeType.QNameDictionaryText); WriteByte((byte)(ch - 'a')); WriteDictionaryString(localName, key); } else { WriteText(prefix); WriteText(":"); WriteText(localName); } } } protected override void FlushBuffer() { base.FlushBuffer(); textNodeOffset = -1; } public override void Close() { base.Close(); attributeValue.Clear(); } struct AttributeValue { string captureText; XmlDictionaryString captureXText; MemoryStream captureStream; public void Clear() { captureText = null; captureXText = null; captureStream = null; } public void WriteText(string s) { if (captureStream != null) { captureText = XmlConverter.Base64Encoding.GetString(captureStream.GetBuffer(), 0, (int)captureStream.Length); captureStream = null; } if (captureXText != null) { captureText = captureXText.Value; captureXText = null; } if (captureText == null || captureText.Length == 0) { captureText = s; } else { captureText += s; } } public void WriteText(XmlDictionaryString s) { if (captureText != null || captureStream != null) { WriteText(s.Value); } else { captureXText = s; } } public void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (captureText != null || captureXText != null) { if (trailByteCount > 0) { WriteText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount)); } WriteText(XmlConverter.Base64Encoding.GetString(buffer, offset, count)); } else { if (captureStream == null) captureStream = new MemoryStream(); if (trailByteCount > 0) captureStream.Write(trailBytes, 0, trailByteCount); captureStream.Write(buffer, offset, count); } } public void WriteTo(XmlBinaryNodeWriter writer) { if (captureText != null) { writer.WriteText(captureText); captureText = null; } else if (captureXText != null) { writer.WriteText(captureXText); captureXText = null; } else if (captureStream != null) { writer.WriteBase64Text(null, 0, captureStream.GetBuffer(), 0, (int)captureStream.Length); captureStream = null; } else { writer.WriteEmptyText(); } } } } class XmlBinaryWriter : XmlBaseWriter, IXmlBinaryWriterInitializer { XmlBinaryNodeWriter writer; char[] chars; byte[] bytes; #if LOG_NON_DICTIONARY_WRITES static readonly bool logCallStackOnNonDictionaryWrites = true; static readonly bool logWriteStringNonDictionaryWrites = true; internal static void OnNonDictionaryWrite(string apiName, bool isDictionaryMismatchIssue, string s1, string s2) { StringBuilder log = new StringBuilder(); log.AppendFormat("> Text string write in binary: {0}(\"{1}\"", apiName, s1); if (s2 != null) log.AppendFormat(", \"{0}\"", s2); log.AppendLine(")"); if (isDictionaryMismatchIssue) { log.AppendLine(" Issue: Dictionary mismatch between XmlDictionaryWriter and XmlDictionaryString"); } if (logCallStackOnNonDictionaryWrites) { string callStack = new System.Diagnostics.StackTrace().ToString(); log.AppendLine(" Callstack:"); log.AppendFormat("{0}", callStack.Substring(callStack.IndexOf(Environment.NewLine) + Environment.NewLine.Length)); } Console.WriteLine("{0}", log); } public override void WriteStartAttribute(string prefix, string localName, string namespaceUri) { OnNonDictionaryWrite("WriteStartAttribute", false, localName, namespaceUri); base.WriteStartAttribute(prefix, localName, namespaceUri); } public override void WriteStartElement(string prefix, string localName, string namespaceUri) { OnNonDictionaryWrite("WriteStartElement", false, localName, namespaceUri); base.WriteStartElement(prefix, localName, namespaceUri); } public override void WriteString(string value) { if (logWriteStringNonDictionaryWrites && !typeof(XmlBinaryWriter).Assembly.Equals(System.Reflection.Assembly.GetCallingAssembly())) OnNonDictionaryWrite("WriteString", false, value, null); base.WriteString(value); } #endif public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream")); if (writer == null) writer = new XmlBinaryNodeWriter(); writer.SetOutput(stream, dictionary, session, ownsStream); SetOutput(writer); } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(false); } protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute) { Type type = reader.ValueType; if (type == typeof(string)) { XmlDictionaryString value; if (reader.TryGetValueAsDictionaryString(out value)) { WriteString(value); } else { if (reader.CanReadValueChunk) { if (chars == null) { chars = new char[256]; } int count; while ((count = reader.ReadValueChunk(chars, 0, chars.Length)) > 0) { this.WriteChars(chars, 0, count); } } else { WriteString(reader.Value); } } if (!attribute) { reader.Read(); } } else if (type == typeof(byte[])) { if (reader.CanReadBinaryContent) { // Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text if (bytes == null) { bytes = new byte[384]; } int count; while ((count = reader.ReadValueAsBase64(bytes, 0, bytes.Length)) > 0) { this.WriteBase64(bytes, 0, count); } } else { WriteString(reader.Value); } if (!attribute) { reader.Read(); } } else if (type == typeof(int)) WriteValue(reader.ReadContentAsInt()); else if (type == typeof(long)) WriteValue(reader.ReadContentAsLong()); else if (type == typeof(bool)) WriteValue(reader.ReadContentAsBoolean()); else if (type == typeof(double)) WriteValue(reader.ReadContentAsDouble()); else if (type == typeof(DateTime)) WriteValue(reader.ReadContentAsDateTime()); else if (type == typeof(float)) WriteValue(reader.ReadContentAsFloat()); else if (type == typeof(decimal)) WriteValue(reader.ReadContentAsDecimal()); else if (type == typeof(UniqueId)) WriteValue(reader.ReadContentAsUniqueId()); else if (type == typeof(Guid)) WriteValue(reader.ReadContentAsGuid()); else if (type == typeof(TimeSpan)) WriteValue(reader.ReadContentAsTimeSpan()); else WriteValue(reader.ReadContentAsObject()); } void WriteStartArray(string prefix, string localName, string namespaceUri, int count) { StartArray(count); writer.WriteArrayNode(); WriteStartElement(prefix, localName, namespaceUri); WriteEndElement(); } void WriteStartArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int count) { StartArray(count); writer.WriteArrayNode(); WriteStartElement(prefix, localName, namespaceUri); WriteEndElement(); } void WriteEndArray() { EndArray(); } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")] [SecurityCritical] unsafe void UnsafeWriteArray(string prefix, string localName, string namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); writer.UnsafeWriteArray(nodeType, count, array, arrayMax); WriteEndArray(); } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")] [SecurityCritical] unsafe void UnsafeWriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); writer.UnsafeWriteArray(nodeType, count, array, arrayMax); WriteEndArray(); } void CheckArray(Array array, int offset, int count) { if (array == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative))); if (offset > array.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, array.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative))); if (count > array.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, array.Length - offset))); } // bool [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (bool* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (bool* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // Int16 [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, Int16[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (Int16* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (Int16* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // Int32 [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, Int32[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (Int32* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (Int32* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // Int64 [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, Int64[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (Int64* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (Int64* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // float [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (float* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (float* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // double [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (double* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (double* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // decimal [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (decimal* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { fixed (decimal* items = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement, count, (byte*)items, (byte*)&items[count]); } } } } // DateTime public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteDateTimeArray(array, offset, count); WriteEndArray(); } } } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteDateTimeArray(array, offset, count); WriteEndArray(); } } } // Guid public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteGuidArray(array, offset, count); WriteEndArray(); } } } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteGuidArray(array, offset, count); WriteEndArray(); } } } // TimeSpan public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteTimeSpanArray(array, offset, count); WriteEndArray(); } } } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { if (Signing) base.WriteArray(prefix, localName, namespaceUri, array, offset, count); else { CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteTimeSpanArray(array, offset, count); WriteEndArray(); } } } } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Bluetooth.Msft.BluetoothClient // // Copyright (c) 2003-2008 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License //#define WIN32_READ_BTH_DEVICE_INFO using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using Microsoft.Win32; using InTheHand.Net.Bluetooth.Factory; using InTheHand.Net.Sockets; using InTheHand.Runtime.InteropServices; using AsyncResult_BeginDiscoverDevices = InTheHand.Net.AsyncResult< InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo[], InTheHand.Net.Bluetooth.Msft.SocketBluetoothClient.DiscoDevsParamsWithLive>; using List_IBluetoothDeviceInfo = System.Collections.Generic.List<InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo>; using InTheHand.SystemCore; namespace InTheHand.Net.Bluetooth.Msft { class SocketBluetoothClient : IBluetoothClient { readonly BluetoothFactory _fcty; private bool cleanedUp = false; private ISocketOptionHelper m_optionHelper; #if WinXP // If SetPin(String) is called before connect we need to know the remote // address to start the BluetoothWin32Authenticator for, so store this // so we can start the authenticator at connect-time. string m_pinForConnect; #endif #region Constructor #if NETCF static SocketBluetoothClient() { InTheHand.Net.PlatformVerification.ThrowException(); } #endif internal SocketBluetoothClient(BluetoothFactory fcty) { Debug.Assert(fcty != null, "ArgNull"); _fcty = fcty; try { this.Client = CreateSocket(); } catch (SocketException se) { throw new PlatformNotSupportedException("32feet.NET does not support the Bluetooth stack on this device.", se); } m_optionHelper = CreateSocketOptionHelper(this.Client); } internal SocketBluetoothClient(BluetoothFactory fcty, BluetoothEndPoint localEP) : this(fcty) { if (localEP == null) { throw new ArgumentNullException("localEP"); } //bind to specific local endpoint var bindEP = PrepareBindEndPoint(localEP); this.Client.Bind(bindEP); } internal SocketBluetoothClient(BluetoothFactory fcty, Socket acceptedSocket) { Debug.Assert(fcty != null, "ArgNull"); _fcty = fcty; this.Client = acceptedSocket; active = true; m_optionHelper = CreateSocketOptionHelper(this.Client); } protected virtual Socket CreateSocket() { return new Socket(BluetoothAddressFamily, SocketType.Stream, BluetoothProtocolType.RFComm); } protected virtual AddressFamily BluetoothAddressFamily { get { return AddressFamily32.Bluetooth; } } protected virtual BluetoothEndPoint PrepareConnectEndPoint(BluetoothEndPoint serverEP) { return serverEP; } protected virtual BluetoothEndPoint PrepareBindEndPoint(BluetoothEndPoint serverEP) { return serverEP; } protected virtual ISocketOptionHelper CreateSocketOptionHelper(Socket socket) { return new MsftSocketOptionHelper(socket); } #endregion #region InquiryAccessCode private int iac = BluetoothAddress.Giac; //0x9E8B33; #if NETCF /// <summary> /// /// </summary> public int InquiryAccessCode { get { return iac; } set { iac = value; } } #else public int InquiryAccessCode { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endif #endregion #region Query Length //length of time for query private TimeSpan inquiryLength = new TimeSpan(0, 0, 10); /// <summary> /// Amount of time allowed to perform the query. /// </summary> /// <remarks>On Windows CE the actual value used is expressed in units of 1.28 seconds, so will be the nearest match for the value supplied. /// The default value is 10 seconds. The maximum is 60 seconds.</remarks> public TimeSpan InquiryLength { get { return inquiryLength; } set { if ((value.TotalSeconds > 0) && (value.TotalSeconds <= 60)) { inquiryLength = value; } else { throw new ArgumentOutOfRangeException("value", "QueryLength must be a positive timespan between 0 and 60 seconds."); } } } #endregion #region Discover Devices /// <summary> /// Discovers accessible Bluetooth devices and returns their names and addresses. /// </summary> /// <param name="maxDevices">The maximum number of devices to get information about.</param> /// <param name="authenticated">True to return previously authenticated/paired devices.</param> /// <param name="remembered">True to return remembered devices.</param> /// <param name="unknown">True to return previously unknown devices.</param> /// <param name="discoverableOnly">True to return only discoverable devices /// (where both in range and in discoverable mode). /// When <see langword="true"/> all other flags are ignored. /// <strong>Note: Does NOT work on Win32 with the Microsoft stack.</strong> /// </param> /// <returns>An array of BluetoothDeviceInfo objects describing the devices discovered.</returns> /// - /// <remarks> /// <para>The <see paramref="discoverableOnly"/> flag will discover only /// the devices that are in range and are in discoverable mode. This works /// only on WM/CE with the Microsoft stack, or on any platform with the /// Widcomm stack. /// </para> /// <para> /// It does not work on desktop Windows with the Microsoft /// stack, where the in range and remembered devices are returned already /// merged! There simple all devices will be returned. Even the /// <see cref="InTheHand.Net.Sockets.BluetoothDeviceInfo.LastSeen">BluetoothDeviceInfo.LastSeen</see> /// property is of no use there: on XP and Vista at least the value provided /// is always simply the current time. /// </para> /// </remarks> IBluetoothDeviceInfo[] IBluetoothClient.DiscoverDevices(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly) { return DiscoverDevices(maxDevices, authenticated, remembered, unknown, discoverableOnly, null, null); } public virtual IBluetoothDeviceInfo[] DiscoverDevices(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly, InTheHand.Net.Sockets.BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState) { #if !NETCF // In the MSFT+Win32 API there's no simple way to get only the // in-range-discoverable devices, and thus it can't provide // 'discoverableOnly' nor live discovery. So, we register for the // native event whilst we run a normal discovery. We use the // native event to raise our live event and to gather the devices // to be included in the discoverableOnly result. // Note the event seems NOT be raised on WinXP in this case. // The event (on Win7 at least) raises lots of apparently duplicate // events, so we need to do some filtering for both results. var realLiveDiscoHandler = liveDiscoHandler; //if (realLiveDiscoHandler != null) Debug.Assert(discoverableOnly || unknown, "You want live events from 'remembered'?!?"); bool keepDiscoOnly = false; if (discoverableOnly) { keepDiscoOnly = true; unknown = authenticated = remembered = true; discoverableOnly = false; } BluetoothWin32Events events; EventHandler<BluetoothWin32RadioInRangeEventArgs> radioInRangeHandler; List<IBluetoothDeviceInfo> seenDevices; if (keepDiscoOnly || realLiveDiscoHandler != null) { events = BluetoothWin32Events.GetInstance(); seenDevices = new List<IBluetoothDeviceInfo>(); radioInRangeHandler = delegate(object sender, BluetoothWin32RadioInRangeEventArgs e) { var newdevice = e.DeviceWindows; Debug.WriteLine("Radio in range: " + newdevice.DeviceAddress); bool unique = BluetoothDeviceInfo.AddUniqueDevice(seenDevices, newdevice); if (unique && realLiveDiscoHandler != null) { Debug.WriteLine("Live IS unique."); realLiveDiscoHandler(newdevice, liveDiscoState); } else { //COVERAGE Debug.WriteLine("Live is NOT unique (" + unique + "," + realLiveDiscoHandler != null + ")."); } }; events.InRange += radioInRangeHandler; } else { events = null; radioInRangeHandler = null; seenDevices = null; } // Don't use the WM live-disco functionality. liveDiscoHandler = null; #endif IBluetoothDeviceInfo[] result; try { result = DoDiscoverDevices(maxDevices, authenticated, remembered, unknown, discoverableOnly, liveDiscoHandler, liveDiscoState); } finally { #if !NETCF if (events != null && radioInRangeHandler != null) { events.InRange -= radioInRangeHandler; } #endif } #if !NETCF if (keepDiscoOnly) { Debug.Assert(seenDevices != null, "Should have created list 'seenDevices' above!"); Debug.WriteLine("Disco result: " + result.Length + ", liveDevice: " + seenDevices.Count); result = BluetoothDeviceInfo.Intersect(result, seenDevices); Debug.WriteLine("Result result: " + result.Length); } #endif return result; } IBluetoothDeviceInfo[] DoDiscoverDevices(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly, InTheHand.Net.Sockets.BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState) { WqsOffset.AssertCheckLayout(); CsaddrInfoOffsets.AssertCheckLayout(); // #if !NETCF Debug.Assert(liveDiscoHandler == null, "Don't use the NETCF live-disco feature on Win32!"); #endif #if WinXP const bool Win32DiscoverableOnlyIncludesAllDevices = false; #endif var prototype = new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.Empty); int discoveredDevices = 0; List_IBluetoothDeviceInfo al = null; IntPtr handle = IntPtr.Zero; int lookupresult = 0; /* Windows XP SP3 Begin takes the full Inquiry time. 12:09:15.7968750: Begin 10.265s 12:09:26.0625000: Begin complete 12:09:26.0625000: Next 12:09:26.0625000: Next Complete ... 12:09:26.1718750: Next 12:09:26.1718750: Next Complete 12:09:26.1718750: End 12:09:26.1718750: End Complete */ /* WM 6 SP Begin is quick, Next blocks until a device is found. 13:46:47.1760000: Begin 13:46:47.2350000: Begin complete 13:46:47.2360000: Next 10.537s 13:46:57.7730000: Next Complete 13:46:57.8910000: Next 13:46:57.8940000: Next Complete 13:46:57.8950000: Next 13:46:57.8960000: Next Complete 13:46:57.8960000: End 13:46:57.8990000: End Complete */ System.Text.StringBuilder timings = null; #if DEBUG // timings = new System.Text.StringBuilder(); #endif Action<string> markTime = delegate(string name) { if (timings != null) timings.AppendFormat(CultureInfo.InvariantCulture, "{1}: {0}\r\n", name, DateTime.UtcNow.TimeOfDay); }; #if WinXP if (discoverableOnly && !Win32DiscoverableOnlyIncludesAllDevices) { // No way to separate out the devices-in-range on Win32. :-( return new IBluetoothDeviceInfo[0]; } #endif #if NETCF DateTime discoTime = DateTime.UtcNow; if(unknown || discoverableOnly) { #endif al = new List_IBluetoothDeviceInfo(); byte[] buffer = new byte[1024]; BitConverter.GetBytes(WqsOffset.StructLength_60).CopyTo(buffer, WqsOffset.dwSize_0); BitConverter.GetBytes(WqsOffset.NsBth_16).CopyTo(buffer, WqsOffset.dwNameSpace_20); int bufferlen = buffer.Length; BTHNS_INQUIRYBLOB bib = new BTHNS_INQUIRYBLOB(); bib.LAP = iac;// 0x9E8B33; #if NETCF bib.length = Convert.ToByte(inquiryLength.TotalSeconds / 1.28); bib.num_responses = Convert.ToByte(maxDevices); #else bib.length = Convert.ToByte(inquiryLength.TotalSeconds); #endif GCHandle hBib = GCHandle.Alloc(bib, GCHandleType.Pinned); IntPtr pBib = hBib.AddrOfPinnedObject(); BLOB b = new BLOB(8, pBib); GCHandle hBlob = GCHandle.Alloc(b, GCHandleType.Pinned); Marshal32.WriteIntPtr(buffer, WqsOffset.lpBlob_56, hBlob.AddrOfPinnedObject()); //start looking for Bluetooth devices LookupFlags flags = LookupFlags.Containers; #if WinXP //ensure cache is cleared on XP when looking for new devices if (unknown || discoverableOnly) { flags |= LookupFlags.FlushCache; } #endif markTime("Begin"); lookupresult = NativeMethods.WSALookupServiceBegin(buffer, flags, out handle); markTime("Begin complete"); hBlob.Free(); hBib.Free(); // TODO ?Change "while(...maxDevices)" usage on WIN32? while (discoveredDevices < maxDevices && lookupresult != -1) { markTime("Next"); #if NETCF lookupresult = NativeMethods.WSALookupServiceNext(handle, LookupFlags.ReturnAddr | LookupFlags.ReturnBlob , ref bufferlen, buffer); #else LookupFlags flagsNext = LookupFlags.ReturnAddr; #if WIN32_READ_BTH_DEVICE_INFO flagsNext |= LookupFlags.ReturnBlob; #endif lookupresult = NativeMethods.WSALookupServiceNext(handle, flagsNext, ref bufferlen, buffer); #endif markTime("Next Complete"); if (lookupresult != -1) { //increment found count discoveredDevices++; //status #if WinXP BTHNS_RESULT status = (BTHNS_RESULT)BitConverter.ToInt32(buffer, WqsOffset.dwOutputFlags_52); bool devAuthd = ((status & BTHNS_RESULT.Authenticated) == BTHNS_RESULT.Authenticated); bool devRembd = ((status & BTHNS_RESULT.Remembered) == BTHNS_RESULT.Remembered); if (devAuthd && !devRembd) { System.Diagnostics.Debug.WriteLine("Win32 BT disco: Auth'd but NOT Remembered."); } bool devUnkwn = !devRembd && !devAuthd; bool include = (authenticated && devAuthd) || (remembered && devRembd) || (unknown && devUnkwn); Debug.Assert(!discoverableOnly, "Expected short circuit for Win32 unsupported discoverableOnly!"); if (include) #else if(true) #endif { #if NETCF IntPtr lpBlob = (IntPtr)BitConverter.ToInt32(buffer, 56); BLOB ib = (BLOB)Marshal.PtrToStructure(lpBlob, typeof(BLOB)); BthInquiryResult bir = (BthInquiryResult)Marshal.PtrToStructure(ib.pBlobData, typeof(BthInquiryResult)); #endif //struct CSADDR_INFO { // SOCKET_ADDRESS LocalAddr; // SOCKET_ADDRESS RemoteAddr; // INT iSocketType; // INT iProtocol; //} //struct SOCKET_ADDRESS { // LPSOCKADDR lpSockaddr; // INT iSockaddrLength; //} //pointer to outputbuffer IntPtr bufferptr = Marshal32.ReadIntPtr(buffer, WqsOffset.lpcsaBuffer_48); //remote socket address IntPtr sockaddrptr = Marshal32.ReadIntPtr(bufferptr, CsaddrInfoOffsets.OffsetRemoteAddr_lpSockaddr_8); //remote socket len int sockaddrlen = Marshal.ReadInt32(bufferptr, CsaddrInfoOffsets.OffsetRemoteAddr_iSockaddrLength_12); SocketAddress btsa = new SocketAddress(AddressFamily32.Bluetooth, sockaddrlen); for (int sockbyte = 0; sockbyte < sockaddrlen; sockbyte++) { btsa[sockbyte] = Marshal.ReadByte(sockaddrptr, sockbyte); } var bep = (BluetoothEndPoint)prototype.Create(btsa); //new deviceinfo IBluetoothDeviceInfo newdevice; #if NETCF newdevice = new WindowsBluetoothDeviceInfo(bep.Address, bir.cod); // Built-in to Win32 so only do on NETCF newdevice.SetDiscoveryTime(discoTime); #else newdevice = new WindowsBluetoothDeviceInfo(bep.Address); #if WIN32_READ_BTH_DEVICE_INFO ReadBlobBTH_DEVICE_INFO(buffer, newdevice); #endif #endif //add to discovered list al.Add(newdevice); if (liveDiscoHandler != null) { liveDiscoHandler(newdevice, liveDiscoState); } } } }//while #if NETCF } #endif //stop looking if (handle != IntPtr.Zero) { markTime("End"); lookupresult = NativeMethods.WSALookupServiceEnd(handle); markTime("End Complete"); } if (timings != null) { Debug.WriteLine(timings); #if !NETCF Console.WriteLine(timings); #endif } #if NETCF List_IBluetoothDeviceInfo known = WinCEReadKnownDevicesFromRegistry(); al = BluetoothClient.DiscoverDevicesMerge(authenticated, remembered, unknown, known, al, discoverableOnly, discoTime); #endif //return results if (al.Count == 0) { //special case for empty collection return new IBluetoothDeviceInfo[0] { }; } return (IBluetoothDeviceInfo[])al.ToArray( #if V1 typeof(IBluetoothDeviceInfo) #endif ); } #if WinXP private void ReadBlobBTH_DEVICE_INFO(byte[] buffer, IBluetoothDeviceInfo dev) { // XXXX - Testing only, at least delete the "Console.WriteLine" before use. - XXXX IntPtr pBlob = Marshal32.ReadIntPtr(buffer, WqsOffset.lpBlob_56); if (pBlob != IntPtr.Zero) { BLOB blob = (BLOB)Marshal.PtrToStructure(pBlob, typeof(BLOB)); if (blob.pBlobData != IntPtr.Zero) { BTH_DEVICE_INFO bdi = (BTH_DEVICE_INFO)Marshal.PtrToStructure(blob.pBlobData, typeof(BTH_DEVICE_INFO)); BluetoothDeviceInfoProperties flags = bdi.flags; Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "[BTH_DEVICE_INFO: {0:X12}, '{1}' = 0x{2:X4}]", bdi.address, flags, bdi.flags)); Trace.Assert((flags & ~BDIFMasks.AllOrig) == 0, "*Are* new flags there!"); } } } #endif #if NETCF static class DevicesValueNames { internal const string DeviceName = "name"; internal const string ClassOfDevice = "class"; } private static List_IBluetoothDeviceInfo WinCEReadKnownDevicesFromRegistry() { Func<BluetoothAddress, string, uint, bool, IBluetoothDeviceInfo> makeDev = (address, name, classOfDevice, authd) => new WindowsBluetoothDeviceInfo(address, name, classOfDevice, authd); var deviceListPath = "Software\\Microsoft\\Bluetooth\\Device"; return ReadKnownDevicesFromRegistry(deviceListPath, makeDev); } internal static List_IBluetoothDeviceInfo ReadKnownDevicesFromRegistry( string deviceListPath, Func<BluetoothAddress, string, uint, bool, IBluetoothDeviceInfo> makeDev) { List_IBluetoothDeviceInfo known = new List_IBluetoothDeviceInfo(); //open bluetooth device key RegistryKey devkey = Registry.LocalMachine.OpenSubKey(deviceListPath); //bool addFromRegistry = authenticated || remembered; if (devkey != null) { //enumerate the keys foreach (string devid in devkey.GetSubKeyNames()) { BluetoothAddress address; if (BluetoothAddress.TryParse(devid, out address)) { //get friendly name RegistryKey thisdevkey = devkey.OpenSubKey(devid); string name = thisdevkey.GetValue(DevicesValueNames.DeviceName, "").ToString(); uint classOfDevice = Convert.ToUInt32(thisdevkey.GetValue(DevicesValueNames.ClassOfDevice, 0)); thisdevkey.Close(); //add to collection IBluetoothDeviceInfo thisdevice = makeDev(address, name, classOfDevice, true); known.Add(thisdevice); } } devkey.Close(); } return known; } #endif #if !V1 IAsyncResult IBluetoothClient.BeginDiscoverDevices(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly, AsyncCallback callback, object state) { return ((IBluetoothClient)this).BeginDiscoverDevices(maxDevices, authenticated, remembered, unknown, discoverableOnly, callback, state, null, null); } IAsyncResult IBluetoothClient.BeginDiscoverDevices(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly, AsyncCallback callback, object state, InTheHand.Net.Sockets.BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState) { var args = new DiscoDevsParamsWithLive(maxDevices, authenticated, remembered, unknown, discoverableOnly, DateTime.MinValue, liveDiscoHandler, liveDiscoState); AsyncResult_BeginDiscoverDevices ar = new AsyncResult_BeginDiscoverDevices( callback, state, args); System.Threading.ThreadPool.QueueUserWorkItem(BeginDiscoverDevices_Runner, ar); return ar; } internal class DiscoDevsParamsWithLive : DiscoDevsParams { internal readonly InTheHand.Net.Sockets.BluetoothClient.LiveDiscoveryCallback _liveDiscoHandler; internal readonly object _liveDiscoState; public DiscoDevsParamsWithLive(int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly, DateTime discoTime, InTheHand.Net.Sockets.BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState) : base(maxDevices, authenticated, remembered, unknown, discoverableOnly, discoTime) { _liveDiscoHandler = liveDiscoHandler; _liveDiscoState = liveDiscoState; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] void BeginDiscoverDevices_Runner(object state) { AsyncResult_BeginDiscoverDevices ar = (AsyncResult_BeginDiscoverDevices)state; ar.SetAsCompletedWithResultOf(() => DiscoverDevices(ar.BeginParameters.maxDevices, ar.BeginParameters.authenticated, ar.BeginParameters.remembered, ar.BeginParameters.unknown, ar.BeginParameters.discoverableOnly, ar.BeginParameters._liveDiscoHandler, ar.BeginParameters._liveDiscoState), false); } IBluetoothDeviceInfo[] IBluetoothClient.EndDiscoverDevices(IAsyncResult asyncResult) { AsyncResult_BeginDiscoverDevices ar = (AsyncResult_BeginDiscoverDevices)asyncResult; return ar.EndInvoke(); } #endif #endregion #region Active private bool active = false; /// <summary> /// Gets or set a value that indicates whether a connection has been made. /// </summary> protected bool Active { get { return active; } set { active = value; } } #endregion #region Available public int Available { get { EnsureNotDisposed(); return clientSocket.Available; } } #endregion #region Client private Socket clientSocket; public Socket Client { get { return clientSocket; } set { this.clientSocket = value; } } #endregion #region Connect /// <summary> /// Connects a client to a specified endpoint. /// </summary> /// <param name="remoteEP">A <see cref="BluetoothEndPoint"/> that represents the remote device.</param> public virtual void Connect(BluetoothEndPoint remoteEP) { EnsureNotDisposed(); if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } Connect_StartAuthenticator(remoteEP); try { var connEP = PrepareConnectEndPoint(remoteEP); clientSocket.Connect(connEP); active = true; } finally { Connect_StopAuthenticator(); } } #region Begin Connect /// <summary> /// Begins an asynchronous request for a remote host connection. /// The remote host is specified by a <see cref="BluetoothEndPoint"/>. /// </summary> /// <param name="remoteEP">A <see cref="BluetoothEndPoint"/> containing the /// address and UUID of the remote service.</param> /// <param name="requestCallback">An AsyncCallback delegate that references the method to invoke when the operation is complete.</param> /// <param name="state">A user-defined object that contains information about the connect operation. /// This object is passed to the requestCallback delegate when the operation is complete.</param> /// <returns></returns> public virtual IAsyncResult BeginConnect(BluetoothEndPoint remoteEP, AsyncCallback requestCallback, object state) { EnsureNotDisposed(); Connect_StartAuthenticator(remoteEP); var connEP = PrepareConnectEndPoint(remoteEP); return this.Client.BeginConnect(connEP, requestCallback, state); } #endregion #region End Connect /// <summary> /// Asynchronously accepts an incoming connection attempt. /// </summary> /// <param name="asyncResult">An <see cref="IAsyncResult"/> object returned by a call to /// <see cref="M:BeginConnect(InTheHand.Net.Sockets.BluetoothEndPoint,System.AsyncCallback,System.Object)"/> /// / <see cref="M:BeginConnect(InTheHand.Net.Sockets.BluetoothAddress,System.Guid,System.AsyncCallback,System.Object)"/>. /// </param> public virtual void EndConnect(IAsyncResult asyncResult) { try { Socket sock = this.Client; if (sock == null) { Debug.Assert(cleanedUp, "!cleanedUp"); throw new ObjectDisposedException("BluetoothClient"); } else { sock.EndConnect(asyncResult); } this.active = true; } finally { Connect_StopAuthenticator(); } } #endregion #endregion #region Connected public bool Connected { get { if (clientSocket == null) return false; return clientSocket.Connected; } } #endregion #region Get Stream private NetworkStream dataStream; protected virtual NetworkStream MakeStream(Socket sock) { return new NetworkStream(this.Client, true); } public NetworkStream GetStream() { EnsureNotDisposed(); if (!this.Client.Connected) { throw new InvalidOperationException("The operation is not allowed on non-connected sockets."); } if (dataStream == null) { dataStream = MakeStream(this.Client); } return dataStream; } #if TEST_EARLY public Stream GetStream2() { return GetStream(); } #endif #endregion public LingerOption LingerState { #if !NETCF get { return Client.LingerState; } set { Client.LingerState = value; } #else get { return (LingerOption)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value); } #endif } #region Authenticate /// <summary> /// Gets or sets the authentication state of the current connect or behaviour to use when connection is established. /// </summary> /// <remarks> /// For disconnected sockets, specifies that authentication is required in order for a connect or accept operation to complete successfully. /// Setting this option actively initiates authentication during connection establishment, if the two Bluetooth devices were not previously authenticated. /// The user interface for passkey exchange, if necessary, is provided by the operating system outside the application context. /// For outgoing connections that require authentication, the connect operation fails with WSAEACCES if authentication is not successful. /// In response, the application may prompt the user to authenticate the two Bluetooth devices before connection. /// For incoming connections, the connection is rejected if authentication cannot be established and returns a WSAEHOSTDOWN error. /// </remarks> public bool Authenticate { get { return m_optionHelper.Authenticate; } set { m_optionHelper.Authenticate = value; } } #endregion #region Encrypt /// <summary> /// On unconnected sockets, enforces encryption to establish a connection. /// Encryption is only available for authenticated connections. /// For incoming connections, a connection for which encryption cannot be established is automatically rejected and returns WSAEHOSTDOWN as the error. /// For outgoing connections, the connect function fails with WSAEACCES if encryption cannot be established. /// In response, the application may prompt the user to authenticate the two Bluetooth devices before connection. /// </summary> public bool Encrypt { get { return m_optionHelper.Encrypt; } set { m_optionHelper.Encrypt = value; } } #endregion #region Link Key /// <summary> /// Returns link key associated with peer Bluetooth device. /// </summary> public Guid LinkKey { get { EnsureNotDisposed(); byte[] bytes = new byte[16]; #if NETCF byte[] link = clientSocket.GetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.GetLink, 32); Buffer.BlockCopy(link, 16, bytes, 0, 16); #endif return new Guid(bytes); } } #endregion #region Link Policy /// <summary> /// Returns the Link Policy of the current connection. /// </summary> public LinkPolicy LinkPolicy { get { EnsureNotDisposed(); #if NETCF byte[] policy = clientSocket.GetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.GetLinkPolicy, 4); return (LinkPolicy)BitConverter.ToInt32(policy, 0); #else return LinkPolicy.Disabled; #endif } } #endregion #region Set PIN /// <summary> /// Sets the PIN associated with the currently connected device. /// </summary> /// <param name="pin">PIN which must be composed of 1 to 16 ASCII characters.</param> /// <remarks>Assigning null (Nothing in VB) or an empty String will revoke the PIN.</remarks> public void SetPin(string pin) { if (!Connected) { #if WinXP m_pinForConnect = pin; #else SetPin(null, pin); #endif } else { EndPoint rep = clientSocket.RemoteEndPoint; BluetoothAddress addr = null; if (rep != null) addr = ((BluetoothEndPoint)rep).Address; if (addr == null) throw new InvalidOperationException( "The socket needs to be connected to detect the remote device" + ", use the other SetPin method.."); SetPin(addr, pin); } } /// <summary> /// Set or change the PIN to be used with a specific remote device. /// </summary> /// <param name="device">Address of Bluetooth device.</param> /// <param name="pin">PIN string consisting of 1 to 16 ASCII characters.</param> /// <remarks>Assigning null (Nothing in VB) or an empty String will revoke the PIN.</remarks> public void SetPin(BluetoothAddress device, string pin) { m_optionHelper.SetPin(device, pin); } private void Connect_StartAuthenticator(BluetoothEndPoint remoteEP) { #if WinXP if (m_pinForConnect != null) { SetPin(remoteEP.Address, m_pinForConnect); } #endif } private void Connect_StopAuthenticator() { #if WinXP if (m_pinForConnect != null) { SetPin(null, null); } #endif } #endregion #region Remote Machine Name public BluetoothEndPoint RemoteEndPoint { get { EnsureNotDisposed(); return (BluetoothEndPoint)clientSocket.RemoteEndPoint; } } /// <summary> /// Gets the name of the remote device. /// </summary> public string RemoteMachineName { get { EnsureNotDisposed(); return GetRemoteMachineName(clientSocket); } } /// <summary> /// Gets the name of the specified remote device. /// </summary> /// <param name="a">Address of remote device.</param> /// <returns>Friendly name of specified device.</returns> public string GetRemoteMachineName(BluetoothAddress a) { #if WinXP var bdi = _fcty.DoGetBluetoothDeviceInfo(a); return bdi.DeviceName; #else byte[] buffer = new byte[504]; //copy remote device address to buffer Buffer.BlockCopy(a.ToByteArray(), 0, buffer, 0, 6); try { clientSocket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.ReadRemoteName, buffer); string name = string.Empty; name = System.Text.Encoding.Unicode.GetString(buffer, 8, 496); int offset = name.IndexOf('\0'); if(offset > -1) { name = name.Substring(0, offset); } return name; } catch(SocketException ex) { System.Diagnostics.Debug.WriteLine("BluetoothClient GetRemoteMachineName(addr) ReadRemoteName failed: " + ex.Message); return null; } #endif } /// <summary> /// Gets the name of a device by a specified socket. /// </summary> /// <param name="s"> A <see cref="Socket"/>.</param> /// <returns>Returns a string value of the computer or device name.</returns> public static string GetRemoteMachineName(Socket s) { #if WinXP // HACK was new WindowsBluetoothDeviceInfo var bdi = new BluetoothDeviceInfo(((BluetoothEndPoint)s.RemoteEndPoint).Address); return bdi.DeviceName; #else byte[] buffer = new byte[504]; //copy remote device address to buffer Buffer.BlockCopy(((BluetoothEndPoint)s.RemoteEndPoint).Address.ToByteArray(), 0, buffer, 0, 6); string name = ""; try { s.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.ReadRemoteName, buffer); name = System.Text.Encoding.Unicode.GetString(buffer, 8, 496); int offset = name.IndexOf('\0'); if(offset > -1) { name = name.Substring(0, offset); } return name; } catch(SocketException ex) { System.Diagnostics.Debug.WriteLine("BluetoothClient GetRemoteMachineName(socket) ReadRemoteName failed: " + ex.Message); return null; } #endif } #endregion #region IDisposable Members /// <summary> /// Releases the unmanaged resources used by the BluetoothClient 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> protected virtual void Dispose(bool disposing) { if (!cleanedUp) { if (disposing) { IDisposable idStream = dataStream; if (idStream != null) { //dispose the stream which will also close the socket idStream.Dispose(); } else { if (this.Client != null) { this.Client.Close(); this.Client = null; } } // TODO ??? m_optionHelper.Dispose(); } cleanedUp = true; } } private void EnsureNotDisposed() { Debug.Assert(cleanedUp == (clientSocket == null), "always consistent!! (" + cleanedUp + " != " + (clientSocket == null) + ")"); if (cleanedUp || (clientSocket == null)) throw new ObjectDisposedException("BluetoothClient"); } /// <summary> /// Closes the <see cref="BluetoothClient"/> and the underlying connection. /// </summary> /// - /// <seealso cref="M:InTheHand.Net.Sockets.BluetoothClient.Close"/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Frees resources used by the <see cref="BluetoothClient"/> class. /// </summary> ~SocketBluetoothClient() { Dispose(false); } #endregion #region Throw SocketException For HR internal static void ThrowSocketExceptionForHR(int errorCode) { if (errorCode < 0) { int socketerror = 0; socketerror = Marshal.GetLastWin32Error(); throw new SocketException(socketerror); } } internal static void ThrowSocketExceptionForHrExceptFor(int errorCode, params int[] nonErrorCodes) { if (errorCode < 0) { int socketerror = 0; socketerror = Marshal.GetLastWin32Error(); if (-1 != Array.IndexOf(nonErrorCodes, socketerror, 0, nonErrorCodes.Length)) { return; } throw new SocketException(socketerror); } } #endregion internal class MsftSocketOptionHelper : ISocketOptionHelper { readonly Socket m_socket; #if !WinCE private bool authenticate = false; private BluetoothWin32Authentication m_authenticator; #endif private bool encrypt = false; internal MsftSocketOptionHelper(Socket socket) { m_socket = socket; } #region Authenticate /// <summary> /// Gets or sets the authentication state of the current connect or behaviour to use when connection is established. /// </summary> /// <remarks> /// For disconnected sockets, specifies that authentication is required in order for a connect or accept operation to complete successfully. /// Setting this option actively initiates authentication during connection establishment, if the two Bluetooth devices were not previously authenticated. /// The user interface for passkey exchange, if necessary, is provided by the operating system outside the application context. /// For outgoing connections that require authentication, the connect operation fails with WSAEACCES if authentication is not successful. /// In response, the application may prompt the user to authenticate the two Bluetooth devices before connection. /// For incoming connections, the connection is rejected if authentication cannot be established and returns a WSAEHOSTDOWN error. /// </remarks> public bool Authenticate { get { #if NETCF byte[] authbytes = m_socket.GetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.GetAuthenticationEnabled, 4); int auth = BitConverter.ToInt32(authbytes, 0); return (auth==0) ? false : true; #else return authenticate; #endif } set { #if NETCF m_socket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.SetAuthenticationEnabled, (int)(value ? 1 : 0)); #else m_socket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.Authenticate, value); authenticate = value; #endif } } #endregion #region Encrypt /// <summary> /// On unconnected sockets, enforces encryption to establish a connection. /// Encryption is only available for authenticated connections. /// For incoming connections, a connection for which encryption cannot be established is automatically rejected and returns WSAEHOSTDOWN as the error. /// For outgoing connections, the connect function fails with WSAEACCES if encryption cannot be established. /// In response, the application may prompt the user to authenticate the two Bluetooth devices before connection. /// </summary> public bool Encrypt { get { return encrypt; } set { m_socket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.Encrypt, (int)(value ? 1 : 0)); encrypt = value; } } #endregion #region Set Pin public void SetPin(BluetoothAddress device, string pin) { #if WinXP if (pin != null) { m_authenticator = new BluetoothWin32Authentication(device, pin); } else { if (m_authenticator != null) { m_authenticator.Dispose(); } } #else byte[] link = new byte[32]; //copy remote device address if (device != null) { Buffer.BlockCopy(device.ToByteArray(), 0, link, 8, 6); } //copy PIN if (pin != null & pin.Length > 0) { if (pin.Length > 16) { throw new ArgumentOutOfRangeException("PIN must be between 1 and 16 ASCII characters"); } //copy pin bytes byte[] pinbytes = System.Text.Encoding.ASCII.GetBytes(pin); Buffer.BlockCopy(pinbytes, 0, link, 16, pin.Length); BitConverter.GetBytes(pin.Length).CopyTo(link, 0); } m_socket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.SetPin, link); #endif } #endregion }//class--SocketOptionHelper }//class--BluetoothClient }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using Franson.BlueTools; using Franson.Protocols.Obex; using Franson.Protocols.Obex.ObjectPush; namespace ObjectPushSample200 { /// <summary> /// Summary description for Form1. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.ListBox deviceList; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button discoverBtn; private System.Windows.Forms.Button sendBtn; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.StatusBarPanel statusBarPanel; private System.Windows.Forms.StatusBar statusBar; private System.Windows.Forms.StatusBarPanel copyPanel; private Manager m_manager = null; private Network m_network = null; private ObexObjectPush m_objectPush = null; // these objects should be class global to prevent them from being taken by the garbage collector private RemoteService m_serviceCurrent = null; private Stream m_streamCurrent = null; private System.Windows.Forms.Label informLabel; // this is to control that the stream is'nt closed before all transfers is done. private int m_intTransfers = 0; // this is status booleans private bool m_boolAborted = false; private bool m_boolDenied = false; private bool m_boolUnrecoverableError = false; private bool m_boolTimeOut = false; public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); // catch all BlueTools exceptions - like e.g. license expired try { // get your trial license or buy BlueTools at franson.com Franson.BlueTools.License license = new Franson.BlueTools.License(); license.LicenseKey = "WoK6IL944A9CIONQRXaYUjpRJRiuHYFYWrT7"; // get bluetools manager m_manager = Manager.GetManager(); // get first network dongle - bluetools 1.0 only supports one! m_network = m_manager.Networks[0]; // marshal events into this class thread. m_manager.Parent = this; // update statusbar panel with name of currently used stack switch (Manager.StackID) { case StackID.STACK_MICROSOFT: { statusBarPanel.Text = "Microsoft Stack"; break; } case StackID.STACK_WIDCOMM: { statusBarPanel.Text = "Widcomm Stack"; break; } default: { statusBarPanel.Text = "Unknown stack"; break; } } } catch (Exception exc) { // display BlueTools error here MessageBox.Show(exc.Message); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { // BlueTools manager must be disposed, otherwise you can't exit application! Manager.GetManager().Dispose(); if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.deviceList = new System.Windows.Forms.ListBox(); this.label1 = new System.Windows.Forms.Label(); this.discoverBtn = new System.Windows.Forms.Button(); this.sendBtn = new System.Windows.Forms.Button(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.statusBar = new System.Windows.Forms.StatusBar(); this.statusBarPanel = new System.Windows.Forms.StatusBarPanel(); this.copyPanel = new System.Windows.Forms.StatusBarPanel(); this.informLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.copyPanel)).BeginInit(); this.SuspendLayout(); // // openFileDialog // this.openFileDialog.Multiselect = true; // // deviceList // this.deviceList.Location = new System.Drawing.Point(16, 32); this.deviceList.Name = "deviceList"; this.deviceList.Size = new System.Drawing.Size(160, 160); this.deviceList.TabIndex = 0; this.deviceList.SelectedIndexChanged += new System.EventHandler(this.deviceList_SelectedIndexChanged); // // label1 // this.label1.Location = new System.Drawing.Point(16, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 16); this.label1.TabIndex = 1; this.label1.Text = "Devices"; // // discoverBtn // this.discoverBtn.Location = new System.Drawing.Point(16, 216); this.discoverBtn.Name = "discoverBtn"; this.discoverBtn.Size = new System.Drawing.Size(75, 23); this.discoverBtn.TabIndex = 2; this.discoverBtn.Text = "Discover"; this.discoverBtn.Click += new System.EventHandler(this.discoverBtn_Click); // // sendBtn // this.sendBtn.Enabled = false; this.sendBtn.Location = new System.Drawing.Point(104, 216); this.sendBtn.Name = "sendBtn"; this.sendBtn.Size = new System.Drawing.Size(75, 23); this.sendBtn.TabIndex = 3; this.sendBtn.Text = "Push"; this.sendBtn.Click += new System.EventHandler(this.sendBtn_Click); // // progressBar // this.progressBar.Location = new System.Drawing.Point(16, 200); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(160, 8); this.progressBar.TabIndex = 4; // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 295); this.statusBar.Name = "statusBar"; this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] { this.statusBarPanel, this.copyPanel}); this.statusBar.ShowPanels = true; this.statusBar.Size = new System.Drawing.Size(192, 22); this.statusBar.SizingGrip = false; this.statusBar.TabIndex = 5; // // statusBarPanel // this.statusBarPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring; this.statusBarPanel.Name = "statusBarPanel"; this.statusBarPanel.Width = 182; // // copyPanel // this.copyPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents; this.copyPanel.Name = "copyPanel"; this.copyPanel.Width = 10; // // informLabel // this.informLabel.Location = new System.Drawing.Point(16, 248); this.informLabel.Name = "informLabel"; this.informLabel.Size = new System.Drawing.Size(160, 40); this.informLabel.TabIndex = 6; this.informLabel.Text = "Click Discover to find nearby Bluetooth devices."; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(192, 317); this.Controls.Add(this.informLabel); this.Controls.Add(this.statusBar); this.Controls.Add(this.progressBar); this.Controls.Add(this.sendBtn); this.Controls.Add(this.discoverBtn); this.Controls.Add(this.label1); this.Controls.Add(this.deviceList); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.Name = "MainForm"; this.Text = "ObjectPush Sample"; this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.copyPanel)).EndInit(); this.ResumeLayout(false); } #endregion private void discoverBtn_Click(object sender, System.EventArgs e) { m_network.DeviceDiscovered += new BlueToolsEventHandler(m_network_DeviceDiscovered); m_network.DeviceDiscoveryStarted += new BlueToolsEventHandler(m_network_DeviceDiscoveryStarted); m_network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(m_network_DeviceDiscoveryCompleted); // Start looking for devices on the network // Use Network.DiscoverDevices() if you don't want to use events. m_network.DiscoverDevicesAsync(); } private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // if currentService is available, close the stream if (m_serviceCurrent != null) { if (m_streamCurrent != null) m_streamCurrent.Close(); // set these objects to null to mark them for GC m_streamCurrent = null; m_serviceCurrent = null; } // dispose objects - also makes sure that Manager are disposed. Dispose(); } private void m_network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs) { // add every device found RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; deviceList.Items.Add(device); } private void m_network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { // disable the Discover button when we begin device discovery discoverBtn.Enabled = false; // disable the send button since you can't send while device discovering sendBtn.Enabled = false; // disable the device list while searching for devices deviceList.Enabled = false; // inform the user what we're doing informLabel.Text = "Scanning for devices..."; } private void m_network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { Device[] devices = (Device[])((DiscoveryEventArgs)eventArgs).Discovery; // enable Discover button again since device discovery is complete discoverBtn.Enabled = true; // enable the device list again deviceList.Enabled = true; // inform the user what to do informLabel.Text = "Click on the device you wish to push a file to."; m_network.DeviceDiscovered -= new BlueToolsEventHandler(m_network_DeviceDiscovered); m_network.DeviceDiscoveryStarted -= new BlueToolsEventHandler(m_network_DeviceDiscoveryStarted); m_network.DeviceDiscoveryCompleted -= new BlueToolsEventHandler(m_network_DeviceDiscoveryCompleted); } private void deviceList_SelectedIndexChanged(object sender, System.EventArgs e) { // get selected item (a remote device) RemoteDevice selectedDevice = (RemoteDevice)deviceList.SelectedItem; selectedDevice.ServiceDiscoveryStarted += new BlueToolsEventHandler(selectedDevice_ServiceDiscoveryStarted); selectedDevice.ServiceDiscoveryCompleted += new BlueToolsEventHandler(selectedDevice_ServiceDiscoveryCompleted); // detect Object Push service (OPP) on this device deviceList.Enabled = false; selectedDevice.DiscoverServicesAsync(ServiceType.OBEXObjectPush); } private void selectedDevice_ServiceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { // when beginning to search for services - disable the Discover button // we shouldn't scan for devices while attempting to scan for services. discoverBtn.Enabled = false; sendBtn.Enabled = false; } private void selectedDevice_ServiceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { // when service discovery is complete - let us re-enable the discover button. // It is okay to try to update the device list discoverBtn.Enabled = true; // re-enable the device list deviceList.Enabled = true; // set error event handler for the device RemoteDevice device = (RemoteDevice)sender; device.Error += new BlueToolsEventHandler(device_Error); // get all services found Service[] services = (Service[])((DiscoveryEventArgs)eventArgs).Discovery; // if we have a service since before, close the stream if (m_streamCurrent != null) { m_streamCurrent.Close(); m_streamCurrent = null; } // and remove the service if (m_serviceCurrent != null) { m_serviceCurrent = null; } // if we found a new service... if (services.Length > 0) { // ...get OPP service object m_serviceCurrent = (RemoteService)services[0]; try { // create an ObexObjectPush object connected to the ServiceStream m_objectPush = new ObexObjectPush(-1); // wait forever // marshal event to this class thread m_objectPush.Parent = this; // setup event handlers m_objectPush.Error += new ObexEventHandler(m_objectPush_Error); m_objectPush.PutFileBegin += new ObexEventHandler(m_objectPush_PutFileBegin); m_objectPush.PutFileProgress += new ObexEventHandler(m_objectPush_PutFileProgress); m_objectPush.PutFileEnd += new ObexEventHandler(m_objectPush_PutFileEnd); m_objectPush.DisconnectEnd += new ObexEventHandler(m_objectPush_DisconnectEnd); // enable the Push button sendBtn.Enabled = true; // inform the user what to do next informLabel.Text = "Click on Send to select file(s) to push to device."; } catch (Exception exc) { sendBtn.Enabled = false; MessageBox.Show(exc.Message); } } } void m_objectPush_DisconnectEnd(object sender, ObexEventArgs e) { // Count down disconnections m_intTransfers--; // When we have had same number of disconnections as transfers we are done and can safely close the stream. if (m_intTransfers == 0) { m_streamCurrent.Close(); } } private void sendBtn_Click(object sender, System.EventArgs e) { if (sendBtn.Text.Equals("Push")) { try { // if we have a service to send to if (m_serviceCurrent != null) { // make sure ObexObjectPush is initialized and select file to push to device if (m_objectPush != null && openFileDialog.ShowDialog() == DialogResult.OK) { foreach(string filename in openFileDialog.FileNames) { m_streamCurrent = m_serviceCurrent.Stream; FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read); m_objectPush.PushFileAsync(fileStream, Path.GetFileName(filename), m_streamCurrent); // Increment number of transfers m_intTransfers++; } } } } catch { // disable Push button if there was an error sendBtn.Enabled = false; // inform the user what happened informLabel.Text = "Failed to get a socket.\nClick on the device you wish to push a file to."; } } else { // if button text isn't Send it will be Cancel - // if user click it, we tell ObexObjectPush that we want to abort m_objectPush.Abort(); // only need to press cancel once - won't help you to press it more sendBtn.Enabled = false; } } private void m_objectPush_PutFileProgress(object sender, ObexEventArgs eventArgs) { ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)eventArgs; // if size isn't unknown if (copyArgs.Size != -1) { // if max value on progressbar isn't set, set it if (copyArgs.Size != progressBar.Maximum) { progressBar.Maximum = (int)copyArgs.Size; } // set position of file copy progressBar.Value = (int)copyArgs.Position; // update copy panel to show progress in kb copyPanel.Text = Convert.ToString(copyArgs.Position / 1024) + " kb / " + Convert.ToString(copyArgs.Size / 1024) + " kb"; } else { // update copy panel to show progress in kb copyPanel.Text = Convert.ToString(copyArgs.Position / 1024) + " kb / ? kb"; } } private void m_objectPush_PutFileEnd(object sender, ObexEventArgs eventArgs) { // when finished copying... // ...close file stream ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)eventArgs; // Close Stream opened by ObexObjectPush copyArgs.Stream.Close(); // ...enable discover button discoverBtn.Enabled = true; // ...change text caption back to Send sendBtn.Text = "Push"; // set progressbar position back to beginning - just for show, doesn't really matter progressBar.Value = 0; // set copy panel to nothing to make it invisible again - it's auto-resizing :) copyPanel.Text = ""; // inform the user what is happening if (m_boolAborted) { // ...if transfer was aborted.. informLabel.Text = "Push aborted.\nClick on Push to select file(s) to push to device."; } else if (m_boolDenied) { // .. if push was denied by receiving device informLabel.Text = "Push denied by device.\nClick on Push to select file(s) to push to device."; } else if (m_boolTimeOut) { // ..if stream was lost because of a timeout informLabel.Text = "Stream lost to device due to device not responding within timeout interval." + "\nClick on the device you wish to push file(s) to."; } else if (m_boolUnrecoverableError) { // ..if stream was lost informLabel.Text = "Stream lost to device.\nClick on the device you wish to push file(s) to."; } else { // ...transfer completed informLabel.Text = "File(s) sent to device.\nClick on Push to select file(s) to push to device."; } // enable device list again when finished deviceList.Enabled = true; // we enable the Send button again if it was disabled when it was a Cancel button sendBtn.Enabled = true; } private void m_objectPush_PutFileBegin(object sender, ObexEventArgs eventArgs) { // this transfer hasn't been aborted (yet!) m_boolAborted = false; // this transfer hasn't been denied (yet!) m_boolDenied = false; // there hasn't been any unrecoverable error (yet!) m_boolUnrecoverableError = false; // no timeout (yet!) m_boolTimeOut = false; // while copying, disable the discover button discoverBtn.Enabled = false; // change the text so the user can Cancel the transfer sendBtn.Text = "Cancel"; // disable device list again while copying deviceList.Enabled = false; // inform the user what is happening informLabel.Text = "Sending file(s) to device..."; } private void m_objectPush_Error(object sender, ObexEventArgs eventArgs) { ObexErrorEventArgs errorArgs = (ObexErrorEventArgs)eventArgs; if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.Timeout) { m_boolTimeOut = true; // since the stream was lost, re-enable the UI // the Push button sendBtn.Enabled = false; // the device list deviceList.Enabled = true; } else if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.StreamError) { // since the stream was lost, re-enable the UI // the Push button sendBtn.Enabled = false; // the device list deviceList.Enabled = true; // this error can't be recovered from m_boolUnrecoverableError = true; // show this error in a box - it's pretty serious MessageBox.Show(errorArgs.Message); } else { // if the error is transfer was aborted, set boolean so we can display this to user if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.Aborted || errorArgs.Error == Franson.Protocols.Obex.ErrorCode.SecurityAbort) { m_boolAborted = true; } // some devices return Forbidden when canceling (like Sony Ericsson phones) so let's tell // user what really happened if (errorArgs.Error == Franson.Protocols.Obex.ErrorCode.SendDenied) { m_boolDenied = true; } } } private void device_Error(object sender, BlueToolsEventArgs eventArgs) { Franson.BlueTools.ErrorEventArgs errorArgs = (Franson.BlueTools.ErrorEventArgs)eventArgs; // show bluetools errors in boxes - they are serious, can't use obex without bluetools in this sample MessageBox.Show(errorArgs.Message); } } }
// <copyright file="ObservableDictionary{TKey,TValue}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using IX.Observable.Adapters; using IX.Observable.DebugAide; using IX.Observable.StateChanges; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Extensions; using IX.StandardExtensions.Threading; using IX.Undoable.StateChanges; using JetBrains.Annotations; namespace IX.Observable; /// <summary> /// A dictionary that broadcasts its changes. /// </summary> /// <typeparam name="TKey">The data key type.</typeparam> /// <typeparam name="TValue">The data value type.</typeparam> [DebuggerDisplay("ObservableDictionary, Count = {" + nameof(Count) + "}")] [DebuggerTypeProxy(typeof(DictionaryDebugView<,>))] [CollectionDataContract( Namespace = Constants.DataContractNamespace, Name = "Observable{1}DictionaryBy{0}", ItemName = "Entry", KeyName = "Key", ValueName = "Value")] [PublicAPI] public class ObservableDictionary<TKey, TValue> : ObservableCollectionBase<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> where TKey : notnull { #region Constructors and destructors /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> public ObservableDictionary() : base(new DictionaryCollectionAdapter<TKey, TValue>()) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="capacity">The initial capacity of the dictionary.</param> public ObservableDictionary(int capacity) : base(new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(capacity))) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> public ObservableDictionary(IEqualityComparer<TKey> equalityComparer) : base(new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(equalityComparer))) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="capacity">The initial capacity of the dictionary.</param> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> public ObservableDictionary( int capacity, IEqualityComparer<TKey> equalityComparer) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( capacity, equalityComparer))) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="dictionary">A dictionary of items to copy from.</param> public ObservableDictionary(IDictionary<TKey, TValue> dictionary) : base(new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(dictionary))) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="dictionary">A dictionary of items to copy from.</param> /// <param name="comparer">A comparer object to use for equality comparison.</param> public ObservableDictionary( IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( dictionary, comparer))) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> public ObservableDictionary(SynchronizationContext context) : base( new DictionaryCollectionAdapter<TKey, TValue>(), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="capacity">The initial capacity of the dictionary.</param> public ObservableDictionary( SynchronizationContext context, int capacity) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(capacity)), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> public ObservableDictionary( SynchronizationContext context, IEqualityComparer<TKey> equalityComparer) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(equalityComparer)), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="capacity">The initial capacity of the dictionary.</param> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> public ObservableDictionary( SynchronizationContext context, int capacity, IEqualityComparer<TKey> equalityComparer) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( capacity, equalityComparer)), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="dictionary">A dictionary of items to copy from.</param> public ObservableDictionary( SynchronizationContext context, IDictionary<TKey, TValue> dictionary) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(dictionary)), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="dictionary">A dictionary of items to copy from.</param> /// <param name="comparer">A comparer object to use for equality comparison.</param> public ObservableDictionary( SynchronizationContext context, IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( dictionary, comparer)), context) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary(bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="capacity">The initial capacity of the dictionary.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( int capacity, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(capacity)), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( IEqualityComparer<TKey> equalityComparer, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(equalityComparer)), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="capacity">The initial capacity of the dictionary.</param> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( int capacity, IEqualityComparer<TKey> equalityComparer, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( capacity, equalityComparer)), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="dictionary">A dictionary of items to copy from.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( IDictionary<TKey, TValue> dictionary, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(dictionary)), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="dictionary">A dictionary of items to copy from.</param> /// <param name="comparer">A comparer object to use for equality comparison.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( dictionary, comparer)), suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( SynchronizationContext context, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(), context, suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="capacity">The initial capacity of the dictionary.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( SynchronizationContext context, int capacity, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(capacity)), context, suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( SynchronizationContext context, IEqualityComparer<TKey> equalityComparer, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(equalityComparer)), context, suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="capacity">The initial capacity of the dictionary.</param> /// <param name="equalityComparer">A comparer object to use for equality comparison.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( SynchronizationContext context, int capacity, IEqualityComparer<TKey> equalityComparer, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( capacity, equalityComparer)), context, suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="dictionary">A dictionary of items to copy from.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( SynchronizationContext context, IDictionary<TKey, TValue> dictionary, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>(new Dictionary<TKey, TValue>(dictionary)), context, suppressUndoable) { } /// <summary> /// Initializes a new instance of the <see cref="ObservableDictionary{TKey, TValue}" /> class. /// </summary> /// <param name="context">The synchronization context top use when posting observable messages.</param> /// <param name="dictionary">A dictionary of items to copy from.</param> /// <param name="comparer">A comparer object to use for equality comparison.</param> /// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param> public ObservableDictionary( SynchronizationContext context, IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer, bool suppressUndoable) : base( new DictionaryCollectionAdapter<TKey, TValue>( new Dictionary<TKey, TValue>( dictionary, comparer)), context, suppressUndoable) { } #endregion #region Properties and indexers /// <summary> /// Gets the collection of keys in this dictionary. /// </summary> public ICollection<TKey> Keys { get { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.InternalContainer.Keys; } } } /// <summary> /// Gets the collection of values in this dictionary. /// </summary> public ICollection<TValue> Values { get { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.InternalContainer.Values; } } } /// <summary> /// Gets the collection of keys in this dictionary. /// </summary> IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => this.Keys; /// <summary> /// Gets the collection of values in this dictionary. /// </summary> IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => this.Values; /// <summary> /// Gets the internal object container. /// </summary> /// <value>The internal container.</value> protected internal new IDictionaryCollectionAdapter<TKey, TValue> InternalContainer => (DictionaryCollectionAdapter<TKey, TValue>)base.InternalContainer; /// <summary> /// Gets or sets the value associated with a specific key. /// </summary> /// <param name="key">The key.</param> /// <returns>The value associated with the specified key.</returns> public TValue this[TKey key] { get { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.InternalContainer[key]; } } set { // PRECONDITIONS // Current object not disposed this.RequiresNotDisposed(); // ACTION IDictionary<TKey, TValue> dictionary = this.InternalContainer; // Within a write lock using (this.WriteLock()) { if (dictionary.TryGetValue( key, out TValue? val)) { // Set the new item dictionary[key] = value; // Push a change undo level this.PushUndoLevel( new DictionaryChangeStateChange<TKey, TValue>( key, value, val)); } else { // Add the new item dictionary.Add( key, value); // Push an add undo level this.PushUndoLevel( new DictionaryAddStateChange<TKey, TValue>( key, value)); } } // NOTIFICATION this.BroadcastChange(); } } #endregion #region Methods #region Interface implementations /// <summary> /// Adds an item to the dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Add( TKey key, TValue value) { // PRECONDITIONS // Current object not disposed this.RequiresNotDisposed(); // ACTION // Under write lock using (this.WriteLock()) { // Add the item var newIndex = this.InternalContainer.Add( key, value); // Push the undo level this.PushUndoLevel( new AddStateChange<KeyValuePair<TKey, TValue>>( new KeyValuePair<TKey, TValue>( key, value), newIndex)); } // NOTIFICATIONS this.BroadcastChange(); } /// <summary> /// Determines whether the dictionary contains a specific key. /// </summary> /// <param name="key">The key to look for.</param> /// <returns><see langword="true" /> whether a key has been found, <see langword="false" /> otherwise.</returns> public bool ContainsKey(TKey key) { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.InternalContainer.ContainsKey(key); } } /// <summary> /// Attempts to remove all info related to a key from the dictionary. /// </summary> /// <param name="key">The key to remove data from.</param> /// <returns><see langword="true" /> if the removal was successful, <see langword="false" /> otherwise.</returns> public bool Remove(TKey key) { // PRECONDITIONS // Current object not disposed this.RequiresNotDisposed(); // ACTION bool result; IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; // Within a read/write lock using (ReadWriteSynchronizationLocker locker = this.ReadWriteLock()) { // Find out if there's anything to remove if (!container.TryGetValue( key, out TValue? value)) { return false; } // Upgrade the locker to a write lock locker.Upgrade(); // Do the actual removal result = container.Remove(key); // Push undo level if (result) { this.PushUndoLevel( new DictionaryRemoveStateChange<TKey, TValue>( key, value)); } } // NOTIFICATION AND RETURN if (result) { this.BroadcastChange(); } return result; } #pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). /// <summary> /// Attempts to fetch a value for a specific key, indicating whether it has been found or not. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns><see langword="true" /> if the value was successfully fetched, <see langword="false" /> otherwise.</returns> public bool TryGetValue( TKey key, [MaybeNullWhen(false)] out TValue value) { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.InternalContainer.TryGetValue( key, out value); } } #pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). #endregion /// <summary> /// Called when contents of this dictionary may have changed. /// </summary> protected override void ContentsMayHaveChanged() { this.RaisePropertyChanged(nameof(this.Keys)); this.RaisePropertyChanged(nameof(this.Values)); this.RaisePropertyChanged(Constants.ItemsName); } /// <summary> /// Interprets the block state changes outside the write lock. /// </summary> /// <param name="actions">The actions to employ.</param> /// <param name="states">The state objects to send to the corresponding actions.</param> protected override void InterpretBlockStateChangesOutsideLock( Action<object?>?[] actions, object?[] states) => this.BroadcastChange(); /// <summary> /// Has the last operation undone. /// </summary> /// <param name="undoRedoLevel">A level of undo, with contents.</param> /// <param name="toInvokeOutsideLock">An action to invoke outside of the lock.</param> /// <param name="state">The state object to pass to the invocation.</param> /// <returns><see langword="true" /> if the undo was successful, <see langword="false" /> otherwise.</returns> protected override bool UndoInternally( StateChangeBase undoRedoLevel, out Action<object?>? toInvokeOutsideLock, out object? state) { if (base.UndoInternally( undoRedoLevel, out toInvokeOutsideLock, out state)) { return true; } switch (undoRedoLevel) { case AddStateChange<KeyValuePair<TKey, TValue>>(var keyValuePair, _): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Remove(keyValuePair.Key); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case RemoveStateChange<KeyValuePair<TKey, TValue>>(_, var (key, value)): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Add( key, value); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case ClearStateChange<KeyValuePair<TKey, TValue>>(var keyValuePairs): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; foreach ((TKey key, TValue value) in keyValuePairs) { container.Add( key, value); } toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case DictionaryAddStateChange<TKey, TValue>(var key, _): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Remove(key); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case DictionaryRemoveStateChange<TKey, TValue>(var key, var value): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Add( key, value); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case DictionaryChangeStateChange<TKey, TValue>(var key, _, var oldValue): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container[key] = oldValue; toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } default: { toInvokeOutsideLock = null; state = null; return false; } } return true; } /// <summary> /// Has the last undone operation redone. /// </summary> /// <param name="undoRedoLevel">A level of undo, with contents.</param> /// <param name="toInvokeOutsideLock">An action to invoke outside of the lock.</param> /// <param name="state">The state object to pass to the invocation.</param> /// <returns><see langword="true" /> if the redo was successful, <see langword="false" /> otherwise.</returns> protected override bool RedoInternally( StateChangeBase undoRedoLevel, out Action<object?>? toInvokeOutsideLock, out object? state) { if (base.RedoInternally( undoRedoLevel, out toInvokeOutsideLock, out state)) { return true; } switch (undoRedoLevel) { case AddStateChange<KeyValuePair<TKey, TValue>>(var (key, value), _): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Add( key, value); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case RemoveStateChange<KeyValuePair<TKey, TValue>>(_, var keyValuePair): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Remove(keyValuePair.Key); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case ClearStateChange<KeyValuePair<TKey, TValue>>: { this.InternalContainer.Clear(); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case DictionaryAddStateChange<TKey, TValue>(var key, var value): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Add( key, value); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case DictionaryRemoveStateChange<TKey, TValue>(var key, _): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container.Remove(key); toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } case DictionaryChangeStateChange<TKey, TValue>(var key, var newValue, _): { IDictionaryCollectionAdapter<TKey, TValue> container = this.InternalContainer; container[key] = newValue; toInvokeOutsideLock = innerState => { if (innerState == null) { return; } ((ObservableDictionary<TKey, TValue>)innerState).BroadcastChange(); }; state = this; break; } default: { toInvokeOutsideLock = null; state = null; return false; } } return true; } private void BroadcastChange() { this.RaiseCollectionReset(); this.RaisePropertyChanged(nameof(this.Keys)); this.RaisePropertyChanged(nameof(this.Values)); this.RaisePropertyChanged(nameof(this.Count)); this.RaisePropertyChanged(Constants.ItemsName); } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Composite Swagger for Compute Client /// </summary> public partial class ComputeManagementClient : Microsoft.Rest.ServiceClient<ComputeManagementClient>, IComputeManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAvailabilitySetsOperations. /// </summary> public virtual IAvailabilitySetsOperations AvailabilitySets { get; private set; } /// <summary> /// Gets the IVirtualMachineExtensionImagesOperations. /// </summary> public virtual IVirtualMachineExtensionImagesOperations VirtualMachineExtensionImages { get; private set; } /// <summary> /// Gets the IVirtualMachineExtensionsOperations. /// </summary> public virtual IVirtualMachineExtensionsOperations VirtualMachineExtensions { get; private set; } /// <summary> /// Gets the IVirtualMachineImagesOperations. /// </summary> public virtual IVirtualMachineImagesOperations VirtualMachineImages { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Gets the IVirtualMachineSizesOperations. /// </summary> public virtual IVirtualMachineSizesOperations VirtualMachineSizes { get; private set; } /// <summary> /// Gets the IVirtualMachinesOperations. /// </summary> public virtual IVirtualMachinesOperations VirtualMachines { get; private set; } /// <summary> /// Gets the IVirtualMachineScaleSetsOperations. /// </summary> public virtual IVirtualMachineScaleSetsOperations VirtualMachineScaleSets { get; private set; } /// <summary> /// Gets the IVirtualMachineScaleSetVMsOperations. /// </summary> public virtual IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMs { get; private set; } /// <summary> /// Gets the IContainerServiceOperations. /// </summary> public virtual IContainerServiceOperations ContainerService { get; private set; } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ComputeManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ComputeManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected ComputeManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected ComputeManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.AvailabilitySets = new AvailabilitySetsOperations(this); this.VirtualMachineExtensionImages = new VirtualMachineExtensionImagesOperations(this); this.VirtualMachineExtensions = new VirtualMachineExtensionsOperations(this); this.VirtualMachineImages = new VirtualMachineImagesOperations(this); this.Usage = new UsageOperations(this); this.VirtualMachineSizes = new VirtualMachineSizesOperations(this); this.VirtualMachines = new VirtualMachinesOperations(this); this.VirtualMachineScaleSets = new VirtualMachineScaleSetsOperations(this); this.VirtualMachineScaleSetVMs = new VirtualMachineScaleSetVMsOperations(this); this.ContainerService = new ContainerServiceOperations(this); this.BaseUri = new System.Uri("https://management.azure.com"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
// 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.Transactions.Tests { // Ported from Mono public class TransactionScopeTest { [Fact] public void TransactionScopeWithInvalidTimeSpanThrows() { Assert.Throws<ArgumentNullException>("transactionToUse", () => new TransactionScope(null, TimeSpan.FromSeconds(-1))); Assert.Throws<ArgumentOutOfRangeException>("scopeTimeout", () => new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(-1))); } [Fact] public void TransactionScopeCommit() { Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { Assert.NotNull(Transaction.Current); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); scope.Complete(); } Assert.Null(Transaction.Current); } [Fact] public void TransactionScopeAbort() { Assert.Null(Transaction.Current); IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope()) { Assert.NotNull(Transaction.Current); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); irm.Value = 2; /* Not completing scope here */ } irm.Check(0, 0, 1, 0, "irm"); Assert.Equal(1, irm.Value); Assert.Null(Transaction.Current); } [Fact] public void TransactionScopeCompleted1() { Assert.Throws<InvalidOperationException>(() => { using (TransactionScope scope = new TransactionScope()) { scope.Complete(); /* Can't access ambient transaction after scope.Complete */ TransactionStatus status = Transaction.Current.TransactionInformation.Status; } }); } [Fact] public void TransactionScopeCompleted2() { using (TransactionScope scope = new TransactionScope()) { scope.Complete(); Assert.Throws<InvalidOperationException>(() => { Transaction.Current = Transaction.Current; }); } } [Fact] public void TransactionScopeCompleted3() { Assert.Throws<InvalidOperationException>(() => { using (TransactionScope scope = new TransactionScope()) { scope.Complete(); scope.Complete(); } }); } #region NestedTransactionScope tests [Fact] public void NestedTransactionScope1() { IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; /* Complete this scope */ scope.Complete(); } Assert.Null(Transaction.Current); /* Value = 2, got committed */ Assert.Equal(irm.Value, 2); irm.Check(1, 1, 0, 0, "irm"); } [Fact] public void NestedTransactionScope2() { IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; /* Not-Completing this scope */ } Assert.Null(Transaction.Current); /* Value = 2, got rolledback */ Assert.Equal(irm.Value, 1); irm.Check(0, 0, 1, 0, "irm"); } [Fact] public void NestedTransactionScope3() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm2.Value = 20; scope2.Complete(); } scope.Complete(); } Assert.Null(Transaction.Current); /* Both got committed */ Assert.Equal(irm.Value, 2); Assert.Equal(irm2.Value, 20); irm.Check(1, 1, 0, 0, "irm"); irm2.Check(1, 1, 0, 0, "irm2"); } [Fact] public void NestedTransactionScope4() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm2.Value = 20; /* Inner Tx not completed, Tx should get rolled back */ //scope2.Complete(); } /* Both rolledback */ irm.Check(0, 0, 1, 0, "irm"); irm2.Check(0, 0, 1, 0, "irm2"); Assert.Equal(TransactionStatus.Aborted, Transaction.Current.TransactionInformation.Status); //scope.Complete (); } Assert.Null(Transaction.Current); Assert.Equal(irm.Value, 1); Assert.Equal(irm2.Value, 10); irm.Check(0, 0, 1, 0, "irm"); } [Fact] public void NestedTransactionScope5() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm2.Value = 20; scope2.Complete(); } Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); /* Not completing outer scope scope.Complete (); */ } Assert.Null(Transaction.Current); Assert.Equal(irm.Value, 1); Assert.Equal(irm2.Value, 10); irm.Check(0, 0, 1, 0, "irm"); irm2.Check(0, 0, 1, 0, "irm2"); } [Fact] public void NestedTransactionScope6() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew)) { irm2.Value = 20; scope2.Complete(); } /* vr2, committed */ irm2.Check(1, 1, 0, 0, "irm2"); Assert.Equal(irm2.Value, 20); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); scope.Complete(); } Assert.Null(Transaction.Current); Assert.Equal(irm.Value, 2); irm.Check(1, 1, 0, 0, "irm"); } [Fact] public void NestedTransactionScope7() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew)) { irm2.Value = 20; /* Not completing scope2.Complete();*/ } /* irm2, rolled back*/ irm2.Check(0, 0, 1, 0, "irm2"); Assert.Equal(irm2.Value, 10); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); scope.Complete(); } Assert.Null(Transaction.Current); /* ..But irm got committed */ Assert.Equal(irm.Value, 2); irm.Check(1, 1, 0, 0, "irm"); } [Fact] public void NestedTransactionScope8() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress)) { /* Not transactional, so this WONT get committed */ irm2.Value = 20; scope2.Complete(); } irm2.Check(0, 0, 0, 0, "irm2"); Assert.Equal(20, irm2.Value); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); scope.Complete(); } Assert.Null(Transaction.Current); Assert.Equal(irm.Value, 2); irm.Check(1, 1, 0, 0, "irm"); } [Fact] public void NestedTransactionScope8a() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress)) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm2.Value = 20; scope2.Complete(); } irm2.Check(1, 1, 0, 0, "irm2"); Assert.Equal(20, irm2.Value); scope.Complete(); } Assert.Null(Transaction.Current); Assert.Equal(2, irm.Value); irm.Check(0, 0, 0, 0, "irm"); } [Fact] public void NestedTransactionScope9() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress)) { /* Not transactional, so this WONT get committed */ irm2.Value = 4; scope2.Complete(); } irm2.Check(0, 0, 0, 0, "irm2"); using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.RequiresNew)) { irm.Value = 6; scope3.Complete(); } /* vr's value has changed as the inner scope committed = 6 */ irm.Check(1, 1, 0, 0, "irm"); Assert.Equal(irm.Value, 6); Assert.Equal(irm.Actual, 6); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); scope.Complete(); } Assert.Null(Transaction.Current); Assert.Equal(irm.Value, 6); irm.Check(2, 2, 0, 0, "irm"); } [Fact] public void NestedTransactionScope10() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm.Value = 4; /* Not completing this, so the transaction will * get aborted scope2.Complete (); */ } using (TransactionScope scope3 = new TransactionScope()) { /* Aborted transaction cannot be used for another * TransactionScope */ } } }); } [Fact] public void NestedTransactionScope12() { IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm.Value = 4; /* Not completing this, so the transaction will * get aborted scope2.Complete (); */ } using (TransactionScope scope3 = new TransactionScope(TransactionScopeOption.RequiresNew)) { /* Using RequiresNew here, so outer transaction * being aborted doesn't matter */ scope3.Complete(); } } } [Fact] public void NestedTransactionScope13() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; using (TransactionScope scope2 = new TransactionScope()) { irm.Value = 4; /* Not completing this, so the transaction will * get aborted scope2.Complete (); */ } scope.Complete(); } }); } #endregion /* Tests using IntResourceManager */ [Fact] public void RMFail1() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); IntResourceManager irm3 = new IntResourceManager(12); Assert.Null(Transaction.Current); try { using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; irm2.Value = 20; irm3.Value = 24; /* Make second RM fail to prepare, this should throw * TransactionAbortedException when the scope ends */ irm2.FailPrepare = true; scope.Complete(); } } catch (TransactionAbortedException) { irm.Check(1, 0, 1, 0, "irm"); irm2.Check(1, 0, 0, 0, "irm2"); irm3.Check(0, 0, 1, 0, "irm3"); } Assert.Null(Transaction.Current); } [Fact] [OuterLoop] // 30 second timeout public void RMFail2() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(10); IntResourceManager irm3 = new IntResourceManager(12); Assert.Null(Transaction.Current); TransactionAbortedException e = Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 30))) { irm.Value = 2; irm2.Value = 20; irm3.Value = 24; /* irm2 wont call Prepared or ForceRollback in * its Prepare (), so TransactionManager will timeout * waiting for it */ irm2.IgnorePrepare = true; scope.Complete(); } }); Assert.NotNull(e.InnerException); Assert.IsType<TimeoutException>(e.InnerException); Assert.Null(Transaction.Current); } #region Explicit Transaction Tests [Fact] public void ExplicitTransactionCommit() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); Assert.Equal(2, irm.Value); Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status); Transaction.Current = oldTransaction; } [Fact] public void ExplicitTransactionRollback() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; Assert.Equal(TransactionStatus.Active, ct.TransactionInformation.Status); ct.Rollback(); Assert.Equal(1, irm.Value); Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); } finally { Transaction.Current = oldTransaction; } } [Fact] public void ExplicitTransaction1() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; using (TransactionScope scope = new TransactionScope()) { Assert.Equal(ct, Transaction.Current); irm.Value = 4; scope.Complete(); } Assert.Equal(ct, Transaction.Current); Assert.Equal(TransactionStatus.Active, Transaction.Current.TransactionInformation.Status); Assert.Equal(1, irm.Actual); ct.Commit(); Assert.Equal(4, irm.Actual); Assert.Equal(TransactionStatus.Committed, Transaction.Current.TransactionInformation.Status); } finally { Transaction.Current = oldTransaction; } } [Fact] public void ExplicitTransaction2() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; using (TransactionScope scope = new TransactionScope()) { Assert.Equal(ct, Transaction.Current); /* Not calling scope.Complete scope.Complete ();*/ } Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); Assert.Equal(ct, Transaction.Current); Assert.Equal(1, irm.Actual); Assert.Equal(1, irm.NumRollback); irm.Check(0, 0, 1, 0, "irm"); } finally { Transaction.Current = oldTransaction; } Assert.Throws<TransactionAbortedException>(() => ct.Commit()); } [Fact] public void ExplicitTransaction3() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; Transaction.Current = ct; try { IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { Assert.True(ct != Transaction.Current, "Scope with RequiresNew should have a new ambient transaction"); irm.Value = 3; scope.Complete(); } irm.Value = 2; Assert.Equal(3, irm.Actual); Assert.Equal(ct, Transaction.Current); ct.Commit(); Assert.Equal(2, irm.Actual); } finally { Transaction.Current = oldTransaction; } } [Fact] public void ExplicitTransaction4() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; /* Not setting ambient transaction Transaction.Current = ct; */ IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(ct)) { Assert.Equal(ct, Transaction.Current); irm.Value = 2; scope.Complete(); } Assert.Equal(oldTransaction, Transaction.Current); Assert.Equal(TransactionStatus.Active, ct.TransactionInformation.Status); Assert.Equal(1, irm.Actual); ct.Commit(); Assert.Equal(2, irm.Actual); Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status); irm.Check(1, 1, 0, 0, "irm"); } [Fact] public void ExplicitTransaction5() { Assert.Null(Transaction.Current); CommittableTransaction ct = new CommittableTransaction(); Transaction oldTransaction = Transaction.Current; /* Not setting ambient transaction Transaction.Current = ct; */ IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(ct)) { Assert.Equal(ct, Transaction.Current); irm.Value = 2; /* Not completing this scope scope.Complete (); */ } Assert.Equal(oldTransaction, Transaction.Current); Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); Assert.Equal(1, irm.Actual); irm.Check(0, 0, 1, 0, "irm"); } [Fact] public void ExplicitTransaction6() { Assert.Throws<InvalidOperationException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); ct.Commit(); }); } [Fact] public void ExplicitTransaction6a() { Assert.Throws<InvalidOperationException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); /* Using a already committed transaction in a new * TransactionScope */ TransactionScope scope = new TransactionScope(ct); }); } [Fact] public void ExplicitTransaction6b() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { TransactionScope scope1 = new TransactionScope(); /* Enlist */ irm.Value = 2; scope1.Complete(); Assert.Throws<TransactionAbortedException>(() => ct.Commit()); irm.Check(0, 0, 1, 0, "irm"); scope1.Dispose(); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction6c() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { TransactionScope scope1 = new TransactionScope(TransactionScopeOption.RequiresNew); /* Enlist */ irm.Value = 2; TransactionScope scope2 = new TransactionScope(); Assert.Throws<InvalidOperationException>(() => scope1.Dispose()); irm.Check(0, 0, 1, 0, "irm"); scope2.Dispose(); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction6d() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { TransactionScope scope1 = new TransactionScope(); /* Enlist */ irm.Value = 2; TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew); Assert.Throws<InvalidOperationException>(() => scope1.Dispose()); scope2.Dispose(); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction6e() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { TransactionScope scope1 = new TransactionScope(); /* Enlist */ irm.Value = 2; TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress); Assert.Throws<InvalidOperationException>(() => scope1.Dispose()); scope2.Dispose(); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction7() { Assert.Throws<TransactionException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Value = 2; ct.Commit(); /* Cannot accept any new work now, so TransactionException */ ct.Rollback(); }); } [Fact] public void ExplicitTransaction8() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(ct)) { irm.Value = 2; Assert.Throws<TransactionAbortedException>(() => ct.Commit()); /* FIXME: Why TransactionAbortedException ?? */ irm.Check(0, 0, 1, 0, "irm"); } } [Fact] public void ExplicitTransaction8a() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope(ct)) { irm.Value = 2; scope.Complete(); Assert.Throws<TransactionAbortedException>(() => ct.Commit()); /* FIXME: Why TransactionAbortedException ?? */ irm.Check(0, 0, 1, 0, "irm"); } } [Fact] public void ExplicitTransaction9() { Assert.Throws<InvalidOperationException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); ct.BeginCommit(null, null); ct.BeginCommit(null, null); }); } [Fact] public void ExplicitTransaction10() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { irm.Value = 2; TransactionScope scope = new TransactionScope(ct); Assert.Equal(ct, Transaction.Current); Assert.Throws<TransactionAbortedException>(() => ct.Commit()); irm.Check(0, 0, 1, 0, "irm"); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction10a() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { irm.Value = 2; Transaction.Current = null; TransactionScope scope = new TransactionScope(ct); Assert.Equal(ct, Transaction.Current); Transaction.Current = null; Assert.Throws<TransactionAbortedException>(() => ct.Commit()); irm.Check(0, 0, 1, 0, "irm"); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction10b() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; try { irm.Value = 2; Transaction.Current = null; TransactionScope scope = new TransactionScope(ct); Assert.Equal(ct, Transaction.Current); IAsyncResult ar = ct.BeginCommit(null, null); Assert.Throws<TransactionAbortedException>(() => ct.EndCommit(ar)); irm.Check(0, 0, 1, 0, "irm"); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction12() { Assert.Throws<ArgumentException>(() => { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.FailPrepare = true; ct.BeginCommit(null, null); ct.EndCommit(null); }); } [Fact] public void ExplicitTransaction13() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); Transaction.Current = ct; try { irm.Value = 2; irm.FailPrepare = true; Assert.Throws<TransactionAbortedException>(() => ct.Commit()); Assert.Equal(TransactionStatus.Aborted, ct.TransactionInformation.Status); Assert.Throws<InvalidOperationException>(() => ct.BeginCommit(null, null)); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction14() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); Transaction.Current = ct; try { irm.Value = 2; ct.Commit(); Assert.Equal(TransactionStatus.Committed, ct.TransactionInformation.Status); Assert.Throws<InvalidOperationException>(() => ct.BeginCommit(null, null)); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction15() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(3); Assert.Null(Transaction.Current); Transaction.Current = ct; try { Assert.Throws<InvalidOperationException>(() => { using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; Transaction.Current = new CommittableTransaction(); irm2.Value = 6; } }); irm.Check(0, 0, 1, 0, "irm"); irm2.Check(0, 0, 1, 0, "irm2"); } finally { Transaction.Current = null; } } [Fact] public void ExplicitTransaction16() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm0 = new IntResourceManager(3); IntResourceManager irm = new IntResourceManager(1); Assert.Null(Transaction.Current); Transaction.Current = ct; try { irm.FailPrepare = true; irm.FailWithException = true; irm.Value = 2; irm0.Value = 6; var e = Assert.Throws<TransactionAbortedException>(() => ct.Commit()); Assert.NotNull(e.InnerException); Assert.IsType<NotSupportedException>(e.InnerException); irm.Check(1, 0, 0, 0, "irm"); irm0.Check(0, 0, 1, 0, "irm0"); } finally { Transaction.Current = null; } } #endregion } }
//--------------------------------------------------------------------------- // // File: HtmlLexicalAnalyzer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Lexical analyzer for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.IO; using System.Diagnostics; using System.Collections; using System.Text; namespace Html { /// <summary> /// lexical analyzer class /// recognizes tokens as groups of characters separated by arbitrary amounts of whitespace /// also classifies tokens according to type /// </summary> internal class HtmlLexicalAnalyzer { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// initializes the _inputStringReader member with the string to be read /// also sets initial values for _nextCharacterCode and _nextTokenType /// </summary> /// <param name="inputTextString"> /// text string to be parsed for xml content /// </param> internal HtmlLexicalAnalyzer(string inputTextString) { _inputStringReader = new StringReader(inputTextString); _nextCharacterCode = 0; _nextCharacter = ' '; _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; _previousCharacter = ' '; _ignoreNextWhitespace = true; _nextToken = new StringBuilder(100); _nextTokenType = HtmlTokenType.Text; // read the first character so we have some value for the NextCharacter property this.GetNextCharacter(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// retrieves next recognizable token from input string /// and identifies its type /// if no valid token is found, the output parameters are set to null /// if end of stream is reached without matching any token, token type /// paramter is set to EOF /// </summary> internal void GetNextContentToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } if (this.IsAtTagStart) { this.GetNextCharacter(); if (this.NextCharacter == '/') { _nextToken.Append("</"); _nextTokenType = HtmlTokenType.ClosingTagStart; // advance this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespaces after closing tags are significant } else { _nextTokenType = HtmlTokenType.OpeningTagStart; _nextToken.Append("<"); _ignoreNextWhitespace = true; // Whitespaces after opening tags are insignificant } } else if (this.IsAtDirectiveStart) { // either a comment or CDATA this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // cdata this.ReadDynamicContent(); } else if (_lookAheadCharacter == '-') { this.ReadComment(); } else { // neither a comment nor cdata, should be something like DOCTYPE // skip till the next tag ender this.ReadUnknownDirective(); } } else { // read text content, unless you encounter a tag _nextTokenType = HtmlTokenType.Text; while (!this.IsAtTagStart && !this.IsAtEndOfStream && !this.IsAtDirectiveStart) { if (this.NextCharacter == '<' && !this.IsNextCharacterEntity && _lookAheadCharacter == '?') { // ignore processing directive this.SkipProcessingDirective(); } else { if (this.NextCharacter <= ' ') { // Respect xml:preserve or its equivalents for whitespace processing if (_ignoreNextWhitespace) { // Ignore repeated whitespaces } else { // Treat any control character sequence as one whitespace _nextToken.Append(' '); } _ignoreNextWhitespace = true; // and keep ignoring the following whitespaces } else { _nextToken.Append(this.NextCharacter); _ignoreNextWhitespace = false; } this.GetNextCharacter(); } } } } /// <summary> /// Unconditionally returns a token which is one of: TagEnd, EmptyTagEnd, Name, Atom or EndOfStream /// Does not guarantee token reader advancing. /// </summary> internal void GetNextTagToken() { _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } this.SkipWhiteSpace(); if (this.NextCharacter == '>' && !this.IsNextCharacterEntity) { // &gt; should not end a tag, so make sure it's not an entity _nextTokenType = HtmlTokenType.TagEnd; _nextToken.Append('>'); this.GetNextCharacter(); // Note: _ignoreNextWhitespace must be set appropriately on tag start processing } else if (this.NextCharacter == '/' && _lookAheadCharacter == '>') { // could be start of closing of empty tag _nextTokenType = HtmlTokenType.EmptyTagEnd; _nextToken.Append("/>"); this.GetNextCharacter(); this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespace after no-scope tags are sifnificant } else if (IsGoodForNameStart(this.NextCharacter)) { _nextTokenType = HtmlTokenType.Name; // starts a name // we allow character entities here // we do not throw exceptions here if end of stream is encountered // just stop and return whatever is in the token // if the parser is not expecting end of file after this it will call // the get next token function and throw an exception while (IsGoodForName(this.NextCharacter) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } else { // Unexpected type of token for a tag. Reprot one character as Atom, expecting that HtmlParser will ignore it. _nextTokenType = HtmlTokenType.Atom; _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns equal sign token. Even if there is no /// real equal sign in the stream, it behaves as if it were there. /// Does not guarantee token reader advancing. /// </summary> internal void GetNextEqualSignToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; _nextToken.Append('='); _nextTokenType = HtmlTokenType.EqualSign; this.SkipWhiteSpace(); if (this.NextCharacter == '=') { // '=' is not in the list of entities, so no need to check for entities here this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns an atomic value for an attribute /// Even if there is no appropriate token it returns Atom value /// Does not guarantee token reader advancing. /// </summary> internal void GetNextAtomToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; this.SkipWhiteSpace(); _nextTokenType = HtmlTokenType.Atom; if ((this.NextCharacter == '\'' || this.NextCharacter == '"') && !this.IsNextCharacterEntity) { char startingQuote = this.NextCharacter; this.GetNextCharacter(); // Consume all characters between quotes while (!(this.NextCharacter == startingQuote && !this.IsNextCharacterEntity) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } if (this.NextCharacter == startingQuote) { this.GetNextCharacter(); } // complete the quoted value // NOTE: our recovery here is different from IE's // IE keeps reading until it finds a closing quote or end of file // if end of file, it treats current value as text // if it finds a closing quote at any point within the text, it eats everything between the quotes // TODO: Suggestion: // however, we could stop when we encounter end of file or an angle bracket of any kind // and assume there was a quote there // so the attribute value may be meaningless but it is never treated as text } else { while (!this.IsAtEndOfStream && !Char.IsWhiteSpace(this.NextCharacter) && this.NextCharacter != '>') { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties internal HtmlTokenType NextTokenType { get { return _nextTokenType; } } internal string NextToken { get { return _nextToken.ToString(); } } #endregion Internal Properties // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Advances a reading position by one character code /// and reads the next availbale character from a stream. /// This character becomes available as NextCharacter property. /// </summary> /// <remarks> /// Throws InvalidOperationException if attempted to be called on EndOfStream /// condition. /// </remarks> private void GetNextCharacter() { if (_nextCharacterCode == -1) { throw new InvalidOperationException("GetNextCharacter method called at the end of a stream"); } _previousCharacter = _nextCharacter; _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; // next character not an entity as of now _isNextCharacterEntity = false; this.ReadLookAheadCharacter(); if (_nextCharacter == '&') { if (_lookAheadCharacter == '#') { // numeric entity - parse digits - &#DDDDD; int entityCode; entityCode = 0; this.ReadLookAheadCharacter(); // largest numeric entity is 7 characters for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++) { entityCode = 10 * entityCode + (_lookAheadCharacterCode - (int)'0'); this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // correct format - advance this.ReadLookAheadCharacter(); _nextCharacterCode = entityCode; // if this is out of range it will set the character to '?' _nextCharacter = (char)_nextCharacterCode; // as far as we are concerned, this is an entity _isNextCharacterEntity = true; } else { // not an entity, set next character to the current lookahread character // we would have eaten up some digits _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } else if (Char.IsLetter(_lookAheadCharacter)) { // entity is written as a string string entity = ""; // maximum length of string entities is 10 characters for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++) { entity += _lookAheadCharacter; this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // advance this.ReadLookAheadCharacter(); if (HtmlSchema.IsEntity(entity)) { _nextCharacter = HtmlSchema.EntityCharacterValue(entity); _nextCharacterCode = (int)_nextCharacter; _isNextCharacterEntity = true; } else { // just skip the whole thing - invalid entity // move on to the next character _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); // not an entity _isNextCharacterEntity = false; } } else { // skip whatever we read after the ampersand // set next character and move on _nextCharacter = _lookAheadCharacter; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } } } private void ReadLookAheadCharacter() { if (_lookAheadCharacterCode != -1) { _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; } } /// <summary> /// skips whitespace in the input string /// leaves the first non-whitespace character available in the NextCharacter property /// this may be the end-of-file character, it performs no checking /// </summary> private void SkipWhiteSpace() { // TODO: handle character entities while processing comments, cdata, and directives // TODO: SUGGESTION: we could check if lookahead and previous characters are entities also while (true) { if (_nextCharacter == '<' && (_lookAheadCharacter == '?' || _lookAheadCharacter == '!')) { this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // Skip CDATA block and DTDs(?) while (!this.IsAtEndOfStream && !(_previousCharacter == ']' && _nextCharacter == ']' && _lookAheadCharacter == '>')) { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } else { // Skip processing instruction, comments while (!this.IsAtEndOfStream && _nextCharacter != '>') { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } } if (!Char.IsWhiteSpace(this.NextCharacter)) { break; } this.GetNextCharacter(); } } /// <summary> /// checks if a character can be used to start a name /// if this check is true then the rest of the name can be read /// </summary> /// <param name="character"> /// character value to be checked /// </param> /// <returns> /// true if the character can be the first character in a name /// false otherwise /// </returns> private bool IsGoodForNameStart(char character) { return character == '_' || Char.IsLetter(character); } /// <summary> /// checks if a character can be used as a non-starting character in a name /// uses the IsExtender and IsCombiningCharacter predicates to see /// if a character is an extender or a combining character /// </summary> /// <param name="character"> /// character to be checked for validity in a name /// </param> /// <returns> /// true if the character can be a valid part of a name /// </returns> private bool IsGoodForName(char character) { // we are not concerned with escaped characters in names // we assume that character entities are allowed as part of a name return this.IsGoodForNameStart(character) || character == '.' || character == '-' || character == ':' || Char.IsDigit(character) || IsCombiningCharacter(character) || IsExtender(character); } /// <summary> /// identifies a character as being a combining character, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of combining characters in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is a combining character, false otherwise /// </returns> private bool IsCombiningCharacter(char character) { // TODO: put actual code with checks against all combining characters here return false; } /// <summary> /// identifies a character as being an extender, permitted in a name /// TODO: only a placeholder for now but later to be replaced with comparisons against /// the list of extenders in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is an extender, false otherwise /// </returns> private bool IsExtender(char character) { // TODO: put actual code with checks against all extenders here return false; } /// <summary> /// skips dynamic content starting with '<![' and ending with ']>' /// </summary> private void ReadDynamicContent() { // verify that we are at dynamic content, which may include CDATA Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '['); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance twice, once to get the lookahead character and then to reach the start of the cdata this.GetNextCharacter(); this.GetNextCharacter(); // NOTE: 10/12/2004: modified this function to check when called if's reading CDATA or something else // some directives may start with a <![ and then have some data and they will just end with a ]> // this function is modified to stop at the sequence ]> and not ]]> // this means that CDATA and anything else expressed in their own set of [] within the <! [...]> // directive cannot contain a ]> sequence. However it is doubtful that cdata could contain such // sequence anyway, it probably stops at the first ] while (!(_nextCharacter == ']' && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } /// <summary> /// skips comments starting with '<!-' and ending with '-->' /// NOTE: 10/06/2004: processing changed, will now skip anything starting with /// the "<!-" sequence and ending in "!>" or "->", because in practice many html pages do not /// use the full comment specifying conventions /// </summary> private void ReadComment() { // verify that we are at a comment Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '-'); // Initialize a token _nextTokenType = HtmlTokenType.Comment; _nextToken.Length = 0; // advance to the next character, so that to be at the start of comment value this.GetNextCharacter(); // get first '-' this.GetNextCharacter(); // get second '-' this.GetNextCharacter(); // get first character of comment content while (true) { // Read text until end of comment // Note that in many actual html pages comments end with "!>" (while xml standard is "-->") while (!this.IsAtEndOfStream && !(_nextCharacter == '-' && _lookAheadCharacter == '-' || _nextCharacter == '!' && _lookAheadCharacter == '>')) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } // Finish comment reading this.GetNextCharacter(); if (_previousCharacter == '-' && _nextCharacter == '-' && _lookAheadCharacter == '>') { // Standard comment end. Eat it and exit the loop this.GetNextCharacter(); // get '>' break; } else if (_previousCharacter == '!' && _nextCharacter == '>') { // Nonstandard but possible comment end - '!>'. Exit the loop break; } else { // Not an end. Save character and continue continue reading _nextToken.Append(_previousCharacter); continue; } } // Read end of comment combination if (_nextCharacter == '>') { this.GetNextCharacter(); } } /// <summary> /// skips past unknown directives that start with "<!" but are not comments or Cdata /// ignores content of such directives until the next ">" character /// applies to directives such as DOCTYPE, etc that we do not presently support /// </summary> private void ReadUnknownDirective() { // verify that we are at an unknown directive Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && !(_lookAheadCharacter == '-' || _lookAheadCharacter == '[')); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance to the next character this.GetNextCharacter(); // skip to the first tag end we find while (!(_nextCharacter == '>' && !IsNextCharacterEntity) && !this.IsAtEndOfStream) { this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance past the tag end this.GetNextCharacter(); } } /// <summary> /// skips processing directives starting with the characters '<?' and ending with '?>' /// NOTE: 10/14/2004: IE also ends processing directives with a />, so this function is /// being modified to recognize that condition as well /// </summary> private void SkipProcessingDirective() { // verify that we are at a processing directive Debug.Assert(_nextCharacter == '<' && _lookAheadCharacter == '?'); // advance twice, once to get the lookahead character and then to reach the start of the drective this.GetNextCharacter(); this.GetNextCharacter(); while (!((_nextCharacter == '?' || _nextCharacter == '/') && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance // we don't need to check for entities here because '?' is not an entity // and even though > is an entity there is no entity processing when reading lookahead character this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Properties // // --------------------------------------------------------------------- #region Private Properties private char NextCharacter { get { return _nextCharacter; } } private bool IsAtEndOfStream { get { return _nextCharacterCode == -1; } } private bool IsAtTagStart { get { return _nextCharacter == '<' && (_lookAheadCharacter == '/' || IsGoodForNameStart(_lookAheadCharacter)) && !_isNextCharacterEntity; } } private bool IsAtTagEnd { // check if at end of empty tag or regular tag get { return (_nextCharacter == '>' || (_nextCharacter == '/' && _lookAheadCharacter == '>')) && !_isNextCharacterEntity; } } private bool IsAtDirectiveStart { get { return (_nextCharacter == '<' && _lookAheadCharacter == '!' && !this.IsNextCharacterEntity); } } private bool IsNextCharacterEntity { // check if next character is an entity get { return _isNextCharacterEntity; } } #endregion Private Properties // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // string reader which will move over input text private StringReader _inputStringReader; // next character code read from input that is not yet part of any token // and the character it represents private int _nextCharacterCode; private char _nextCharacter; private int _lookAheadCharacterCode; private char _lookAheadCharacter; private char _previousCharacter; private bool _ignoreNextWhitespace; private bool _isNextCharacterEntity; // store token and type in local variables before copying them to output parameters StringBuilder _nextToken; HtmlTokenType _nextTokenType; #endregion Private Fields } }
using System; using System.Collections.Specialized; using Skybrud.Social.Vimeo.Advanced.Enums; namespace Skybrud.Social.Vimeo.Advanced.Endpoints.Raw { public class VimeoChannelsRawEndpoint { public VimeoOAuthClient Client { get; private set; } public VimeoChannelsRawEndpoint(VimeoOAuthClient client) { Client = client; } #region Method: vimeo.channels.addVideo /// <summary> /// Adds a video to a channel and returns the raw JSON response from the server. /// /// API description: Add a video to a channel. This method requires a token with write permission. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> /// <param name="videoId">The ID of the video.</param> public string AddVideo(string channelId, int videoId) { return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.addVideo"}, {"channel_id", channelId}, {"video_id", videoId + ""} }, null); } #endregion #region Method: vimeo.channels.getAll public string GetAll() { return GetAll(null, 0, 0); } public string GetAll(string username) { return GetAll(username, 0, 0); } /// <summary> /// Gets the raw JSON response for the channels on the specified page. /// </summary> /// <param name="username">The username or user ID behind a user. </param> /// <param name="page">The page number to show.</param> /// <param name="perPage">Number of items to show on each page. Max 50.</param> /// <returns></returns> public string GetAll(string username, int page, int perPage) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getAll"} }; // Add optional parameters if (!String.IsNullOrEmpty(username)) query.Add("user_id", username); if (page > 0) query.Add("page", page + ""); if (perPage > 0) query.Add("per_page", perPage + ""); // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } public string GetAll(string username, VimeoChannelsSort sort, int page, int perPage) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getAll"} }; // Add optional parameters if (!String.IsNullOrEmpty(username)) query.Add("user_id", username); if (sort != VimeoChannelsSort.Default) query.Add("sort", SocialUtils.CamelCaseToUnderscore(sort)); if (page > 0) query.Add("page", page + ""); if (perPage > 0) query.Add("per_page", perPage + ""); // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } #endregion #region Method: vimeo.channels.getInfo /// <summary> /// API description: Get the information on a single channel. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> public string GetInfoAsRawJson(string channelId) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getInfo"}, {"channel_id", channelId} }; // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } #endregion #region Method: vimeo.channels.getModerated /// <summary> /// API description: Get a list of the channels that a user moderates. /// </summary> /// <param name="username">The username or user ID behind a user. </param> /// <param name="sort">How the response should be sorted.</param> /// <param name="page">The page number to show.</param> /// <param name="perPage">Number of items to show on each page. Max 50.</param> public string GetModerated(string username, VimeoChannelsSort sort, int page, int perPage) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getModerated"} }; if (!String.IsNullOrEmpty(username)) query.Add("user_id", username); if (sort != VimeoChannelsSort.Default) query.Add("sort", SocialUtils.CamelCaseToUnderscore(sort)); if (page > 0) query.Add("page", page + ""); if (perPage > 0) query.Add("per_page", perPage + ""); // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } #endregion #region Method: vimeo.channels.getModerators /// <summary> /// API description: Get a list of the channel's moderators. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> public string GetModerators(int channelId) { return GetModerators(channelId, 0, 0); } /// <summary> /// API description: Get a list of the channel's moderators. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> /// <param name="page">The page number to show.</param> /// <param name="perPage">Number of items to show on each page. Max 50.</param> public string GetModerators(int channelId, int page, int perPage) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getModerators"}, {"channel_id", channelId + ""} }; if (page > 0) query.Add("page", page + ""); if (perPage > 0) query.Add("per_page", perPage + ""); // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } #endregion #region Method: vimeo.channels.getSubscribers /// <summary> /// API description: Get a list of the channel's subscribers. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> public string GetSubscribers(int channelId) { return GetSubscribers(channelId, 0, 0); } /// <summary> /// API description: Get a list of the channel's subscribers. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> /// <param name="page">The page number to show.</param> /// <param name="perPage">Number of items to show on each page. Max 50.</param> public string GetSubscribers(int channelId, int page, int perPage) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getSubscribers"}, {"channel_id", channelId + ""} }; if (page > 0) query.Add("page", page + ""); if (perPage > 0) query.Add("per_page", perPage + ""); // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } #endregion #region Method: vimeo.channels.getVideos /// <summary> /// API description: Get a list of the videos in a channel. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> public string GetVideos(int channelId) { return GetVideos(channelId, 0, 0); } /// <summary> /// API description: Get a list of the videos in a channel. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> /// <param name="page">The page number to show.</param> /// <param name="perPage">Number of items to show on each page. Max 50.</param> public string GetVideos(int channelId, int page, int perPage) { return GetVideos(channelId, null, page, perPage, false, false); } public string GetVideos(int channelId, string username, int page, int perPage, bool summaryResponse, bool fullResponse) { // Initialize the query string NameValueCollection query = new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.getVideos"}, {"channel_id", channelId + ""} }; if (!String.IsNullOrEmpty(username)) query.Add("user_id", username); if (page > 0) query.Add("page", page + ""); if (perPage > 0) query.Add("per_page", perPage + ""); if (summaryResponse) query.Add("summary_response", "1"); if (fullResponse) query.Add("full_response", "1"); // Call the Vimeo API return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", query, null); } #endregion #region Method: vimeo.channels.removeVideo /// <summary> /// API description: Remove a video from a channel. This method requires a token with write permission. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> /// <param name="videoId">The ID of the video.</param> public string RemoveVideo(string channelId, int videoId) { return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.removeVideo"}, {"channel_id", channelId}, {"video_id", videoId + ""} }, null); } #endregion #region Method: vimeo.channels.subscribe /// <summary> /// API description: Subscribe a user to a channel. This method requires a token with write permission. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> public string Subscribe(string channelId) { return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.subscribe"}, {"channel_id", channelId} }, null); } #endregion #region Method: vimeo.channels.unsubscribe /// <summary> /// API description: Unsubscribe a user from a channel. This method requires a token with write permission. /// </summary> /// <param name="channelId">The numeric id of the channel or its url name.</param> public string Unsubscribe(string channelId) { return Client.DoHttpRequestAsString("GET", "http://vimeo.com/api/rest/v2", new NameValueCollection { {"format", "json"}, {"method", "vimeo.channels.unsubscribe"}, {"channel_id", channelId} }, null); } #endregion } }
/* * 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.Reflection; using System.Threading; using log4net; using Nini.Config; using Nwc.XmlRpc; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Hypergrid; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.Avatar.Friends { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGFriendsModule")] public class HGFriendsModule : FriendsModule, ISharedRegionModule, IFriendsModule, IFriendsSimConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private int m_levelHGFriends = 0; IUserManagement m_uMan; public IUserManagement UserManagementModule { get { if (m_uMan == null) m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>(); return m_uMan; } } protected HGFriendsServicesConnector m_HGFriendsConnector = new HGFriendsServicesConnector(); protected HGStatusNotifier m_StatusNotifier; #region ISharedRegionModule public override string Name { get { return "HGFriendsModule"; } } public override void AddRegion(Scene scene) { if (!m_Enabled) return; base.AddRegion(scene); scene.RegisterModuleInterface<IFriendsSimConnector>(this); } public override void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_StatusNotifier == null) m_StatusNotifier = new HGStatusNotifier(this); } protected override void InitModule(IConfigSource config) { base.InitModule(config); // Additionally to the base method IConfig friendsConfig = config.Configs["HGFriendsModule"]; if (friendsConfig != null) { m_levelHGFriends = friendsConfig.GetInt("LevelHGFriends", 0); // TODO: read in all config variables pertaining to // HG friendship permissions } } #endregion #region IFriendsSimConnector /// <summary> /// Notify the user that the friend's status changed /// </summary> /// <param name="userID">user to be notified</param> /// <param name="friendID">friend whose status changed</param> /// <param name="online">status</param> /// <returns></returns> public bool StatusNotify(UUID friendID, UUID userID, bool online) { return LocalStatusNotification(friendID, userID, online); } #endregion protected override void OnInstantMessage(IClientAPI client, GridInstantMessage im) { if ((InstantMessageDialog)im.dialog == InstantMessageDialog.FriendshipOffered) { // we got a friendship offer UUID principalID = new UUID(im.fromAgentID); UUID friendID = new UUID(im.toAgentID); // Check if friendID is foreigner and if principalID has the permission // to request friendships with foreigners. If not, return immediately. if (!UserManagementModule.IsLocalGridUser(friendID)) { ScenePresence avatar = null; ((Scene)client.Scene).TryGetScenePresence(principalID, out avatar); if (avatar == null) return; if (avatar.GodController.UserLevel < m_levelHGFriends) { client.SendAgentAlertMessage("Unable to send friendship invitation to foreigner. Insufficient permissions.", false); return; } } } base.OnInstantMessage(client, im); } protected override void OnApproveFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders) { // Update the local cache. Yes, we need to do it right here // because the HGFriendsService placed something on the DB // from under the sim base.OnApproveFriendRequest(client, friendID, callingCardFolders); } protected override bool CacheFriends(IClientAPI client) { // m_log.DebugFormat("[HGFRIENDS MODULE]: Entered CacheFriends for {0}", client.Name); if (base.CacheFriends(client)) { UUID agentID = client.AgentId; // we do this only for the root agent if (m_Friends[agentID].Refcount == 1) { // We need to preload the user management cache with the names // of foreign friends, just like we do with SOPs' creators foreach (FriendInfo finfo in m_Friends[agentID].Friends) { if (finfo.TheirFlags != -1) { UUID id; if (!UUID.TryParse(finfo.Friend, out id)) { string url = string.Empty, first = string.Empty, last = string.Empty, tmp = string.Empty; if (Util.ParseUniversalUserIdentifier(finfo.Friend, out id, out url, out first, out last, out tmp)) { IUserManagement uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>(); m_log.DebugFormat("[HGFRIENDS MODULE]: caching {0}", finfo.Friend); uMan.AddUser(id, url + ";" + first + " " + last); } } } } // m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting CacheFriends for {0} since detected root agent", client.Name); return true; } } // m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting CacheFriends for {0} since detected not root agent", client.Name); return false; } public override bool SendFriendsOnlineIfNeeded(IClientAPI client) { // m_log.DebugFormat("[HGFRIENDS MODULE]: Entering SendFriendsOnlineIfNeeded for {0}", client.Name); if (base.SendFriendsOnlineIfNeeded(client)) { AgentCircuitData aCircuit = ((Scene)client.Scene).AuthenticateHandler.GetAgentCircuitData(client.AgentId); if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0) { UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.ScopeID, client.AgentId); if (account == null) // foreign { FriendInfo[] friends = GetFriendsFromCache(client.AgentId); foreach (FriendInfo f in friends) { int rights = f.TheirFlags; if(rights != -1 ) client.SendChangeUserRights(new UUID(f.Friend), client.AgentId, rights); } } } } // m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting SendFriendsOnlineIfNeeded for {0}", client.Name); return false; } protected override void GetOnlineFriends(UUID userID, List<string> friendList, /*collector*/ List<UUID> online) { // m_log.DebugFormat("[HGFRIENDS MODULE]: Entering GetOnlineFriends for {0}", userID); List<string> fList = new List<string>(); foreach (string s in friendList) { if (s.Length < 36) m_log.WarnFormat( "[HGFRIENDS MODULE]: Ignoring friend {0} ({1} chars) for {2} since identifier too short", s, s.Length, userID); else fList.Add(s.Substring(0, 36)); } // FIXME: also query the presence status of friends in other grids (like in HGStatusNotifier.Notify()) PresenceInfo[] presence = PresenceService.GetAgents(fList.ToArray()); foreach (PresenceInfo pi in presence) { UUID presenceID; if (UUID.TryParse(pi.UserID, out presenceID)) online.Add(presenceID); } // m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting GetOnlineFriends for {0}", userID); } protected override void StatusNotify(List<FriendInfo> friendList, UUID userID, bool online) { //m_log.DebugFormat("[HGFRIENDS MODULE]: Entering StatusNotify for {0}", userID); // First, let's divide the friends on a per-domain basis Dictionary<string, List<FriendInfo>> friendsPerDomain = new Dictionary<string, List<FriendInfo>>(); foreach (FriendInfo friend in friendList) { UUID friendID; if (UUID.TryParse(friend.Friend, out friendID)) { if (!friendsPerDomain.ContainsKey("local")) friendsPerDomain["local"] = new List<FriendInfo>(); friendsPerDomain["local"].Add(friend); } else { // it's a foreign friend string url = string.Empty, tmp = string.Empty; if (Util.ParseUniversalUserIdentifier(friend.Friend, out friendID, out url, out tmp, out tmp, out tmp)) { // Let's try our luck in the local sim. Who knows, maybe it's here if (LocalStatusNotification(userID, friendID, online)) continue; if (!friendsPerDomain.ContainsKey(url)) friendsPerDomain[url] = new List<FriendInfo>(); friendsPerDomain[url].Add(friend); } } } // For the local friends, just call the base method // Let's do this first of all if (friendsPerDomain.ContainsKey("local")) base.StatusNotify(friendsPerDomain["local"], userID, online); m_StatusNotifier.Notify(userID, friendsPerDomain, online); // m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting StatusNotify for {0}", userID); } protected override bool GetAgentInfo(UUID scopeID, string fid, out UUID agentID, out string first, out string last) { first = "Unknown"; last = "UserHGGAI"; if (base.GetAgentInfo(scopeID, fid, out agentID, out first, out last)) return true; // fid is not a UUID... string url = string.Empty, tmp = string.Empty, f = string.Empty, l = string.Empty; if (Util.ParseUniversalUserIdentifier(fid, out agentID, out url, out f, out l, out tmp)) { if (!agentID.Equals(UUID.Zero)) { m_uMan.AddUser(agentID, f, l, url); string name = m_uMan.GetUserName(agentID); string[] parts = name.Trim().Split(new char[] { ' ' }); if (parts.Length == 2) { first = parts[0]; last = parts[1]; } else { first = f; last = l; } return true; } } return false; } protected override string GetFriendshipRequesterName(UUID agentID) { return m_uMan.GetUserName(agentID); } protected override string FriendshipMessage(string friendID) { UUID id; if (UUID.TryParse(friendID, out id)) return base.FriendshipMessage(friendID); return "Please confirm this friendship you made while you where on another HG grid"; } protected override FriendInfo GetFriend(FriendInfo[] friends, UUID friendID) { foreach (FriendInfo fi in friends) { if (fi.Friend.StartsWith(friendID.ToString())) return fi; } return null; } public override FriendInfo[] GetFriendsFromService(IClientAPI client) { // m_log.DebugFormat("[HGFRIENDS MODULE]: Entering GetFriendsFromService for {0}", client.Name); Boolean agentIsLocal = true; if (UserManagementModule != null) agentIsLocal = UserManagementModule.IsLocalGridUser(client.AgentId); if (agentIsLocal) return base.GetFriendsFromService(client); FriendInfo[] finfos = new FriendInfo[0]; // Foreigner AgentCircuitData agentClientCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode); if (agentClientCircuit != null) { // Note that this is calling a different interface than base; this one calls with a string param! finfos = FriendsService.GetFriends(client.AgentId.ToString()); m_log.DebugFormat("[HGFRIENDS MODULE]: Fetched {0} local friends for visitor {1}", finfos.Length, client.AgentId.ToString()); } // m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting GetFriendsFromService for {0}", client.Name); return finfos; } protected override bool StoreRights(UUID agentID, UUID friendID, int rights) { Boolean agentIsLocal = true; Boolean friendIsLocal = true; if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); friendIsLocal = UserManagementModule.IsLocalGridUser(friendID); } // Are they both local users? if (agentIsLocal && friendIsLocal) { // local grid users return base.StoreRights(agentID, friendID, rights); } if (agentIsLocal) // agent is local, friend is foreigner { FriendInfo[] finfos = GetFriendsFromCache(agentID); FriendInfo finfo = GetFriend(finfos, friendID); if (finfo != null) { FriendsService.StoreFriend(agentID.ToString(), finfo.Friend, rights); return true; } } if (friendIsLocal) // agent is foreigner, friend is local { string agentUUI = GetUUI(friendID, agentID); if (agentUUI != string.Empty) { FriendsService.StoreFriend(agentUUI, friendID.ToString(), rights); return true; } } return false; } protected override void StoreBackwards(UUID friendID, UUID agentID) { bool agentIsLocal = true; // bool friendIsLocal = true; if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); // friendIsLocal = UserManagementModule.IsLocalGridUser(friendID); } // Is the requester a local user? if (agentIsLocal) { // local grid users m_log.DebugFormat("[HGFRIENDS MODULE]: Friendship requester is local. Storing backwards."); base.StoreBackwards(friendID, agentID); return; } // no provision for this temporary friendship state when user is not local //FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0); } protected override void StoreFriendships(UUID agentID, UUID friendID) { Boolean agentIsLocal = true; Boolean friendIsLocal = true; if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); friendIsLocal = UserManagementModule.IsLocalGridUser(friendID); } // Are they both local users? if (agentIsLocal && friendIsLocal) { // local grid users m_log.DebugFormat("[HGFRIENDS MODULE]: Users are both local"); DeletePreviousHGRelations(agentID, friendID); base.StoreFriendships(agentID, friendID); return; } // ok, at least one of them is foreigner, let's get their data IClientAPI agentClient = LocateClientObject(agentID); IClientAPI friendClient = LocateClientObject(friendID); AgentCircuitData agentClientCircuit = null; AgentCircuitData friendClientCircuit = null; string agentUUI = string.Empty; string friendUUI = string.Empty; string agentFriendService = string.Empty; string friendFriendService = string.Empty; if (agentClient != null) { agentClientCircuit = ((Scene)(agentClient.Scene)).AuthenticateHandler.GetAgentCircuitData(agentClient.CircuitCode); agentUUI = Util.ProduceUserUniversalIdentifier(agentClientCircuit); agentFriendService = agentClientCircuit.ServiceURLs["FriendsServerURI"].ToString(); RecacheFriends(agentClient); } if (friendClient != null) { friendClientCircuit = ((Scene)(friendClient.Scene)).AuthenticateHandler.GetAgentCircuitData(friendClient.CircuitCode); friendUUI = Util.ProduceUserUniversalIdentifier(friendClientCircuit); friendFriendService = friendClientCircuit.ServiceURLs["FriendsServerURI"].ToString(); RecacheFriends(friendClient); } m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}", agentUUI, friendUUI, agentFriendService, friendFriendService); // Generate a random 8-character hex number that will sign this friendship string secret = UUID.Random().ToString().Substring(0, 8); string theFriendUUID = friendUUI + ";" + secret; string agentUUID = agentUUI + ";" + secret; if (agentIsLocal) // agent is local, 'friend' is foreigner { // This may happen when the agent returned home, in which case the friend is not there // We need to look for its information in the friends list itself FriendInfo[] finfos = null; bool confirming = false; if (friendUUI == string.Empty) { finfos = GetFriendsFromCache(agentID); foreach (FriendInfo finfo in finfos) { if (finfo.TheirFlags == -1) { if (finfo.Friend.StartsWith(friendID.ToString())) { friendUUI = finfo.Friend; theFriendUUID = friendUUI; UUID utmp = UUID.Zero; string url = String.Empty; string first = String.Empty; string last = String.Empty; // If it's confirming the friendship, we already have the full UUI with the secret if (Util.ParseUniversalUserIdentifier(theFriendUUID, out utmp, out url, out first, out last, out secret)) { agentUUID = agentUUI + ";" + secret; m_uMan.AddUser(utmp, first, last, url); } confirming = true; break; } } } if (!confirming) { friendUUI = m_uMan.GetUserUUI(friendID); theFriendUUID = friendUUI + ";" + secret; } friendFriendService = m_uMan.GetUserServerURL(friendID, "FriendsServerURI"); // m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}", // agentUUI, friendUUI, agentFriendService, friendFriendService); } // Delete any previous friendship relations DeletePreviousRelations(agentID, friendID); // store in the local friends service a reference to the foreign friend FriendsService.StoreFriend(agentID.ToString(), theFriendUUID, 1); // and also the converse FriendsService.StoreFriend(theFriendUUID, agentID.ToString(), 1); //if (!confirming) //{ // store in the foreign friends service a reference to the local agent HGFriendsServicesConnector friendsConn = null; if (friendClientCircuit != null) // the friend is here, validate session friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID); else // the friend is not here, he initiated the request in his home world friendsConn = new HGFriendsServicesConnector(friendFriendService); friendsConn.NewFriendship(friendID, agentUUID); //} } else if (friendIsLocal) // 'friend' is local, agent is foreigner { // Delete any previous friendship relations DeletePreviousRelations(agentID, friendID); // store in the local friends service a reference to the foreign agent FriendsService.StoreFriend(friendID.ToString(), agentUUI + ";" + secret, 1); // and also the converse FriendsService.StoreFriend(agentUUI + ";" + secret, friendID.ToString(), 1); if (agentClientCircuit != null) { // store in the foreign friends service a reference to the local agent HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID); friendsConn.NewFriendship(agentID, friendUUI + ";" + secret); } } else // They're both foreigners! { HGFriendsServicesConnector friendsConn; if (agentClientCircuit != null) { friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID); friendsConn.NewFriendship(agentID, friendUUI + ";" + secret); } if (friendClientCircuit != null) { friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID); friendsConn.NewFriendship(friendID, agentUUI + ";" + secret); } } // my brain hurts now } private void DeletePreviousRelations(UUID a1, UUID a2) { // Delete any previous friendship relations FriendInfo[] finfos = null; FriendInfo f = null; finfos = GetFriendsFromCache(a1); if (finfos != null) { f = GetFriend(finfos, a2); if (f != null) { FriendsService.Delete(a1, f.Friend); // and also the converse FriendsService.Delete(f.Friend, a1.ToString()); } } finfos = GetFriendsFromCache(a2); if (finfos != null) { f = GetFriend(finfos, a1); if (f != null) { FriendsService.Delete(a2, f.Friend); // and also the converse FriendsService.Delete(f.Friend, a2.ToString()); } } } private void DeletePreviousHGRelations(UUID a1, UUID a2) { // Delete any previous friendship relations FriendInfo[] finfos = null; finfos = GetFriendsFromCache(a1); if (finfos != null) { foreach (FriendInfo f in finfos) { if (f.TheirFlags == -1) { if (f.Friend.StartsWith(a2.ToString())) { FriendsService.Delete(a1, f.Friend); // and also the converse FriendsService.Delete(f.Friend, a1.ToString()); } } } } finfos = GetFriendsFromCache(a1); if (finfos != null) { foreach (FriendInfo f in finfos) { if (f.TheirFlags == -1) { if (f.Friend.StartsWith(a1.ToString())) { FriendsService.Delete(a2, f.Friend); // and also the converse FriendsService.Delete(f.Friend, a2.ToString()); } } } } } protected override bool DeleteFriendship(UUID agentID, UUID exfriendID) { Boolean agentIsLocal = true; Boolean friendIsLocal = true; if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); friendIsLocal = UserManagementModule.IsLocalGridUser(exfriendID); } // Are they both local users? if (agentIsLocal && friendIsLocal) { // local grid users return base.DeleteFriendship(agentID, exfriendID); } // ok, at least one of them is foreigner, let's get their data string agentUUI = string.Empty; string friendUUI = string.Empty; if (agentIsLocal) // agent is local, 'friend' is foreigner { // We need to look for its information in the friends list itself FriendInfo[] finfos = GetFriendsFromCache(agentID); FriendInfo finfo = GetFriend(finfos, exfriendID); if (finfo != null) { friendUUI = finfo.Friend; // delete in the local friends service the reference to the foreign friend FriendsService.Delete(agentID, friendUUI); // and also the converse FriendsService.Delete(friendUUI, agentID.ToString()); // notify the exfriend's service Util.FireAndForget( delegate { Delete(exfriendID, agentID, friendUUI); }, null, "HGFriendsModule.DeleteFriendshipForeignFriend"); m_log.DebugFormat("[HGFRIENDS MODULE]: {0} terminated {1}", agentID, friendUUI); return true; } } else if (friendIsLocal) // agent is foreigner, 'friend' is local { agentUUI = GetUUI(exfriendID, agentID); if (agentUUI != string.Empty) { // delete in the local friends service the reference to the foreign agent FriendsService.Delete(exfriendID, agentUUI); // and also the converse FriendsService.Delete(agentUUI, exfriendID.ToString()); // notify the agent's service? Util.FireAndForget( delegate { Delete(agentID, exfriendID, agentUUI); }, null, "HGFriendsModule.DeleteFriendshipLocalFriend"); m_log.DebugFormat("[HGFRIENDS MODULE]: {0} terminated {1}", agentUUI, exfriendID); return true; } } //else They're both foreigners! Can't handle this return false; } private string GetUUI(UUID localUser, UUID foreignUser) { // Let's see if the user is here by any chance FriendInfo[] finfos = GetFriendsFromCache(localUser); if (finfos != EMPTY_FRIENDS) // friend is here, cool { FriendInfo finfo = GetFriend(finfos, foreignUser); if (finfo != null) { return finfo.Friend; } } else // user is not currently on this sim, need to get from the service { finfos = FriendsService.GetFriends(localUser); foreach (FriendInfo finfo in finfos) { if (finfo.Friend.StartsWith(foreignUser.ToString())) // found it! { return finfo.Friend; } } } return string.Empty; } private void Delete(UUID foreignUser, UUID localUser, string uui) { UUID id; string url = string.Empty, secret = string.Empty, tmp = string.Empty; if (Util.ParseUniversalUserIdentifier(uui, out id, out url, out tmp, out tmp, out secret)) { m_log.DebugFormat("[HGFRIENDS MODULE]: Deleting friendship from {0}", url); HGFriendsServicesConnector friendConn = new HGFriendsServicesConnector(url); friendConn.DeleteFriendship(foreignUser, localUser, secret); } } protected override bool ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im) { if (base.ForwardFriendshipOffer(agentID, friendID, im)) return true; // OK, that didn't work, so let's try to find this user somewhere if (!m_uMan.IsLocalGridUser(friendID)) { string friendsURL = m_uMan.GetUserServerURL(friendID, "FriendsServerURI"); if (friendsURL != string.Empty) { m_log.DebugFormat("[HGFRIENDS MODULE]: Forwading friendship from {0} to {1} @ {2}", agentID, friendID, friendsURL); GridRegion region = new GridRegion(); region.ServerURI = friendsURL; string name = im.fromAgentName; if (m_uMan.IsLocalGridUser(agentID)) { IClientAPI agentClient = LocateClientObject(agentID); AgentCircuitData agentClientCircuit = ((Scene)(agentClient.Scene)).AuthenticateHandler.GetAgentCircuitData(agentClient.CircuitCode); string agentHomeService = string.Empty; try { agentHomeService = agentClientCircuit.ServiceURLs["HomeURI"].ToString(); string lastname = "@" + new Uri(agentHomeService).Authority; string firstname = im.fromAgentName.Replace(" ", "."); name = firstname + lastname; } catch (KeyNotFoundException) { m_log.DebugFormat("[HGFRIENDS MODULE]: Key HomeURI not found for user {0}", agentID); return false; } catch (NullReferenceException) { m_log.DebugFormat("[HGFRIENDS MODULE]: Null HomeUri for local user {0}", agentID); return false; } catch (UriFormatException) { m_log.DebugFormat("[HGFRIENDS MODULE]: Malformed HomeUri {0} for local user {1}", agentHomeService, agentID); return false; } } m_HGFriendsConnector.FriendshipOffered(region, agentID, friendID, im.message, name); return true; } } return false; } public override bool LocalFriendshipOffered(UUID toID, GridInstantMessage im) { if (base.LocalFriendshipOffered(toID, im)) { if (im.fromAgentName.Contains("@")) { string[] parts = im.fromAgentName.Split(new char[] { '@' }); if (parts.Length == 2) { string[] fl = parts[0].Trim().Split(new char[] { '.' }); if (fl.Length == 2) m_uMan.AddUser(new UUID(im.fromAgentID), fl[0], fl[1], "http://" + parts[1]); else m_uMan.AddUser(new UUID(im.fromAgentID), fl[0], "", "http://" + parts[1]); } } return true; } return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Lucene.Net.Search; using Analyzer = Lucene.Net.Analysis.Analyzer; using BooleanClause = Lucene.Net.Search.BooleanClause; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using MultiPhraseQuery = Lucene.Net.Search.MultiPhraseQuery; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using Query = Lucene.Net.Search.Query; using Version = Lucene.Net.Util.Version; namespace Lucene.Net.QueryParsers { /// <summary> A QueryParser which constructs queries to search multiple fields. /// /// </summary> /// <version> $Revision: 829231 $ /// </version> public class MultiFieldQueryParser : QueryParser { protected internal string[] fields; protected internal IDictionary<string, float> boosts; /// <summary> Creates a MultiFieldQueryParser. Allows passing of a map with term to /// Boost, and the boost to apply to each term. /// /// <p/> /// It will, when parse(String query) is called, construct a query like this /// (assuming the query consists of two terms and you specify the two fields /// <c>title</c> and <c>body</c>): /// <p/> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p/> /// When setDefaultOperator(AND_OPERATOR) is set, the result will be: /// <p/> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p/> /// When you pass a boost (title=>5 body=>10) you can get /// <p/> /// /// <code> /// +(title:term1^5.0 body:term1^10.0) +(title:term2^5.0 body:term2^10.0) /// </code> /// /// <p/> /// In other words, all the query's terms must appear, but it doesn't matter /// in what fields they appear. /// <p/> /// </summary> public MultiFieldQueryParser(Version matchVersion, string[] fields, Analyzer analyzer, IDictionary<string, float> boosts) : this(matchVersion, fields, analyzer) { this.boosts = boosts; } /// <summary> Creates a MultiFieldQueryParser. /// /// <p/> /// It will, when parse(String query) is called, construct a query like this /// (assuming the query consists of two terms and you specify the two fields /// <c>title</c> and <c>body</c>): /// <p/> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p/> /// When setDefaultOperator(AND_OPERATOR) is set, the result will be: /// <p/> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p/> /// In other words, all the query's terms must appear, but it doesn't matter /// in what fields they appear. /// <p/> /// </summary> public MultiFieldQueryParser(Version matchVersion, System.String[] fields, Analyzer analyzer) : base(matchVersion, null, analyzer) { this.fields = fields; } protected internal override Query GetFieldQuery(string field, string queryText, int slop) { if (field == null) { IList<BooleanClause> clauses = new List<BooleanClause>(); for (int i = 0; i < fields.Length; i++) { Query q = base.GetFieldQuery(fields[i], queryText); if (q != null) { //If the user passes a map of boosts if (boosts != null) { //Get the boost and apply them if exists Single boost; if (boosts.TryGetValue(fields[i], out boost)) q.Boost = boost; } ApplySlop(q, slop); clauses.Add(new BooleanClause(q, Occur.SHOULD)); } } if (clauses.Count == 0) // happens for stopwords return null; return GetBooleanQuery(clauses, true); } Query q2 = base.GetFieldQuery(field, queryText); ApplySlop(q2, slop); return q2; } private void ApplySlop(Query q, int slop) { if (q is PhraseQuery) { ((PhraseQuery)q).Slop = slop; } else if (q is MultiPhraseQuery) { ((MultiPhraseQuery)q).Slop = slop; } } protected internal override Query GetFieldQuery(System.String field, System.String queryText) { return GetFieldQuery(field, queryText, 0); } protected internal override Query GetFuzzyQuery(System.String field, System.String termStr, float minSimilarity) { if (field == null) { IList<BooleanClause> clauses = new List<BooleanClause>(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetFuzzyQuery(fields[i], termStr, minSimilarity), Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetFuzzyQuery(field, termStr, minSimilarity); } protected internal override Query GetPrefixQuery(System.String field, System.String termStr) { if (field == null) { IList<BooleanClause> clauses = new List<BooleanClause>(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetPrefixQuery(fields[i], termStr), Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetPrefixQuery(field, termStr); } protected internal override Query GetWildcardQuery(System.String field, System.String termStr) { if (field == null) { IList<BooleanClause> clauses = new List<BooleanClause>(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetWildcardQuery(fields[i], termStr), Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetWildcardQuery(field, termStr); } protected internal override Query GetRangeQuery(System.String field, System.String part1, System.String part2, bool inclusive) { if (field == null) { IList<BooleanClause> clauses = new List<BooleanClause>(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetRangeQuery(fields[i], part1, part2, inclusive), Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetRangeQuery(field, part1, part2, inclusive); } /// <summary> Parses a query which searches on the fields specified. /// <p/> /// If x fields are specified, this effectively constructs: /// /// <code> /// (field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx) /// </code> /// /// </summary> /// <param name="matchVersion">Lucene version to match; this is passed through to /// QueryParser. /// </param> /// <param name="queries">Queries strings to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the queries array differs from the length of /// the fields array /// </summary> public static Query Parse(Version matchVersion, System.String[] queries, System.String[] fields, Analyzer analyzer) { if (queries.Length != fields.Length) throw new System.ArgumentException("queries.length != fields.length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer); Query q = qp.Parse(queries[i]); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery)q).GetClauses().Length > 0)) { bQuery.Add(q, Occur.SHOULD); } } return bQuery; } /// <summary> Parses a query, searching on the fields specified. Use this if you need /// to specify certain fields as required, and others as prohibited. /// <p/> /// Uasge: /// <code> /// String[] fields = {&quot;filename&quot;, &quot;contents&quot;, &quot;description&quot;}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse(&quot;query&quot;, fields, flags, analyzer); /// </code> /// <p/> /// The code above would construct a query: /// /// <code> /// (filename:query) +(contents:query) -(description:query) /// </code> /// /// </summary> /// <param name="matchVersion">Lucene version to match; this is passed through to /// QueryParser. /// </param> /// <param name="query">Query string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the fields array differs from the length of /// the flags array /// </summary> public static Query Parse(Version matchVersion, System.String query, System.String[] fields, Occur[] flags, Analyzer analyzer) { if (fields.Length != flags.Length) throw new System.ArgumentException("fields.length != flags.length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer); Query q = qp.Parse(query); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery)q).GetClauses().Length > 0)) { bQuery.Add(q, flags[i]); } } return bQuery; } /// <summary> Parses a query, searching on the fields specified. Use this if you need /// to specify certain fields as required, and others as prohibited. /// <p/> /// Usage: /// <code> /// String[] query = {&quot;query1&quot;, &quot;query2&quot;, &quot;query3&quot;}; /// String[] fields = {&quot;filename&quot;, &quot;contents&quot;, &quot;description&quot;}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse(query, fields, flags, analyzer); /// </code> /// <p/> /// The code above would construct a query: /// /// <code> /// (filename:query1) +(contents:query2) -(description:query3) /// </code> /// /// </summary> /// <param name="matchVersion">Lucene version to match; this is passed through to /// QueryParser. /// </param> /// <param name="queries">Queries string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the queries, fields, and flags array differ /// </summary> public static Query Parse(Version matchVersion, System.String[] queries, System.String[] fields, Occur[] flags, Analyzer analyzer) { if (!(queries.Length == fields.Length && queries.Length == flags.Length)) throw new System.ArgumentException("queries, fields, and flags array have have different length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer); Query q = qp.Parse(queries[i]); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery)q).GetClauses().Length > 0)) { bQuery.Add(q, flags[i]); } } return bQuery; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Client.Cache; using NUnit.Framework; using Apache.Ignite.Platform.Model; /// <summary> /// Tests checks ability to execute service method without explicit registration of parameter type. /// </summary> public class ServicesTypeAutoResolveTest { /** */ private readonly bool _useBinaryArray; /** Platform service name. */ const string PlatformSvcName = "PlatformTestService"; /** Java service name. */ private string _javaSvcName; /** */ protected internal static readonly Employee[] Emps = new[] { new Employee {Fio = "Sarah Connor", Salary = 1}, new Employee {Fio = "John Connor", Salary = 2} }; /** */ protected internal static readonly Parameter[] Param = new[] { new Parameter() {Id = 1, Values = new[] {new ParamValue() {Id = 1, Val = 42}, new ParamValue() {Id = 2, Val = 43}}}, new Parameter() {Id = 2, Values = new[] {new ParamValue() {Id = 3, Val = 44}, new ParamValue() {Id = 4, Val = 45}}} }; /** */ private IIgnite _grid1; /** */ private IIgnite _client; /** */ private IIgniteClient _thinClient; /** */ public ServicesTypeAutoResolveTest() { // No-op. } /** */ public ServicesTypeAutoResolveTest(bool useBinaryArray) { _useBinaryArray = useBinaryArray; } [TestFixtureTearDown] public void FixtureTearDown() { StopGrids(); } /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { StartGrids(); _grid1.GetServices().DeployClusterSingleton(PlatformSvcName, new PlatformTestService()); _javaSvcName = TestUtils.DeployJavaService(_grid1); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { _grid1.GetServices().Cancel(PlatformSvcName); _grid1.GetServices().Cancel(_javaSvcName); _grid1.GetServices(); TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1); } catch (Exception) { // Restart grids to cleanup StopGrids(); throw; } finally { if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes")) StopGrids(); // clean events for other tests } } /// <summary> /// Tests .Net service invocation on local node. /// </summary> [Test] public void TestPlatformServiceLocal() { DoTestService(_grid1.GetServices().GetServiceProxy<IJavaService>(PlatformSvcName), true); } /// <summary> /// Tests .Net service invocation on remote node. /// </summary> [Test] public void TestPlatformServiceRemote() { DoTestService(_client.GetServices().GetServiceProxy<IJavaService>(PlatformSvcName), true); } /// <summary> /// Tests Java service invocation with dynamic proxy. /// Types should be resolved implicitly. /// </summary> [Test] public void TestJavaServiceDynamicProxy() { DoTestService(new JavaServiceDynamicProxy(_grid1.GetServices().GetDynamicServiceProxy(_javaSvcName, true))); } /// <summary> /// Tests Java service invocation on local. /// Types should be resolved implicitly. /// </summary> [Test] public void TestJavaServiceLocal() { DoTestService(_grid1.GetServices().GetServiceProxy<IJavaService>(_javaSvcName, false)); } /// <summary> /// Tests Java service invocation on remote node.. /// Types should be resolved implicitly. /// </summary> [Test] public void TestJavaServiceRemote() { DoTestService(_client.GetServices().GetServiceProxy<IJavaService>(_javaSvcName, false)); } /// <summary> /// Tests Java service invocation. /// Types should be resolved implicitly. /// </summary> [Test] public void TestJavaServiceThinClient() { DoTestService(_thinClient.GetServices().GetServiceProxy<IJavaService>(_javaSvcName)); } /// <summary> /// Tests Platform service invocation. /// Types should be resolved implicitly. /// </summary> [Test] public void TestPlatformServiceThinClient() { DoTestService(_thinClient.GetServices().GetServiceProxy<IJavaService>(PlatformSvcName), true); } /// <summary> /// Tests service invocation. /// </summary> private void DoTestService(IJavaService svc, bool isPlatform = false) { Assert.IsNull(svc.testDepartments(null)); var arr = new[] { "HR", "IT" }.Select(x => new Department() { Name = x }).ToList(); ICollection deps = svc.testDepartments(arr); Assert.NotNull(deps); Assert.AreEqual(1, deps.Count); Assert.AreEqual("Executive", deps.OfType<Department>().Select(d => d.Name).ToArray()[0]); Assert.IsNull(svc.testAddress(null)); Address addr = svc.testAddress(new Address { Zip = "000", Addr = "Moscow" }); Assert.AreEqual("127000", addr.Zip); Assert.AreEqual("Moscow Akademika Koroleva 12", addr.Addr); if (_useBinaryArray) { Assert.AreEqual(42, svc.testOverload(2, Emps)); Assert.AreEqual(43, svc.testOverload(2, Param)); Assert.AreEqual(3, svc.testOverload(1, 2)); Assert.AreEqual(5, svc.testOverload(3, 2)); } Assert.IsNull(svc.testEmployees(null)); var emps = svc.testEmployees(Emps); if (!isPlatform || _useBinaryArray) Assert.AreEqual(typeof(Employee[]), emps.GetType()); Assert.NotNull(emps); Assert.AreEqual(1, emps.Length); Assert.AreEqual("Kyle Reese", emps[0].Fio); Assert.AreEqual(3, emps[0].Salary); Assert.IsNull(svc.testMap(null)); var map = new Dictionary<Key, Value>(); map.Add(new Key() { Id = 1 }, new Value() { Val = "value1" }); map.Add(new Key() { Id = 2 }, new Value() { Val = "value2" }); var res = svc.testMap(map); Assert.NotNull(res); Assert.AreEqual(1, res.Count); Assert.AreEqual("value3", ((Value)res[new Key() { Id = 3 }]).Val); var accs = svc.testAccounts(); if (!isPlatform || _useBinaryArray) Assert.AreEqual(typeof(Account[]), accs.GetType()); Assert.NotNull(accs); Assert.AreEqual(2, accs.Length); Assert.AreEqual("123", accs[0].Id); Assert.AreEqual("321", accs[1].Id); Assert.AreEqual(42, accs[0].Amount); Assert.AreEqual(0, accs[1].Amount); var users = svc.testUsers(); if (!isPlatform || _useBinaryArray) Assert.AreEqual(typeof(User[]), users.GetType()); Assert.NotNull(users); Assert.AreEqual(2, users.Length); Assert.AreEqual(1, users[0].Id); Assert.AreEqual(ACL.ALLOW, users[0].Acl); Assert.AreEqual("admin", users[0].Role.Name); Assert.AreEqual(AccessLevel.SUPER, users[0].Role.AccessLevel); Assert.AreEqual(2, users[1].Id); Assert.AreEqual(ACL.DENY, users[1].Acl); Assert.AreEqual("user", users[1].Role.Name); Assert.AreEqual(AccessLevel.USER, users[1].Role.AccessLevel); var users2 = svc.testRoundtrip(users); Assert.NotNull(users2); if (_useBinaryArray) Assert.AreEqual(typeof(User[]), users2.GetType()); } /// <summary> /// Starts the grids. /// </summary> private void StartGrids() { if (_grid1 != null) return; var path = Path.Combine("Config", "Compute", "compute-grid"); var cfg = GetConfiguration(path + "1.xml"); _grid1 = Ignition.Start(cfg); cfg.ClientMode = true; cfg.IgniteInstanceName = "client"; cfg.WorkDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "client_work"); _client = Ignition.Start(cfg); _thinClient = Ignition.StartClient(GetClientConfiguration()); } /// <summary> /// Stops the grids. /// </summary> private void StopGrids() { _grid1 = null; Ignition.StopAll(true); } /// <summary> /// Gets the Ignite configuration. /// </summary> private IgniteConfiguration GetConfiguration(string springConfigUrl) { springConfigUrl = Compute.ComputeApiTestFullFooter.ReplaceFooterSetting(springConfigUrl); return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = springConfigUrl, BinaryConfiguration = BinaryConfiguration(), LifecycleHandlers = _useBinaryArray ? new[] { new SetUseBinaryArray() } : null }; } /// <summary> /// Gets the client configuration. /// </summary> private IgniteClientConfiguration GetClientConfiguration() { var port = IgniteClientConfiguration.DefaultPort; return new IgniteClientConfiguration { Endpoints = new List<string> {IPAddress.Loopback + ":" + port}, SocketTimeout = TimeSpan.FromSeconds(15), Logger = new ListLogger(new ConsoleLogger {MinLevel = LogLevel.Trace}), BinaryConfiguration = BinaryConfiguration() }; } /** */ private BinaryConfiguration BinaryConfiguration() { return new BinaryConfiguration { NameMapper = new BinaryBasicNameMapper { NamespacePrefix = "org.", NamespaceToLower = true } }; } } /// <summary> /// Tests checks ability to execute service method without explicit registration of parameter type. /// </summary> public class ServicesTypeAutoResolveTestBinaryArrays : ServicesTypeAutoResolveTest { /** */ public ServicesTypeAutoResolveTestBinaryArrays() : base(true) { // No-op. } } }
//--------------------------------------------------------------------- // This file is part of the CLR Managed Debugger (mdbg) Sample. // // Copyright (C) Microsoft Corporation. All rights reserved. // // Part of managed wrappers for native debugging APIs. // NativeImports.cs: raw definitions of native methods and structures // for native debugging API. // Also includes some useful utility methods. //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Runtime.Serialization; using Microsoft.Samples.Debugging.Native; using Microsoft.Samples.Debugging.Native.Private; using Microsoft.Win32.SafeHandles; using System.Security.Permissions; using System.IO; namespace Microsoft.Samples.Debugging.Native.Private { // Passed to CreateProcess [StructLayout(LayoutKind.Sequential)] public class STARTUPINFO { public STARTUPINFO() { // Initialize size field. this.cb = Marshal.SizeOf(this); // initialize safe handles this.hStdInput = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(0), false); this.hStdOutput = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(0), false); this.hStdError = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(0), false); } public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public Microsoft.Win32.SafeHandles.SafeFileHandle hStdInput; public Microsoft.Win32.SafeHandles.SafeFileHandle hStdOutput; public Microsoft.Win32.SafeHandles.SafeFileHandle hStdError; } // Passed to CreateProces [StructLayout(LayoutKind.Sequential)] public class PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } } namespace Microsoft.Samples.Debugging.Native { #region Interfaces /// <summary> /// Thrown when failing to read memory from a target. /// </summary> [Serializable()] public class ReadMemoryFailureException : InvalidOperationException { /// <summary> /// Initialize a new exception /// </summary> /// <param name="address">address where read failed</param> /// <param name="countBytes">size of read attempted</param> public ReadMemoryFailureException(IntPtr address, int countBytes) : base(MessageHelper(address, countBytes)) { } public ReadMemoryFailureException(IntPtr address, int countBytes, Exception innerException) : base(MessageHelper(address, countBytes), innerException) { } // Internal helper to get the message string for the ctor. static string MessageHelper(IntPtr address, int countBytes) { return String.Format("Failed to read memory at 0x" + address.ToString("x") + " of " + countBytes + " bytes."); } #region Standard Ctors /// <summary> /// Initializes a new instance of the ReadMemoryFailureException. /// </summary> public ReadMemoryFailureException() { } /// <summary> /// Initializes a new instance of the ReadMemoryFailureException with the specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public ReadMemoryFailureException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the ReadMemoryFailureException with the specified error message and inner Exception. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public ReadMemoryFailureException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the ReadMemoryFailureException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> protected ReadMemoryFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion } /// <summary> /// Interface to provide access to target /// </summary> public interface IMemoryReader { /// <summary> /// Read memory from the target process. Either reads all memory or throws. /// </summary> /// <param name="address">target address to read memory from</param> /// <param name="buffer">buffer to fill with memory</param> /// <exception cref="ReadMemoryFailureException">Throws if can't read all the memory</exception> void ReadMemory(IntPtr address, byte[] buffer); } #endregion #region Native Structures /// <summary> /// Platform agnostic flags used to extract platform-specific context flag values /// </summary> [Flags] public enum AgnosticContextFlags : int { //using a seperate bit for each flag will allow logical operations of flags // i.e ContextControl | ContextInteger | ContextSegments, etc ContextControl = 0x1, ContextInteger = 0x2, ContextFloatingPoint = 0x4, ContextDebugRegisters = 0x10, //on IA64, this will be equivalent to ContextDebug ContextAll = 0x3F, None = 0x0 } [Flags] public enum ContextFlags { None = 0, X86Context = 0x10000, X86ContextControl = X86Context | 0x1, X86ContextInteger = X86Context | 0x2, X86ContextSegments = X86Context | 0x4, X86ContextFloatingPoint = X86Context | 0x8, X86ContextDebugRegisters = X86Context | 0x10, X86ContextExtendedRegisters = X86Context | 0x20, X86ContextFull = X86Context | X86ContextControl | X86ContextInteger | X86ContextSegments, X86ContextAll = X86Context | X86ContextControl | X86ContextInteger | X86ContextSegments | X86ContextFloatingPoint | X86ContextDebugRegisters | X86ContextExtendedRegisters, AMD64Context = 0x100000, AMD64ContextControl = AMD64Context | 0x1, AMD64ContextInteger = AMD64Context | 0x2, AMD64ContextSegments = AMD64Context | 0x4, AMD64ContextFloatingPoint = AMD64Context | 0x8, AMD64ContextDebugRegisters = AMD64Context | 0x10, AMD64ContextFull = AMD64Context | AMD64ContextControl | AMD64ContextInteger | AMD64ContextFloatingPoint, AMD64ContextAll = AMD64Context | AMD64ContextControl | AMD64ContextInteger | AMD64ContextSegments | AMD64ContextFloatingPoint | AMD64ContextDebugRegisters, IA64Context = 0x80000, IA64ContextControl = IA64Context | 0x1, IA64ContextLowerFloatingPoint = IA64Context | 0x2, IA64ContextHigherFloatingPoint = IA64Context | 0x4, IA64ContextInteger = IA64Context | 0x8, IA64ContextDebug = IA64Context | 0x10, IA64ContextIA32Control = IA64Context | 0x20, IA64ContextFloatingPoint = IA64Context | IA64ContextLowerFloatingPoint | IA64ContextHigherFloatingPoint, IA64ContextFull = IA64Context | IA64ContextControl | IA64ContextFloatingPoint | IA64ContextInteger | IA64ContextIA32Control, IA64ContextAll = IA64Context | IA64ContextControl | IA64ContextFloatingPoint | IA64ContextInteger | IA64ContextDebug | IA64ContextIA32Control, } public enum ContextSize : int { None = 0, X86 = 716, AMD64 = 1232, IA64 = 2672, } [Flags] public enum X86Offsets : int { ContextFlags = 0x0, // This section is specified/returned if CONTEXT_DEBUG_REGISTERS is // set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT // included in CONTEXT_FULL. Dr0 = 0x4, Dr1 = 0x8, Dr2 = 0xC, Dr3 = 0x10, Dr6 = 0x14, Dr7 = 0x18, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_FLOATING_POINT. FloatSave = 0x1C, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_SEGMENTS. SegGs = 0x8C, SegFs = 0x90, SegEs = 0x94, SegDs = 0x98, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_INTEGER. Edi = 0x9C, Esi = 0xA0, Ebx = 0xA4, Edx = 0xA8, Ecx = 0xAC, Eax = 0xB0, // This section is specified/returned if the // ContextFlags word contians the flag CONTEXT_CONTROL. Ebp = 0xB4, Eip = 0xB8, SegCs = 0xBC, EFlags = 0xC0, Esp = 0xC4, SegSs = 0xC8, // This section is specified/returned if the ContextFlags word // contains the flag CONTEXT_EXTENDED_REGISTERS. // The format and contexts are processor specific ExtendedRegisters = 0xCB, //512 } [Flags] public enum X86Flags : int { SINGLE_STEP_FLAG = 0x100, } [Flags] public enum AMD64Offsets : int { // Register Parameter Home Addresses P1Home = 0x000, P2Home = 0x008, P3Home = 0x010, P4Home = 0x018, P5Home = 0x020, P6Home = 0x028, // Control Flags ContextFlags = 0x030, MxCsr = 0x034, // Segment Registers and Processor Flags SegCs = 0x038, SegDs = 0x03a, SegEs = 0x03c, SegFs = 0x03e, SegGs = 0x040, SegSs = 0x042, EFlags = 0x044, // Debug Registers Dr0 = 0x048, Dr1 = 0x050, Dr2 = 0x058, Dr3 = 0x060, Dr6 = 0x068, Dr7 = 0x070, // Integer Registers Rax = 0x078, Rcx = 0x080, Rdx = 0x088, Rbx = 0x090, Rsp = 0x098, Rbp = 0x0a0, Rsi = 0x0a8, Rdi = 0x0b0, R8 = 0x0b8, R9 = 0x0c0, R10 = 0x0c8, R11 = 0x0d0, R12 = 0x0d8, R13 = 0x0e0, R14 = 0x0e8, R15 = 0x0f0, // Program Counter Rip = 0x0f8, // Floating Point State FltSave = 0x100, Legacy = 0x120, Xmm0 = 0x1a0, Xmm1 = 0x1b0, Xmm2 = 0x1c0, Xmm3 = 0x1d0, Xmm4 = 0x1e0, Xmm5 = 0x1f0, Xmm6 = 0x200, Xmm7 = 0x210, Xmm8 = 0x220, Xmm9 = 0x230, Xmm10 = 0x240, Xmm11 = 0x250, Xmm12 = 0x260, Xmm13 = 0x270, Xmm14 = 0x280, Xmm15 = 0x290, // Vector Registers VectorRegister = 0x300, VectorControl = 0x4a0, // Special Debug Control Registers DebugControl = 0x4a8, LastBranchToRip = 0x4b0, LastBranchFromRip = 0x4b8, LastExceptionToRip = 0x4c0, LastExceptionFromRip = 0x4c8, } [Flags] public enum AMD64Flags : int { SINGLE_STEP_FLAG = 0x100, } [Flags] public enum IA64Offsets : int { ContextFlags = 0x0, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_DEBUG. DbI0 = 0x010, DbI1 = 0x018, DbI2 = 0x020, DbI3 = 0x028, DbI4 = 0x030, DbI5 = 0x038, DbI6 = 0x040, DbI7 = 0x048, DbD0 = 0x050, DbD1 = 0x058, DbD2 = 0x060, DbD3 = 0x068, DbD4 = 0x070, DbD5 = 0x078, DbD6 = 0x080, DbD7 = 0x088, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_LOWER_FLOATING_POINT. FltS0 = 0x090, FltS1 = 0x0a0, FltS2 = 0x0b0, FltS3 = 0x0c0, FltT0 = 0x0d0, FltT1 = 0x0e0, FltT2 = 0x0f0, FltT3 = 0x100, FltT4 = 0x110, FltT5 = 0x120, FltT6 = 0x130, FltT7 = 0x140, FltT8 = 0x150, FltT9 = 0x160, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_HIGHER_FLOATING_POINT. FltS4 = 0x170, FltS5 = 0x180, FltS6 = 0x190, FltS7 = 0x1a0, FltS8 = 0x1b0, FltS9 = 0x1c0, FltS10 = 0x1d0, FltS11 = 0x1e0, FltS12 = 0x1f0, FltS13 = 0x200, FltS14 = 0x210, FltS15 = 0x220, FltS16 = 0x230, FltS17 = 0x240, FltS18 = 0x250, FltS19 = 0x260, FltF32 = 0x270, FltF33 = 0x280, FltF34 = 0x290, FltF35 = 0x2a0, FltF36 = 0x2b0, FltF37 = 0x2c0, FltF38 = 0x2d0, FltF39 = 0x2e0, FltF40 = 0x2f0, FltF41 = 0x300, FltF42 = 0x310, FltF43 = 0x320, FltF44 = 0x330, FltF45 = 0x340, FltF46 = 0x350, FltF47 = 0x360, FltF48 = 0x370, FltF49 = 0x380, FltF50 = 0x390, FltF51 = 0x3a0, FltF52 = 0x3b0, FltF53 = 0x3c0, FltF54 = 0x3d0, FltF55 = 0x3e0, FltF56 = 0x3f0, FltF57 = 0x400, FltF58 = 0x410, FltF59 = 0x420, FltF60 = 0x430, FltF61 = 0x440, FltF62 = 0x450, FltF63 = 0x460, FltF64 = 0x470, FltF65 = 0x480, FltF66 = 0x490, FltF67 = 0x4a0, FltF68 = 0x4b0, FltF69 = 0x4c0, FltF70 = 0x4d0, FltF71 = 0x4e0, FltF72 = 0x4f0, FltF73 = 0x500, FltF74 = 0x510, FltF75 = 0x520, FltF76 = 0x530, FltF77 = 0x540, FltF78 = 0x550, FltF79 = 0x560, FltF80 = 0x570, FltF81 = 0x580, FltF82 = 0x590, FltF83 = 0x5a0, FltF84 = 0x5b0, FltF85 = 0x5c0, FltF86 = 0x5d0, FltF87 = 0x5e0, FltF88 = 0x5f0, FltF89 = 0x600, FltF90 = 0x610, FltF91 = 0x620, FltF92 = 0x630, FltF93 = 0x640, FltF94 = 0x650, FltF95 = 0x660, FltF96 = 0x670, FltF97 = 0x680, FltF98 = 0x690, FltF99 = 0x6a0, FltF100 = 0x6b0, FltF101 = 0x6c0, FltF102 = 0x6d0, FltF103 = 0x6e0, FltF104 = 0x6f0, FltF105 = 0x700, FltF106 = 0x710, FltF107 = 0x720, FltF108 = 0x730, FltF109 = 0x740, FltF110 = 0x750, FltF111 = 0x760, FltF112 = 0x770, FltF113 = 0x780, FltF114 = 0x790, FltF115 = 0x7a0, FltF116 = 0x7b0, FltF117 = 0x7c0, FltF118 = 0x7d0, FltF119 = 0x7e0, FltF120 = 0x7f0, FltF121 = 0x800, FltF122 = 0x810, FltF123 = 0x820, FltF124 = 0x830, FltF125 = 0x840, FltF126 = 0x850, FltF127 = 0x860, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_LOWER_FLOATING_POINT | CONTEXT_HIGHER_FLOATING_POINT | CONTEXT_CONTROL. StFPSR = 0x870, // FP status // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_INTEGER. IntGp = 0x878, // r1 = 0x, volatile IntT0 = 0x880, // r2-r3 = 0x, volatile IntT1 = 0x888, // IntS0 = 0x890, // r4-r7 = 0x, preserved IntS1 = 0x898, IntS2 = 0x8a0, IntS3 = 0x8a8, IntV0 = 0x8b0, // r8 = 0x, volatile IntT2 = 0x8b8, // r9-r11 = 0x, volatile IntT3 = 0x8c0, IntT4 = 0x8c8, IntSp = 0x8d0, // stack pointer (r12) = 0x, special IntTeb = 0x8d8, // teb (r13) = 0x, special IntT5 = 0x8e0, // r14-r31 = 0x, volatile IntT6 = 0x8e8, IntT7 = 0x8f0, IntT8 = 0x8f8, IntT9 = 0x900, IntT10 = 0x908, IntT11 = 0x910, IntT12 = 0x918, IntT13 = 0x920, IntT14 = 0x928, IntT15 = 0x930, IntT16 = 0x938, IntT17 = 0x940, IntT18 = 0x948, IntT19 = 0x950, IntT20 = 0x958, IntT21 = 0x960, IntT22 = 0x968, IntNats = 0x970, // Nat bits for r1-r31 // r1-r31 in bits 1 thru 31. Preds = 0x978, // predicates = 0x, preserved BrRp = 0x980, // return pointer = 0x, b0 = 0x, preserved BrS0 = 0x988, // b1-b5 = 0x, preserved BrS1 = 0x990, BrS2 = 0x998, BrS3 = 0x9a0, BrS4 = 0x9a8, BrT0 = 0x9b0, // b6-b7 = 0x, volatile BrT1 = 0x9b8, // This section is specified/returned if the ContextFlags word contains // the flag CONTEXT_CONTROL. // Other application registers ApUNAT = 0x9c0, // User Nat collection register = 0x, preserved ApLC = 0x9c8, // Loop counter register = 0x, preserved ApEC = 0x9d0, // Epilog counter register = 0x, preserved ApCCV = 0x9d8, // CMPXCHG value register = 0x, volatile ApDCR = 0x9e0, // Default control register (TBD) // Register stack info RsPFS = 0x9e8, // Previous function state = 0x, preserved RsBSP = 0x9f0, // Backing store pointer = 0x, preserved RsBSPSTORE = 0x9f8, RsRSC = 0xa00, // RSE configuration = 0x, volatile RsRNAT = 0xa08, // RSE Nat collection register = 0x, preserved // Trap Status Information StIPSR = 0xa10, // Interruption Processor Status StIIP = 0xa18, // Interruption IP StIFS = 0xa20, // Interruption Function State // iA32 related control registers StFCR = 0xa28, // copy of Ar21 Eflag = 0xa30, // Eflag copy of Ar24 SegCSD = 0xa38, // iA32 CSDescriptor (Ar25) SegSSD = 0xa40, // iA32 SSDescriptor (Ar26) Cflag = 0xa48, // Cr0+Cr4 copy of Ar27 StFSR = 0xa50, // x86 FP status (copy of AR28) StFIR = 0xa58, // x86 FP status (copy of AR29) StFDR = 0xa60, // x86 FP status (copy of AR30) UNUSEDPACK = 0xa68, // alignment padding } [Flags] public enum IA64Flags : long { PSR_RI = 41, IA64_BUNDLE_SIZE = 16, SINGLE_STEP_FLAG = 0x1000000000, } [Flags] public enum ImageFileMachine : int { X86 = 0x014c, AMD64 = 0x8664, IA64 = 0x0200, } public enum Platform { None = 0, X86 = 1, AMD64 = 2, IA64 = 3, } /// <summary> /// Native debug event Codes that are returned through NativeStop event /// </summary> public enum NativeDebugEventCode { None = 0, EXCEPTION_DEBUG_EVENT = 1, CREATE_THREAD_DEBUG_EVENT = 2, CREATE_PROCESS_DEBUG_EVENT = 3, EXIT_THREAD_DEBUG_EVENT = 4, EXIT_PROCESS_DEBUG_EVENT = 5, LOAD_DLL_DEBUG_EVENT = 6, UNLOAD_DLL_DEBUG_EVENT = 7, OUTPUT_DEBUG_STRING_EVENT = 8, RIP_EVENT = 9, } // Debug header for debug events. [StructLayout(LayoutKind.Sequential)] public struct DebugEventHeader { public NativeDebugEventCode dwDebugEventCode; public UInt32 dwProcessId; public UInt32 dwThreadId; }; public enum ThreadAccess : int { None = 0, THREAD_ALL_ACCESS = (0x1F03FF), THREAD_DIRECT_IMPERSONATION = (0x0200), THREAD_GET_CONTEXT = (0x0008), THREAD_IMPERSONATE = (0x0100), THREAD_QUERY_INFORMATION = (0x0040), THREAD_QUERY_LIMITED_INFORMATION = (0x0800), THREAD_SET_CONTEXT = (0x0010), THREAD_SET_INFORMATION = (0x0020), THREAD_SET_LIMITED_INFORMATION = (0x0400), THREAD_SET_THREAD_TOKEN = (0x0080), THREAD_SUSPEND_RESUME = (0x0002), THREAD_TERMINATE = (0x0001), } #region Exception events /// <summary> /// Common Exception codes /// </summary> /// <remarks>Users can define their own exception codes, so the code could be any value. /// The OS reserves bit 28 and may clear that for its own purposes</remarks> public enum ExceptionCode : uint { None = 0x0, // included for completeness sake STATUS_BREAKPOINT = 0x80000003, STATUS_SINGLESTEP = 0x80000004, EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094, /// <summary> /// Fired when debuggee gets a Control-C. /// </summary> DBG_CONTROL_C = 0x40010005, EXCEPTION_STACK_OVERFLOW = 0xC00000FD, EXCEPTION_NONCONTINUABLE_EXCEPTION = 0xC0000025, EXCEPTION_ACCESS_VIOLATION = 0xc0000005, } /// <summary> /// Flags for <see cref="EXCEPTION_RECORD"/> /// </summary> [Flags] public enum ExceptionRecordFlags : uint { /// <summary> /// No flags. /// </summary> None = 0x0, /// <summary> /// Exception can not be continued. Debugging services can still override this to continue the exception, but recommended to warn the user in this case. /// </summary> EXCEPTION_NONCONTINUABLE = 0x1, } /// <summary> /// Information about an exception /// </summary> /// <remarks>This will default to the correct caller's platform</remarks> [StructLayout(LayoutKind.Sequential)] public struct EXCEPTION_RECORD { public ExceptionCode ExceptionCode; public ExceptionRecordFlags ExceptionFlags; /// <summary> /// Based off ExceptionFlags, is the exception Non-continuable? /// </summary> public bool IsNotContinuable { get { return (ExceptionFlags & ExceptionRecordFlags.EXCEPTION_NONCONTINUABLE) != 0; } } public IntPtr ExceptionRecord; /// <summary> /// Address in the debuggee that the exception occured at. /// </summary> public IntPtr ExceptionAddress; /// <summary> /// Number of parameters used in ExceptionInformation array. /// </summary> public UInt32 NumberParameters; const int EXCEPTION_MAXIMUM_PARAMETERS = 15; // We'd like to marshal this as a ByValArray, but that's not supported yet. // We get an alignment error / TypeLoadException for DebugEventUnion //[MarshalAs(UnmanagedType.ByValArray, SizeConst = EXCEPTION_MAXIMUM_PARAMETERS)] //public IntPtr [] ExceptionInformation; // Instead, mashal manually. public IntPtr ExceptionInformation0; public IntPtr ExceptionInformation1; public IntPtr ExceptionInformation2; public IntPtr ExceptionInformation3; public IntPtr ExceptionInformation4; public IntPtr ExceptionInformation5; public IntPtr ExceptionInformation6; public IntPtr ExceptionInformation7; public IntPtr ExceptionInformation8; public IntPtr ExceptionInformation9; public IntPtr ExceptionInformation10; public IntPtr ExceptionInformation11; public IntPtr ExceptionInformation12; public IntPtr ExceptionInformation13; public IntPtr ExceptionInformation14; } // end of class EXCEPTION_RECORD /// <summary> /// Information about an exception debug event. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct EXCEPTION_DEBUG_INFO { public EXCEPTION_RECORD ExceptionRecord; public UInt32 dwFirstChance; } // end of class EXCEPTION_DEBUG_INFO #endregion // Exception events // MODULEINFO declared in psapi.h [StructLayout(LayoutKind.Sequential)] public struct ModuleInfo { public IntPtr lpBaseOfDll; public uint SizeOfImage; public IntPtr EntryPoint; } [StructLayout(LayoutKind.Sequential)] public struct CREATE_PROCESS_DEBUG_INFO { public IntPtr hFile; public IntPtr hProcess; public IntPtr hThread; public IntPtr lpBaseOfImage; public UInt32 dwDebugInfoFileOffset; public UInt32 nDebugInfoSize; public IntPtr lpThreadLocalBase; public IntPtr lpStartAddress; public IntPtr lpImageName; public UInt16 fUnicode; } // end of class CREATE_PROCESS_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct CREATE_THREAD_DEBUG_INFO { public IntPtr hThread; public IntPtr lpThreadLocalBase; public IntPtr lpStartAddress; } // end of class CREATE_THREAD_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct EXIT_THREAD_DEBUG_INFO { public UInt32 dwExitCode; } // end of class EXIT_THREAD_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct EXIT_PROCESS_DEBUG_INFO { public UInt32 dwExitCode; } // end of class EXIT_PROCESS_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct LOAD_DLL_DEBUG_INFO { public IntPtr hFile; public IntPtr lpBaseOfDll; public UInt32 dwDebugInfoFileOffset; public UInt32 nDebugInfoSize; public IntPtr lpImageName; public UInt16 fUnicode; // Helper to read an IntPtr from the target IntPtr ReadIntPtrFromTarget(IMemoryReader reader, IntPtr ptr) { // This is not cross-platform: it assumes host and target are the same size. byte[] buffer = new byte[IntPtr.Size]; reader.ReadMemory(ptr, buffer); System.UInt64 val = 0; // Note: this is dependent on endienness. for (int i = buffer.Length - 1; i >= 0; i--) { val <<= 8; val += buffer[i]; } IntPtr newptr = new IntPtr(unchecked((long)val)); return newptr; } /// <summary> /// Read the image name from the target. /// </summary> /// <param name="reader">access to target's memory</param> /// <returns>String for full path to image. Null if name not available</returns> /// <remarks>MSDN says this will never be provided for during Attach scenarios; nor for the first 1 or 2 dlls.</remarks> public string ReadImageNameFromTarget(IMemoryReader reader) { string moduleName; bool bUnicode = (fUnicode != 0); if (lpImageName == IntPtr.Zero) { return null; } else { try { IntPtr newptr = ReadIntPtrFromTarget(reader, lpImageName); if (newptr == IntPtr.Zero) { return null; } else { int charSize = (bUnicode) ? 2 : 1; byte[] buffer = new byte[charSize]; System.Text.StringBuilder sb = new System.Text.StringBuilder(); while (true) { // Read 1 character at a time. This is extremely inefficient, // but we don't know the whole length of the string and it ensures we don't // read off a page. reader.ReadMemory(newptr, buffer); int b; if (bUnicode) { b = (int)buffer[0] + ((int)buffer[1] << 8); } else { b = (int)buffer[0]; } if (b == 0) // string is null-terminated { break; } sb.Append((char)b); newptr = new IntPtr(newptr.ToInt64() + charSize); // move to next character } moduleName = sb.ToString(); } } catch (System.DataMisalignedException) { return null; } catch (InvalidOperationException) // ignore failures to read { return null; } } return moduleName; } } // end of class LOAD_DLL_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct UNLOAD_DLL_DEBUG_INFO { public IntPtr lpBaseOfDll; } // end of class UNLOAD_DLL_DEBUG_INFO [StructLayout(LayoutKind.Sequential)] public struct OUTPUT_DEBUG_STRING_INFO { public IntPtr lpDebugStringData; public UInt16 fUnicode; public UInt16 nDebugStringLength; // /// <summary> /// Read the log message from the target. /// </summary> /// <param name="reader">interface to access debuggee memory</param> /// <returns>string containing message or null if not available</returns> public string ReadMessageFromTarget(IMemoryReader reader) { try { bool isUnicode = (fUnicode != 0); int cbCharSize = (isUnicode) ? 2 : 1; byte[] buffer = new byte[nDebugStringLength * cbCharSize]; reader.ReadMemory(lpDebugStringData, buffer); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < buffer.Length; i += cbCharSize) { int val; if (isUnicode) { val = (int)buffer[i] + ((int)buffer[i + 1] << 8); } else { val = buffer[i]; } sb.Append((char)val); } return sb.ToString(); } catch (InvalidOperationException) { return null; } } } // end of class OUTPUT_DEBUG_STRING_INFO [StructLayout(LayoutKind.Explicit)] public struct DebugEventUnion { [FieldOffset(0)] public CREATE_PROCESS_DEBUG_INFO CreateProcess; [FieldOffset(0)] public EXCEPTION_DEBUG_INFO Exception; [FieldOffset(0)] public CREATE_THREAD_DEBUG_INFO CreateThread; [FieldOffset(0)] public EXIT_THREAD_DEBUG_INFO ExitThread; [FieldOffset(0)] public EXIT_PROCESS_DEBUG_INFO ExitProcess; [FieldOffset(0)] public LOAD_DLL_DEBUG_INFO LoadDll; [FieldOffset(0)] public UNLOAD_DLL_DEBUG_INFO UnloadDll; [FieldOffset(0)] public OUTPUT_DEBUG_STRING_INFO OutputDebugString; } // 32-bit and 64-bit have sufficiently different alignment that we need // two different debug event structures. /// <summary> /// Matches DEBUG_EVENT layout on 32-bit architecture /// </summary> [StructLayout(LayoutKind.Explicit)] public struct DebugEvent32 { [FieldOffset(0)] public DebugEventHeader header; [FieldOffset(12)] public DebugEventUnion union; } /// <summary> /// Matches DEBUG_EVENT layout on 64-bit architecture /// </summary> [StructLayout(LayoutKind.Explicit)] public struct DebugEvent64 { [FieldOffset(0)] public DebugEventHeader header; [FieldOffset(16)] public DebugEventUnion union; } #endregion Native Structures // SafeHandle to call CloseHandle [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public sealed class SafeWin32Handle : SafeHandleZeroOrMinusOneIsInvalid { public SafeWin32Handle() : base(true) { } public SafeWin32Handle(IntPtr handle) : base(true) { SetHandle(handle); } protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } } // These extend the Mdbg native definitions. public static class NativeMethods { private const string Kernel32LibraryName = "kernel32.dll"; private const string PsapiLibraryName = "psapi.dll"; // // These should be sharable with other pinvokes // [DllImportAttribute(Kernel32LibraryName)] internal static extern void RtlMoveMemory(IntPtr destination, IntPtr source, IntPtr numberBytes); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr handle); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] public static extern int WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext); [DllImport(Kernel32LibraryName)] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwThreadId); [DllImport(Kernel32LibraryName)] public static extern SafeWin32Handle OpenProcess(Int32 dwDesiredAccess, bool bInheritHandle, Int32 dwProcessId); [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetThreadContext(IntPtr hThread, IntPtr lpContext); // This gets the raw OS thread ID. This is not fiber aware. [DllImport(Kernel32LibraryName)] public static extern int GetCurrentThreadId(); [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWow64Process(SafeWin32Handle hProcess, ref bool isWow); [Flags] public enum PageProtection : uint { NoAccess = 0x01, Readonly = 0x02, ReadWrite = 0x04, WriteCopy = 0x08, Execute = 0x10, ExecuteRead = 0x20, ExecuteReadWrite = 0x40, ExecuteWriteCopy = 0x80, Guard = 0x100, NoCache = 0x200, WriteCombine = 0x400, } // Call CloseHandle to clean up. [DllImport(Kernel32LibraryName, SetLastError = true)] public static extern SafeWin32Handle CreateFileMapping(SafeFileHandle hFile, IntPtr lpFileMappingAttributes, PageProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName); [DllImport(Kernel32LibraryName, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFile(IntPtr baseAddress); // SafeHandle to call UnmapViewOfFile [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public sealed class SafeMapViewHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeMapViewHandle() : base(true) { } protected override bool ReleaseHandle() { return UnmapViewOfFile(handle); } // This is technically equivalent to DangerousGetHandle, but it's safer for file // mappings. In file mappings, the "handle" is actually a base address that needs // to be used in computations and RVAs. // So provide a safer accessor method. public IntPtr BaseAddress { get { return handle; } } } // Call BOOL UnmapViewOfFile(void*) to clean up. [DllImport(Kernel32LibraryName, SetLastError = true)] public static extern SafeMapViewHandle MapViewOfFile(SafeWin32Handle hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, IntPtr dwNumberOfBytesToMap); [Flags] public enum LoadLibraryFlags : uint { NoFlags = 0x00000000, DontResolveDllReferences = 0x00000001, LoadIgnoreCodeAuthzLevel = 0x00000010, LoadLibraryAsDatafile = 0x00000002, LoadLibraryAsDatafileExclusive = 0x00000040, LoadLibraryAsImageResource = 0x00000020, LoadWithAlteredSearchPath = 0x00000008 } // SafeHandle to call FreeLibrary [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public sealed class SafeLoadLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeLoadLibraryHandle() : base(true) { } public SafeLoadLibraryHandle(IntPtr handle) : base(true) { SetHandle(handle); } protected override bool ReleaseHandle() { return FreeLibrary(handle); } // This is technically equivalent to DangerousGetHandle, but it's safer for loaded // libraries where the HMODULE is also the base address the module is loaded at. public IntPtr BaseAddress { get { return handle; } } } [DllImportAttribute(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FreeLibrary(IntPtr hModule); [DllImportAttribute(Kernel32LibraryName)] internal static extern IntPtr LoadLibraryEx(String fileName, int hFile, LoadLibraryFlags dwFlags); // Filesize can be used as a approximation of module size in memory. // In memory size will be larger because of alignment issues. [DllImport(Kernel32LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFileSizeEx(IntPtr hFile, out System.Int64 lpFileSize); // Get the module's size. // This can not be called during the actual dll-load debug event. // (The debug event is sent before the information is initialized) [DllImport(PsapiLibraryName, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out ModuleInfo lpmodinfo, uint countBytes); // Read memory from live, local process. [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, UIntPtr nSize, out int lpNumberOfBytesRead); // Requires Windows XP / Win2k03 [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugSetProcessKillOnExit( [MarshalAs(UnmanagedType.Bool)] bool KillOnExit ); // Requires WinXp/Win2k03 [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugBreakProcess(IntPtr hProcess); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetEvent(SafeWin32Handle eventHandle); #region Attach / Detach APIS // constants used in CreateProcess functions public enum CreateProcessFlags { CREATE_NEW_CONSOLE = 0x00000010, // This will include child processes. DEBUG_PROCESS = 1, // This will be just the target process. DEBUG_ONLY_THIS_PROCESS = 2, } [DllImport(Kernel32LibraryName, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, STARTUPINFO lpStartupInfo,// class PROCESS_INFORMATION lpProcessInformation // class ); // Attach to a process [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugActiveProcess(uint dwProcessId); // Detach from a process // Requires WinXp/Win2k03 [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DebugActiveProcessStop(uint dwProcessId); [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode); #endregion // Attach / Detach APIS #region Stop-Go APIs // We have two separate versions of kernel32!WaitForDebugEvent to cope with different structure // layout on each platform. [DllImport(Kernel32LibraryName, EntryPoint = "WaitForDebugEvent", SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WaitForDebugEvent32(ref DebugEvent32 pDebugEvent, int dwMilliseconds); [DllImport(Kernel32LibraryName, EntryPoint = "WaitForDebugEvent", SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WaitForDebugEvent64(ref DebugEvent64 pDebugEvent, int dwMilliseconds); /// <summary> /// Values to pass to ContinueDebugEvent for ContinueStatus /// </summary> public enum ContinueStatus : uint { /// <summary> /// This is our own "empty" value /// </summary> CONTINUED = 0, /// <summary> /// Debugger consumes exceptions. Debuggee will never see the exception. Like "gh" in Windbg. /// </summary> DBG_CONTINUE = 0x00010002, /// <summary> /// Debugger does not interfere with exception processing, this passes the exception onto the debuggee. /// Like "gn" in Windbg. /// </summary> DBG_EXCEPTION_NOT_HANDLED = 0x80010001, } [DllImport(Kernel32LibraryName, SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId, ContinueStatus dwContinueStatus); #endregion // Stop-Go [DllImport("kernel32.dll")] public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] out SYSTEM_INFO lpSystemInfo); [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { // Don't marshal dwOemId since that's obsolete and lets // us avoid marshalling a union. internal ProcessorArchitecture wProcessorArchitecture; internal ushort wReserved; public uint dwPageSize; public IntPtr lpMinimumApplicationAddress; public IntPtr lpMaximumApplicationAddress; public IntPtr dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; // obsolete public uint dwAllocationGranularity; public ushort dwProcessorLevel; public ushort dwProcessorRevision; } } // NativeMethods }
/* * 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.Xml; using System.IO; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.ApplicationPlugins.Rest.Inventory { public class RestFileServices : IRest { private bool enabled = false; private string qPrefix = "files"; // A simple constructor is used to handle any once-only // initialization of working classes. public RestFileServices() { Rest.Log.InfoFormat("{0} File services initializing", MsgId); Rest.Log.InfoFormat("{0} Using REST Implementation Version {1}", MsgId, Rest.Version); // If the handler specifies a relative path for its domain // then we must add the standard absolute prefix, e.g. /admin if (!qPrefix.StartsWith(Rest.UrlPathSeparator)) { Rest.Log.InfoFormat("{0} Prefixing domain name ({1})", MsgId, qPrefix); qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix); Rest.Log.InfoFormat("{0} Fully qualified domain name is <{1}>", MsgId, qPrefix); } // Register interface using the fully-qualified prefix Rest.Plugin.AddPathHandler(DoFile, qPrefix, Allocate); // Activate if all went OK enabled = true; Rest.Log.InfoFormat("{0} File services initialization complete", MsgId); } // Post-construction, pre-enabled initialization opportunity // Not currently exploited. public void Initialize() { } // Called by the plug-in to halt REST processing. Local processing is // disabled, and control blocks until all current processing has // completed. No new processing will be started public void Close() { enabled = false; Rest.Log.InfoFormat("{0} File services ({1}) closing down", MsgId, qPrefix); } // Properties internal string MsgId { get { return Rest.MsgId; } } #region Interface private RequestData Allocate(OSHttpRequest request, OSHttpResponse response, string prefix) { return (RequestData) new FileRequestData(request, response, prefix); } // Asset Handler private void DoFile(RequestData rparm) { if (!enabled) return; FileRequestData rdata = (FileRequestData) rparm; Rest.Log.DebugFormat("{0} REST File handler ({1}) ENTRY", MsgId, qPrefix); // Now that we know this is a serious attempt to // access file data, we should find out who // is asking, and make sure they are authorized // to do so. We need to validate the caller's // identity before revealing anything about the // status quo. Authenticate throws an exception // via Fail if no identity information is present. // // With the present HTTP server we can't use the // builtin authentication mechanisms because they // would be enforced for all in-bound requests. // Instead we look at the headers ourselves and // handle authentication directly. try { if (!rdata.IsAuthenticated) { rdata.Fail(Rest.HttpStatusCodeNotAuthorized, String.Format("user \"{0}\" could not be authenticated")); } } catch (RestException e) { if (e.statusCode == Rest.HttpStatusCodeNotAuthorized) { Rest.Log.WarnFormat("{0} User not authenticated", MsgId); Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization")); } else { Rest.Log.ErrorFormat("{0} User authentication failed", MsgId); Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization")); } throw (e); } // Remove the prefix and what's left are the parameters. If we don't have // the parameters we need, fail the request. Parameters do NOT include // any supplied query values. if (rdata.Parameters.Length > 0) { switch (rdata.method) { case "get" : DoGet(rdata); break; case "put" : DoPut(rdata); break; case "post" : DoPost(rdata); break; case "delete" : DoDelete(rdata); break; default : Rest.Log.WarnFormat("{0} File: Method not supported: {1}", MsgId, rdata.method); rdata.Fail(Rest.HttpStatusCodeBadRequest,String.Format("method <{0}> not supported", rdata.method)); break; } } else { Rest.Log.WarnFormat("{0} File: No agent information provided", MsgId); rdata.Fail(Rest.HttpStatusCodeBadRequest, "no agent information provided"); } Rest.Log.DebugFormat("{0} REST File handler EXIT", MsgId); } #endregion Interface /// <summary> /// The only parameter we recognize is a UUID.If an asset with this identification is /// found, it's content, base-64 encoded, is returned to the client. /// </summary> private void DoGet(FileRequestData rdata) { string path = String.Empty; Rest.Log.DebugFormat("{0} REST File handler, Method = <{1}> ENTRY", MsgId, rdata.method); if (rdata.Parameters.Length > 1) { try { path = rdata.path.Substring(rdata.Parameters[0].Length+qPrefix.Length+2); if (File.Exists(path)) { Rest.Log.DebugFormat("{0} File located <{1}>", MsgId, path); Byte[] data = File.ReadAllBytes(path); rdata.initXmlWriter(); rdata.writer.WriteStartElement(String.Empty,"File",String.Empty); rdata.writer.WriteAttributeString("name", path); rdata.writer.WriteBase64(data,0,data.Length); rdata.writer.WriteFullEndElement(); } else { Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, path); rdata.Fail(Rest.HttpStatusCodeNotFound, String.Format("invalid parameters : {0}", path)); } } catch (Exception e) { Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, e.Message); rdata.Fail(Rest.HttpStatusCodeNotFound, String.Format("invalid parameters : {0} {1}", path, e.Message)); } } rdata.Complete(); rdata.Respond(String.Format("File <{0}> : Normal completion", rdata.method)); } /// <summary> /// UPDATE existing item, if it exists. URI identifies the item in question. /// The only parameter we recognize is a UUID. The enclosed asset data (base-64 encoded) /// is decoded and stored in the database, identified by the supplied UUID. /// </summary> private void DoPut(FileRequestData rdata) { bool modified = false; bool created = false; string path = String.Empty; Rest.Log.DebugFormat("{0} REST File handler, Method = <{1}> ENTRY", MsgId, rdata.method); if (rdata.Parameters.Length > 1) { try { path = rdata.path.Substring(rdata.Parameters[0].Length+qPrefix.Length+2); bool maymod = File.Exists(path); rdata.initXmlReader(); XmlReader xml = rdata.reader; if (!xml.ReadToFollowing("File")) { Rest.Log.DebugFormat("{0} Invalid request data: <{1}>", MsgId, rdata.path); rdata.Fail(Rest.HttpStatusCodeBadRequest,"invalid request data"); } Byte[] data = Convert.FromBase64String(xml.ReadElementContentAsString("File", "")); File.WriteAllBytes(path,data); modified = maymod; created = ! maymod; } catch (Exception e) { Rest.Log.DebugFormat("{0} Exception during file processing : {1}", MsgId, e.Message); } } else { Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, rdata.path); rdata.Fail(Rest.HttpStatusCodeNotFound, "invalid parameters"); } if (created) { rdata.appendStatus(String.Format("<p> Created file {0} <p>", path)); rdata.Complete(Rest.HttpStatusCodeCreated); } else { if (modified) { rdata.appendStatus(String.Format("<p> Modified file {0} <p>", path)); rdata.Complete(Rest.HttpStatusCodeOK); } else { rdata.Complete(Rest.HttpStatusCodeNoContent); } } rdata.Respond(String.Format("File {0} : Normal completion", rdata.method)); } /// <summary> /// CREATE new item, replace if it exists. URI identifies the context for the item in question. /// No parameters are required for POST, just thepayload. /// </summary> private void DoPost(FileRequestData rdata) { bool modified = false; bool created = false; string path = String.Empty; Rest.Log.DebugFormat("{0} REST File handler, Method = <{1}> ENTRY", MsgId, rdata.method); if (rdata.Parameters.Length > 1) { try { path = rdata.path.Substring(rdata.Parameters[0].Length+qPrefix.Length+2); bool maymod = File.Exists(path); rdata.initXmlReader(); XmlReader xml = rdata.reader; if (!xml.ReadToFollowing("File")) { Rest.Log.DebugFormat("{0} Invalid request data: <{1}>", MsgId, rdata.path); rdata.Fail(Rest.HttpStatusCodeBadRequest,"invalid request data"); } Byte[] data = Convert.FromBase64String(xml.ReadElementContentAsString("File", "")); File.WriteAllBytes(path,data); modified = maymod; created = ! maymod; } catch (Exception e) { Rest.Log.DebugFormat("{0} Exception during file processing : {1}", MsgId, e.Message); } } else { Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, rdata.path); rdata.Fail(Rest.HttpStatusCodeNotFound, "invalid parameters"); } if (created) { rdata.appendStatus(String.Format("<p> Created file {0} <p>", path)); rdata.Complete(Rest.HttpStatusCodeCreated); } else { if (modified) { rdata.appendStatus(String.Format("<p> Modified file {0} <p>", path)); rdata.Complete(Rest.HttpStatusCodeOK); } else { rdata.Complete(Rest.HttpStatusCodeNoContent); } } rdata.Respond(String.Format("File {0} : Normal completion", rdata.method)); } /// <summary> /// CREATE new item, replace if it exists. URI identifies the context for the item in question. /// No parameters are required for POST, just thepayload. /// </summary> private void DoDelete(FileRequestData rdata) { bool modified = false; bool created = false; string path = String.Empty; Rest.Log.DebugFormat("{0} REST File handler, Method = <{1}> ENTRY", MsgId, rdata.method); if (rdata.Parameters.Length > 1) { try { path = rdata.path.Substring(rdata.Parameters[0].Length+qPrefix.Length+2); if (File.Exists(path)) { File.Delete(path); } } catch (Exception e) { Rest.Log.DebugFormat("{0} Exception during file processing : {1}", MsgId, e.Message); rdata.Fail(Rest.HttpStatusCodeNotFound, String.Format("invalid parameters : {0} {1}", path, e.Message)); } } else { Rest.Log.DebugFormat("{0} Invalid parameters: <{1}>", MsgId, rdata.path); rdata.Fail(Rest.HttpStatusCodeNotFound, "invalid parameters"); } if (created) { rdata.appendStatus(String.Format("<p> Created file {0} <p>", path)); rdata.Complete(Rest.HttpStatusCodeCreated); } else { if (modified) { rdata.appendStatus(String.Format("<p> Modified file {0} <p>", path)); rdata.Complete(Rest.HttpStatusCodeOK); } else { rdata.Complete(Rest.HttpStatusCodeNoContent); } } rdata.Respond(String.Format("File {0} : Normal completion", rdata.method)); } /// <summary> /// File processing has no special data area requirements. /// </summary> internal class FileRequestData : RequestData { internal FileRequestData(OSHttpRequest request, OSHttpResponse response, string prefix) : base(request, response, prefix) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogical128BitLaneInt641() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt641 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar; private Vector256<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt641() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt641() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (long)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftRightLogical128BitLane( Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftRightLogical128BitLane( Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftRightLogical128BitLane( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneInt641(); var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != 576460752303423488L) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 2 ? result[i] != 576460752303423488L : result[i] != 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<Int64>(Vector256<Int64><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maximum precision for numeric types internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; // can we get rid of this (?just have a mapping?) this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0; } } private static bool _IsAnsiType(SqlDbType type) { return (type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return (type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int)type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return ((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int)SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return ((int)type >= 0 && ((int)type <= (int)SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch (target) { case SqlDbType.BigInt: return s_metaBigInt; case SqlDbType.Binary: return s_metaBinary; case SqlDbType.Bit: return s_metaBit; case SqlDbType.Char: return s_metaChar; case SqlDbType.DateTime: return s_metaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return s_metaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return s_metaInt; case SqlDbType.Money: return s_metaMoney; case SqlDbType.NChar: return s_metaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return s_metaReal; case SqlDbType.UniqueIdentifier: return s_metaUniqueId; case SqlDbType.SmallDateTime: return s_metaSmallDateTime; case SqlDbType.SmallInt: return s_metaSmallInt; case SqlDbType.SmallMoney: return s_metaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return s_metaTimestamp; case SqlDbType.TinyInt: return s_metaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return s_metaVarChar; case SqlDbType.Variant: return s_metaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Udt: return MetaUdt; case SqlDbType.Structured: if (isMultiValued) { return s_metaTable; } else { return s_metaSUDT; } case SqlDbType.Date: return s_metaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return s_metaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return s_metaVarChar; case DbType.AnsiStringFixedLength: return s_metaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return s_metaTinyInt; case DbType.Boolean: return s_metaBit; case DbType.Currency: return s_metaMoney; case DbType.Date: case DbType.DateTime: return s_metaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return s_metaFloat; case DbType.Guid: return s_metaUniqueId; case DbType.Int16: return s_metaSmallInt; case DbType.Int32: return s_metaInt; case DbType.Int64: return s_metaBigInt; case DbType.Object: return s_metaVariant; case DbType.Single: return s_metaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return s_metaNChar; case DbType.Time: return s_metaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return s_metaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: return s_metaMaxUdt; default: return mt; } } // // map COM+ Type to MetaType class // internal static MetaType GetMetaTypeFromType(Type dataType, bool streamAllowed = true) { if (dataType == typeof(System.Byte[])) return MetaVarBinary; else if (dataType == typeof(System.Guid)) return s_metaUniqueId; else if (dataType == typeof(System.Object)) return s_metaVariant; else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return s_metaBit; else if (dataType == typeof(SqlByte)) return s_metaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; else if (dataType == typeof(SqlDateTime)) return s_metaDateTime; else if (dataType == typeof(SqlDouble)) return s_metaFloat; else if (dataType == typeof(SqlGuid)) return s_metaUniqueId; else if (dataType == typeof(SqlInt16)) return s_metaSmallInt; else if (dataType == typeof(SqlInt32)) return s_metaInt; else if (dataType == typeof(SqlInt64)) return s_metaBigInt; else if (dataType == typeof(SqlMoney)) return s_metaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return s_metaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) return MetaNVarChar; else if (dataType == typeof(IEnumerable<DbDataRecord>)) return s_metaTable; else if (dataType == typeof(TimeSpan)) return MetaTime; else if (dataType == typeof(DateTimeOffset)) return MetaDateTimeOffset; else if (dataType == typeof(DBNull)) throw ADP.InvalidDataType(nameof(DBNull)); else if (dataType == typeof(Boolean)) return s_metaBit; else if (dataType == typeof(Char)) throw ADP.InvalidDataType(nameof(Char)); else if (dataType == typeof(SByte)) throw ADP.InvalidDataType(nameof(SByte)); else if (dataType == typeof(Byte)) return s_metaTinyInt; else if (dataType == typeof(Int16)) return s_metaSmallInt; else if (dataType == typeof(UInt16)) throw ADP.InvalidDataType(nameof(UInt16)); else if (dataType == typeof(Int32)) return s_metaInt; else if (dataType == typeof(UInt32)) throw ADP.InvalidDataType(nameof(UInt32)); else if (dataType == typeof(Int64)) return s_metaBigInt; else if (dataType == typeof(UInt64)) throw ADP.InvalidDataType(nameof(UInt64)); else if (dataType == typeof(Single)) return s_metaReal; else if (dataType == typeof(Double)) return s_metaFloat; else if (dataType == typeof(Decimal)) return MetaDecimal; else if (dataType == typeof(DateTime)) return s_metaDateTime; else if (dataType == typeof(String)) return MetaNVarChar; else throw ADP.UnknownDataType(dataType); } internal static MetaType GetMetaTypeFromValue(object value, bool inferLen = true, bool streamAllowed = true) { if (value == null) { throw ADP.InvalidDataType("null"); } if (value is DBNull) { throw ADP.InvalidDataType(nameof(DBNull)); } Type dataType = value.GetType(); switch (Convert.GetTypeCode(value)) { case TypeCode.Empty: throw ADP.InvalidDataType(nameof(TypeCode.Empty)); case TypeCode.Object: if (dataType == typeof (System.Byte[])) { if (!inferLen || ((byte[]) value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } if (dataType == typeof (System.Guid)) { return s_metaUniqueId; } if (dataType == typeof (System.Object)) { return s_metaVariant; } // check sql types now if (dataType == typeof (SqlBinary)) return MetaVarBinary; if (dataType == typeof (SqlBoolean)) return s_metaBit; if (dataType == typeof (SqlByte)) return s_metaTinyInt; if (dataType == typeof (SqlBytes)) return MetaVarBinary; if (dataType == typeof (SqlChars)) return MetaNVarChar; if (dataType == typeof (SqlDateTime)) return s_metaDateTime; if (dataType == typeof (SqlDouble)) return s_metaFloat; if (dataType == typeof (SqlGuid)) return s_metaUniqueId; if (dataType == typeof (SqlInt16)) return s_metaSmallInt; if (dataType == typeof (SqlInt32)) return s_metaInt; if (dataType == typeof (SqlInt64)) return s_metaBigInt; if (dataType == typeof (SqlMoney)) return s_metaMoney; if (dataType == typeof (SqlDecimal)) return MetaDecimal; if (dataType == typeof (SqlSingle)) return s_metaReal; if (dataType == typeof (SqlXml)) return MetaXml; if (dataType == typeof (SqlString)) { return ((inferLen && !((SqlString) value).IsNull) ? PromoteStringType(((SqlString) value).Value) : MetaNVarChar); } if (dataType == typeof (IEnumerable<DbDataRecord>) || dataType == typeof (DataTable)) { return s_metaTable; } if (dataType == typeof (TimeSpan)) { return MetaTime; } if (dataType == typeof (DateTimeOffset)) { return MetaDateTimeOffset; } if (streamAllowed) { // Derived from Stream ? if (value is Stream) { return MetaVarBinary; } // Derived from TextReader ? if (value is TextReader) { return MetaNVarChar; } // Derived from XmlReader ? if (value is XmlReader) { return MetaXml; } } throw ADP.UnknownDataType(dataType); case TypeCode.Boolean: return s_metaBit; case TypeCode.Char: throw ADP.InvalidDataType(nameof(TypeCode.Char)); case TypeCode.SByte: throw ADP.InvalidDataType(nameof(TypeCode.SByte)); case TypeCode.Byte: return s_metaTinyInt; case TypeCode.Int16: return s_metaSmallInt; case TypeCode.UInt16: throw ADP.InvalidDataType(nameof(TypeCode.UInt16)); case TypeCode.Int32: return s_metaInt; case TypeCode.UInt32: throw ADP.InvalidDataType(nameof(TypeCode.UInt32)); case TypeCode.Int64: return s_metaBigInt; case TypeCode.UInt64: throw ADP.InvalidDataType(nameof(TypeCode.UInt64)); case TypeCode.Single: return s_metaReal; case TypeCode.Double: return s_metaFloat; case TypeCode.Decimal: return MetaDecimal; case TypeCode.DateTime: return s_metaDateTime; case TypeCode.String: return (inferLen ? PromoteStringType((string) value) : MetaNVarChar); default: throw ADP.UnknownDataType(dataType); } } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DataTable)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Assert(false, "Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return s_metaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { Debug.Assert(false, "unknown SqlType class stored in sqlVal"); } return comVal; } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is System.Byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is System.Char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is System.Char[]) sqlVal = new SqlChars((System.Char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is Int16) sqlVal = new SqlInt16((Int16)comVal); else if (comVal is Int32) sqlVal = new SqlInt32((Int32)comVal); else if (comVal is Int64) sqlVal = new SqlInt64((Int64)comVal); else if (comVal is Decimal) sqlVal = new SqlDecimal((Decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Assert(false, "unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: //goto TdsEnums.SQLBIGVARCHAR; case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar; case TdsEnums.SQLBINARY: //goto TdsEnums.SQLBIGBINARY; case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: //goto TdsEnums.SQLBIGCHAR; case TdsEnums.SQLBIGCHAR: return s_metaChar; case TdsEnums.SQLINT1: return s_metaTinyInt; case TdsEnums.SQLBIT: //goto TdsEnums.SQLBITN; case TdsEnums.SQLBITN: return s_metaBit; case TdsEnums.SQLINT2: return s_metaSmallInt; case TdsEnums.SQLINT4: return s_metaInt; case TdsEnums.SQLINT8: return s_metaBigInt; case TdsEnums.SQLMONEY: return s_metaMoney; case TdsEnums.SQLDATETIME: return s_metaDateTime; case TdsEnums.SQLFLT8: return s_metaFloat; case TdsEnums.SQLFLT4: return s_metaReal; case TdsEnums.SQLMONEY4: return s_metaSmallMoney; case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime; case TdsEnums.SQLDECIMALN: //goto TdsEnums.SQLNUMERICN; case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return s_metaUniqueId; case TdsEnums.SQLNCHAR: return s_metaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return s_metaVariant; case TdsEnums.SQLUDT: return MetaUdt; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return s_metaTable; case TdsEnums.SQLDATE: return s_metaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return s_metaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Assert(false, "Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); }// case } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static String GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType s_metaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(System.Int64), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType s_metaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(System.Double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType s_metaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(System.Single), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType s_metaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // Syntactic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType s_metaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // HACK!!! We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user! private static readonly MetaType s_metaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType s_metaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(System.Boolean), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType s_metaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(System.Byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType s_metaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(System.Int16), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType s_metaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(System.Int32), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(System.String), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType s_metaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(System.String), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(System.String), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(System.Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(System.String), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType s_metaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType s_metaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType s_metaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType s_metaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType s_metaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType s_metaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(System.Object), typeof(System.Object), SqlDbType.Variant, DbType.Object, 0); internal static readonly MetaType MetaUdt = new MetaType (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaMaxUdt = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType s_metaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days & minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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.Linq; using NUnit.Framework; using Sensus.Extensions; using Sensus.Probes.User.Scripts; namespace Sensus.Tests.Probes.User.Scripts { [TestFixture] public class ScheduleTriggerTests { [Test] public void Deserialize1PointTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00" }; Assert.AreEqual(1, schedule.WindowCount); Assert.AreEqual("10:00", schedule.WindowsString); } [Test] public void Deserialize1WindowTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00-10:30" }; Assert.AreEqual(1, schedule.WindowCount); Assert.AreEqual("10:00-10:30", schedule.WindowsString); } [Test] public void Deserialize1PointTrailingCommaTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00," }; Assert.AreEqual(1, schedule.WindowCount); Assert.AreEqual("10:00", schedule.WindowsString); } [Test] public void Deserialize1Point1WindowTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00,10:10-10:20" }; Assert.AreEqual(2, schedule.WindowCount); Assert.AreEqual("10:00, 10:10-10:20", schedule.WindowsString); } [Test] public void Deserialize1Point1WindowSpacesTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" }; Assert.AreEqual(2, schedule.WindowCount); Assert.AreEqual("10:00, 10:10-10:20", schedule.WindowsString); } [Test] public void DowDeserialize1PointTest() { var schedule = new ScheduleTrigger { WindowsString = "Su-10:00" }; Assert.AreEqual(1, schedule.WindowCount); Assert.AreEqual("Su-10:00", schedule.WindowsString); } [Test] public void DowDeserialize1WindowTest() { var schedule = new ScheduleTrigger { WindowsString = "Mo-10:00-10:30" }; Assert.AreEqual(1, schedule.WindowCount); Assert.AreEqual("Mo-10:00-10:30", schedule.WindowsString); } [Test] public void DowDeserialize1PointTrailingCommaTest() { var schedule = new ScheduleTrigger { WindowsString = "Tu-10:00," }; Assert.AreEqual(1, schedule.WindowCount); Assert.AreEqual("Tu-10:00", schedule.WindowsString); } [Test] public void DowDeserialize1Point1WindowTest() { var schedule = new ScheduleTrigger { WindowsString = "We-10:00,10:10-10:20" }; Assert.AreEqual(2, schedule.WindowCount); Assert.AreEqual("We-10:00, 10:10-10:20", schedule.WindowsString); } [Test] public void DowDeserialize1Point1WindowSpacesTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, Th-10:10-10:20" }; Assert.AreEqual(2, schedule.WindowCount); Assert.AreEqual("10:00, Th-10:10-10:20", schedule.WindowsString); } [Test] public void SchedulesAllFutureTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" }; var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0); var afterDate = new DateTime(1986, 4, 18, 0, 0, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray(); Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0)); Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0)); Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0)); } [Test] public void SchedulesOneFutureTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:20-10:30" }; var referenceDate = new DateTime(1986, 4, 18, 10, 10, 0); var afterDate = new DateTime(1986, 4, 18, 10, 10, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray(); Assert.IsTrue(new TimeSpan(0, 0, 10, 0) <= triggerTimes[0].ReferenceTillTrigger && triggerTimes[0].ReferenceTillTrigger <= new TimeSpan(0, 0, 20, 0)); Assert.AreEqual(new TimeSpan(0, 23, 50, 0), triggerTimes[1].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(1, 0, 10, 0) <= triggerTimes[2].ReferenceTillTrigger && triggerTimes[2].ReferenceTillTrigger <= new TimeSpan(1, 0, 20, 0)); Assert.AreEqual(new TimeSpan(1, 23, 50, 0), triggerTimes[3].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 0, 10, 0) <= triggerTimes[4].ReferenceTillTrigger && triggerTimes[4].ReferenceTillTrigger <= new TimeSpan(2, 0, 20, 0)); Assert.AreEqual(new TimeSpan(2, 23, 50, 0), triggerTimes[5].ReferenceTillTrigger); } [Test] public void SchedulesAfterOneDayTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:20-10:30" }; var referenceDate = new DateTime(1986, 4, 18, 10, 10, 0); var afterDate = new DateTime(1986, 4, 19, 10, 10, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray(); Assert.IsTrue(new TimeSpan(1, 0, 10, 0) <= triggerTimes[0].ReferenceTillTrigger && triggerTimes[0].ReferenceTillTrigger <= new TimeSpan(1, 0, 20, 0)); Assert.AreEqual(new TimeSpan(1, 23, 50, 0), triggerTimes[1].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 0, 10, 0) <= triggerTimes[2].ReferenceTillTrigger && triggerTimes[2].ReferenceTillTrigger <= new TimeSpan(2, 0, 20, 0)); Assert.AreEqual(new TimeSpan(2, 23, 50, 0), triggerTimes[3].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(3, 0, 10, 0) <= triggerTimes[4].ReferenceTillTrigger && triggerTimes[4].ReferenceTillTrigger <= new TimeSpan(3, 0, 20, 0)); Assert.AreEqual(new TimeSpan(3, 23, 50, 0), triggerTimes[5].ReferenceTillTrigger); } [Test] public void SchedulesPullsOnlySevenDays() { var schedule = new ScheduleTrigger { WindowsString = "10:00" }; var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0); var afterDate = new DateTime(1986, 4, 19, 0, 0, 0); var triggerTimeCount = schedule.GetTriggerTimes(referenceDate, afterDate).Count(); Assert.AreEqual(7, triggerTimeCount); } [Test] public void SchedulesAllFutureNoExpirationsTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" }; var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0); var afterDate = new DateTime(1986, 4, 18, 0, 0, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray(); Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0)); Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0)); Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0)); Assert.AreEqual(null, triggerTimes[0].Expiration); Assert.AreEqual(null, triggerTimes[1].Expiration); Assert.AreEqual(null, triggerTimes[2].Expiration); Assert.AreEqual(null, triggerTimes[3].Expiration); Assert.AreEqual(null, triggerTimes[4].Expiration); Assert.AreEqual(null, triggerTimes[5].Expiration); } [Test] public void SchedulesAllFutureExpirationAgeTest() { var schedule = new ScheduleTrigger { WindowsString = "10:00, 10:10-10:20" }; var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0); var afterDate = new DateTime(1986, 4, 18, 0, 0, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate, TimeSpan.FromMinutes(10)).Take(6).ToArray(); Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0)); Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0)); Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0)); Assert.AreEqual(referenceDate + triggerTimes[0].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[0].Expiration); Assert.AreEqual(referenceDate + triggerTimes[1].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[1].Expiration); Assert.AreEqual(referenceDate + triggerTimes[2].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[2].Expiration); Assert.AreEqual(referenceDate + triggerTimes[3].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[3].Expiration); Assert.AreEqual(referenceDate + triggerTimes[4].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[4].Expiration); Assert.AreEqual(referenceDate + triggerTimes[5].ReferenceTillTrigger + TimeSpan.FromMinutes(10), triggerTimes[5].Expiration); } [Test] public void SchedulesAllFutureExpirationWindowTest() { var schedule = new ScheduleTrigger { WindowExpiration = true, WindowsString = "10:00, 10:10-10:20" }; var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0); var afterDate = new DateTime(1986, 4, 18, 0, 0, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate).Take(6).ToArray(); Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0)); Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0)); Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0)); Assert.AreEqual(null, triggerTimes[0].Expiration); Assert.AreEqual(new DateTime(1986, 4, 18, 10, 20, 00), triggerTimes[1].Expiration); Assert.AreEqual(null, triggerTimes[2].Expiration); Assert.AreEqual(new DateTime(1986, 4, 19, 10, 20, 00), triggerTimes[3].Expiration); Assert.AreEqual(null, triggerTimes[4].Expiration); Assert.AreEqual(new DateTime(1986, 4, 20, 10, 20, 00), triggerTimes[5].Expiration); } [Test] public void SchedulesAllFutureExpirationWindowAndAgeTest() { var schedule = new ScheduleTrigger { WindowExpiration = true, WindowsString = "10:00, 10:10-10:20" }; var referenceDate = new DateTime(1986, 4, 18, 0, 0, 0); var afterDate = new DateTime(1986, 4, 18, 0, 0, 0); var triggerTimes = schedule.GetTriggerTimes(referenceDate, afterDate, TimeSpan.FromMinutes(5)).Take(6).ToArray(); Assert.AreEqual(new TimeSpan(0, 10, 0, 0), triggerTimes[0].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(0, 10, 10, 0) <= triggerTimes[1].ReferenceTillTrigger && triggerTimes[1].ReferenceTillTrigger <= new TimeSpan(0, 10, 20, 0)); Assert.AreEqual(new TimeSpan(1, 10, 0, 0), triggerTimes[2].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(1, 10, 10, 0) <= triggerTimes[3].ReferenceTillTrigger && triggerTimes[3].ReferenceTillTrigger <= new TimeSpan(1, 10, 20, 0)); Assert.AreEqual(new TimeSpan(2, 10, 0, 0), triggerTimes[4].ReferenceTillTrigger); Assert.IsTrue(new TimeSpan(2, 10, 10, 0) <= triggerTimes[5].ReferenceTillTrigger && triggerTimes[5].ReferenceTillTrigger <= new TimeSpan(2, 10, 20, 0)); Assert.AreEqual(referenceDate + triggerTimes[0].ReferenceTillTrigger + TimeSpan.FromMinutes(5), triggerTimes[0].Expiration); Assert.AreEqual(new DateTime(1986, 4, 18, 10, 20, 00).Min(referenceDate + triggerTimes[1].ReferenceTillTrigger + TimeSpan.FromMinutes(5)), triggerTimes[1].Expiration); Assert.AreEqual(referenceDate + triggerTimes[2].ReferenceTillTrigger + TimeSpan.FromMinutes(5), triggerTimes[2].Expiration); Assert.AreEqual(new DateTime(1986, 4, 19, 10, 20, 00).Min(referenceDate + triggerTimes[3].ReferenceTillTrigger + TimeSpan.FromMinutes(5)), triggerTimes[3].Expiration); Assert.AreEqual(referenceDate + triggerTimes[4].ReferenceTillTrigger + TimeSpan.FromMinutes(5), triggerTimes[4].Expiration); Assert.AreEqual(new DateTime(1986, 4, 20, 10, 20, 00).Min(referenceDate + triggerTimes[5].ReferenceTillTrigger + TimeSpan.FromMinutes(5)), triggerTimes[5].Expiration); } [Test] public void DowSameDayTest() { var schedule = new ScheduleTrigger { WindowsString = "Mo-12:34" }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(6).ToArray(); Assert.AreEqual(triggerTimes[0].Trigger, reference + new TimeSpan(0, 2, 34, 0)); Assert.AreEqual(triggerTimes[1].Trigger, reference + new TimeSpan(7, 2, 34, 0)); Assert.AreEqual(triggerTimes[2].Trigger, reference + new TimeSpan(14, 2, 34, 0)); Assert.AreEqual(triggerTimes[3].Trigger, reference + new TimeSpan(21, 2, 34, 0)); Assert.AreEqual(triggerTimes[4].Trigger, reference + new TimeSpan(28, 2, 34, 0)); Assert.AreEqual(triggerTimes[5].Trigger, reference + new TimeSpan(35, 2, 34, 0)); } [Test] public void DowSameDayPriorToAfterTimeTest() { var schedule = new ScheduleTrigger { WindowsString = "Mo-8:34" // this time is prior to the time of day specified in the after datetime. we allow this to be scheduled. in practice this will cause surveys (and other scheduled events) to trigger immediately. }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(6).ToArray(); Assert.AreEqual(triggerTimes[0].Trigger, reference + new TimeSpan(0, -2, 34, 0)); Assert.AreEqual(triggerTimes[1].Trigger, reference + new TimeSpan(7, -2, 34, 0)); Assert.AreEqual(triggerTimes[2].Trigger, reference + new TimeSpan(14, -2, 34, 0)); Assert.AreEqual(triggerTimes[3].Trigger, reference + new TimeSpan(21, -2, 34, 0)); Assert.AreEqual(triggerTimes[4].Trigger, reference + new TimeSpan(28, -2, 34, 0)); Assert.AreEqual(triggerTimes[5].Trigger, reference + new TimeSpan(35, -2, 34, 0)); } [Test] public void DowWithinWeekTest() { var schedule = new ScheduleTrigger { WindowsString = "Fr-12:34" }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(6).ToArray(); Assert.AreEqual(triggerTimes[0].Trigger, reference + new TimeSpan(4, 2, 34, 0)); Assert.AreEqual(triggerTimes[1].Trigger, reference + new TimeSpan(11, 2, 34, 0)); Assert.AreEqual(triggerTimes[2].Trigger, reference + new TimeSpan(18, 2, 34, 0)); Assert.AreEqual(triggerTimes[3].Trigger, reference + new TimeSpan(25, 2, 34, 0)); Assert.AreEqual(triggerTimes[4].Trigger, reference + new TimeSpan(32, 2, 34, 0)); Assert.AreEqual(triggerTimes[5].Trigger, reference + new TimeSpan(39, 2, 34, 0)); } [Test] public void DowNextWeekTest() { var schedule = new ScheduleTrigger { WindowsString = "Su-12:34" }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(6).ToArray(); Assert.AreEqual(triggerTimes[0].Trigger, reference + new TimeSpan(6, 2, 34, 0)); Assert.AreEqual(triggerTimes[1].Trigger, reference + new TimeSpan(13, 2, 34, 0)); Assert.AreEqual(triggerTimes[2].Trigger, reference + new TimeSpan(20, 2, 34, 0)); Assert.AreEqual(triggerTimes[3].Trigger, reference + new TimeSpan(27, 2, 34, 0)); Assert.AreEqual(triggerTimes[4].Trigger, reference + new TimeSpan(34, 2, 34, 0)); Assert.AreEqual(triggerTimes[5].Trigger, reference + new TimeSpan(41, 2, 34, 0)); } [Test] public void DowNextWeekPriorToAfterTimeOfDayTest() { var schedule = new ScheduleTrigger { WindowsString = "Su-8:34" // this time of day is prior to the after time of day below. with day-interval-based scheduling, we would skip ahead to the next day (monday) at this time. with dow-based scheduling we will schedule at this exact time. }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(6).ToArray(); Assert.AreEqual(triggerTimes[0].Trigger, reference + new TimeSpan(6, -2, 34, 0)); Assert.AreEqual(triggerTimes[1].Trigger, reference + new TimeSpan(13, -2, 34, 0)); Assert.AreEqual(triggerTimes[2].Trigger, reference + new TimeSpan(20, -2, 34, 0)); Assert.AreEqual(triggerTimes[3].Trigger, reference + new TimeSpan(27, -2, 34, 0)); Assert.AreEqual(triggerTimes[4].Trigger, reference + new TimeSpan(34, -2, 34, 0)); Assert.AreEqual(triggerTimes[5].Trigger, reference + new TimeSpan(41, -2, 34, 0)); } [Test] public void DowNextWeekPriorToAfterTimeOfDayPlusIntervalBasedWindowTest() { var schedule = new ScheduleTrigger { WindowsString = "Su-8:34,10:00" // this time of day is prior to the after time of day below. with day-interval-based scheduling, we would skip ahead to the next day (monday) at this time. with dow-based scheduling we will schedule at this exact time. }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(14).ToArray(); Assert.AreEqual(14, triggerTimes.Length); // the 10am interval-based trigger should be scheduled for 10am each day, starting with tomorrow. Assert.AreEqual(triggerTimes[0].Trigger, reference + TimeSpan.FromDays(1)); // Tuesday Assert.AreEqual(triggerTimes[1].Trigger, reference + TimeSpan.FromDays(2)); // Wednesday Assert.AreEqual(triggerTimes[2].Trigger, reference + TimeSpan.FromDays(3)); // Thursday Assert.AreEqual(triggerTimes[3].Trigger, reference + TimeSpan.FromDays(4)); // Friday Assert.AreEqual(triggerTimes[4].Trigger, reference + TimeSpan.FromDays(5)); // Saturday Assert.AreEqual(triggerTimes[5].Trigger, reference + new TimeSpan(6, -2, 34, 0)); // On Sunday, the DOW-based window will be scheduled at 8:34am... Assert.AreEqual(triggerTimes[6].Trigger, reference + TimeSpan.FromDays(6)); // ...preceding our 10am interval-based trigger. Assert.AreEqual(triggerTimes[7].Trigger, reference + TimeSpan.FromDays(7)); Assert.AreEqual(triggerTimes[8].Trigger, reference + new TimeSpan(13, -2, 34, 0)); // we only schedule 7 windows, so there are no more interval-based triggers left. Assert.AreEqual(triggerTimes[9].Trigger, reference + new TimeSpan(20, -2, 34, 0)); Assert.AreEqual(triggerTimes[10].Trigger, reference + new TimeSpan(27, -2, 34, 0)); Assert.AreEqual(triggerTimes[11].Trigger, reference + new TimeSpan(34, -2, 34, 0)); Assert.AreEqual(triggerTimes[12].Trigger, reference + new TimeSpan(41, -2, 34, 0)); Assert.AreEqual(triggerTimes[13].Trigger, reference + new TimeSpan(48, -2, 34, 0)); } [Test] public void DowNextWeekWindowExpirationTest() { var schedule = new ScheduleTrigger { WindowExpiration = true, WindowsString = "Su-12:00-14:00" }; var reference = new DateTime(2017, 7, 10, 10, 0, 0); var after = new DateTime(2017, 7, 10, 10, 0, 0); // 2017-7-10 was a Monday var triggerTimes = schedule.GetTriggerTimes(reference, after).Take(6).ToArray(); Assert.GreaterOrEqual(triggerTimes[0].Trigger, reference + new TimeSpan(6, 2, 0, 0)); Assert.LessOrEqual(triggerTimes[0].Trigger, reference + new TimeSpan(6, 4, 0, 0)); Assert.AreEqual(triggerTimes[0].Expiration.Value, reference + new TimeSpan(6, 4, 0, 0)); Assert.GreaterOrEqual(triggerTimes[1].Trigger, reference + new TimeSpan(13, 2, 0, 0)); Assert.LessOrEqual(triggerTimes[1].Trigger, reference + new TimeSpan(13, 4, 0, 0)); Assert.AreEqual(triggerTimes[1].Expiration.Value, reference + new TimeSpan(13, 4, 0, 0)); Assert.GreaterOrEqual(triggerTimes[2].Trigger, reference + new TimeSpan(20, 2, 0, 0)); Assert.LessOrEqual(triggerTimes[2].Trigger, reference + new TimeSpan(20, 4, 0, 0)); Assert.AreEqual(triggerTimes[2].Expiration.Value, reference + new TimeSpan(20, 4, 0, 0)); Assert.GreaterOrEqual(triggerTimes[3].Trigger, reference + new TimeSpan(27, 2, 0, 0)); Assert.LessOrEqual(triggerTimes[3].Trigger, reference + new TimeSpan(27, 4, 0, 0)); Assert.AreEqual(triggerTimes[3].Expiration.Value, reference + new TimeSpan(27, 4, 0, 0)); Assert.GreaterOrEqual(triggerTimes[4].Trigger, reference + new TimeSpan(34, 2, 0, 0)); Assert.LessOrEqual(triggerTimes[4].Trigger, reference + new TimeSpan(34, 4, 0, 0)); Assert.AreEqual(triggerTimes[4].Expiration.Value, reference + new TimeSpan(34, 4, 0, 0)); Assert.GreaterOrEqual(triggerTimes[5].Trigger, reference + new TimeSpan(41, 2, 0, 0)); Assert.LessOrEqual(triggerTimes[5].Trigger, reference + new TimeSpan(41, 4, 0, 0)); Assert.AreEqual(triggerTimes[5].Expiration.Value, reference + new TimeSpan(41, 4, 0, 0)); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEditor; using UnityEditorInternal; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Rotorz.ReorderableList; using System.IO; using System.Reflection; namespace Fungus.EditorUtils { [CustomEditor(typeof(Block))] public class BlockEditor : Editor { protected class SetEventHandlerOperation { public Block block; public Type eventHandlerType; } protected class AddCommandOperation { public Type commandType; } private static readonly char[] SPLIT_INPUT_ON = new char[] { ' ', '/', '\\' }; private static readonly int MAX_PREVIEW_GRID = 7; private static readonly string ELIPSIS = "..."; public static List<Action> actionList = new List<Action>(); protected Texture2D upIcon; protected Texture2D downIcon; protected Texture2D addIcon; protected Texture2D duplicateIcon; protected Texture2D deleteIcon; protected string commandTextFieldContents = string.Empty; protected int filteredCommandPreviewSelectedItem = 0; protected Type commandSelectedByTextInput; static List<System.Type> commandTypes; static List<System.Type> eventHandlerTypes; static void CacheEventHandlerTypes() { eventHandlerTypes = EditorExtensions.FindDerivedTypes(typeof(EventHandler)).ToList(); commandTypes = EditorExtensions.FindDerivedTypes(typeof(Command)).ToList(); } [UnityEditor.Callbacks.DidReloadScripts] private static void OnScriptsReloaded() { CacheEventHandlerTypes(); } protected virtual void OnEnable() { upIcon = FungusEditorResources.Up; downIcon = FungusEditorResources.Down; addIcon = FungusEditorResources.Add; duplicateIcon = FungusEditorResources.Duplicate; deleteIcon = FungusEditorResources.Delete; CacheEventHandlerTypes(); } public virtual void DrawBlockName(Flowchart flowchart) { serializedObject.Update(); SerializedProperty blockNameProperty = serializedObject.FindProperty("blockName"); Rect blockLabelRect = new Rect(45, 5, 120, 16); EditorGUI.LabelField(blockLabelRect, new GUIContent("Block Name")); Rect blockNameRect = new Rect(45, 21, 180, 16); EditorGUI.PropertyField(blockNameRect, blockNameProperty, new GUIContent("")); // Ensure block name is unique for this Flowchart var block = target as Block; string uniqueName = flowchart.GetUniqueBlockKey(blockNameProperty.stringValue, block); if (uniqueName != block.BlockName) { blockNameProperty.stringValue = uniqueName; } serializedObject.ApplyModifiedProperties(); } public virtual void DrawBlockGUI(Flowchart flowchart) { serializedObject.Update(); // Execute any queued cut, copy, paste, etc. operations from the prevous GUI update // We need to defer applying these operations until the following update because // the ReorderableList control emits GUI errors if you clear the list in the same frame // as drawing the control (e.g. select all and then delete) if (Event.current.type == EventType.Layout) { foreach (Action action in actionList) { if (action != null) { action(); } } actionList.Clear(); } var block = target as Block; SerializedProperty commandListProperty = serializedObject.FindProperty("commandList"); if (block == flowchart.SelectedBlock) { // Custom tinting SerializedProperty useCustomTintProp = serializedObject.FindProperty("useCustomTint"); SerializedProperty tintProp = serializedObject.FindProperty("tint"); EditorGUILayout.BeginHorizontal(); useCustomTintProp.boolValue = GUILayout.Toggle(useCustomTintProp.boolValue, " Custom Tint"); if (useCustomTintProp.boolValue) { EditorGUILayout.PropertyField(tintProp, GUIContent.none); } EditorGUILayout.EndHorizontal(); SerializedProperty descriptionProp = serializedObject.FindProperty("description"); EditorGUILayout.PropertyField(descriptionProp); DrawEventHandlerGUI(flowchart); block.UpdateIndentLevels(); // Make sure each command has a reference to its parent block foreach (var command in block.CommandList) { if (command == null) // Will be deleted from the list later on { continue; } command.ParentBlock = block; } ReorderableListGUI.Title("Commands"); CommandListAdaptor adaptor = new CommandListAdaptor(commandListProperty, 0); adaptor.nodeRect = block._NodeRect; ReorderableListFlags flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons | ReorderableListFlags.DisableContextMenu; if (block.CommandList.Count == 0) { EditorGUILayout.HelpBox("Press the + button below to add a command to the list.", MessageType.Info); } else { ReorderableListControl.DrawControlFromState(adaptor, null, flags); } // EventType.contextClick doesn't register since we moved the Block Editor to be inside // a GUI Area, no idea why. As a workaround we just check for right click instead. if (Event.current.type == EventType.mouseUp && Event.current.button == 1) { ShowContextMenu(); Event.current.Use(); } if (GUIUtility.keyboardControl == 0) //Only call keyboard shortcuts when not typing in a text field { Event e = Event.current; // Copy keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Copy") { if (flowchart.SelectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Copy") { actionList.Add(Copy); e.Use(); } // Cut keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Cut") { if (flowchart.SelectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Cut") { actionList.Add(Cut); e.Use(); } // Paste keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Paste") { CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); if (commandCopyBuffer.HasCommands()) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Paste") { actionList.Add(Paste); e.Use(); } // Duplicate keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Duplicate") { if (flowchart.SelectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Duplicate") { actionList.Add(Copy); actionList.Add(Paste); e.Use(); } // Delete keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Delete") { if (flowchart.SelectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Delete") { actionList.Add(Delete); e.Use(); } // SelectAll keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "SelectAll") { e.Use(); } if (e.type == EventType.ExecuteCommand && e.commandName == "SelectAll") { actionList.Add(SelectAll); e.Use(); } } } // Remove any null entries in the command list. // This can happen when a command class is deleted or renamed. for (int i = commandListProperty.arraySize - 1; i >= 0; --i) { SerializedProperty commandProperty = commandListProperty.GetArrayElementAtIndex(i); if (commandProperty.objectReferenceValue == null) { commandListProperty.DeleteArrayElementAtIndex(i); } } serializedObject.ApplyModifiedProperties(); } public virtual void DrawButtonToolbar() { GUILayout.BeginHorizontal(); //handle movement along our selection grid before something else eats our inputs if (Event.current.type == EventType.keyDown) { //up down to change selection / esc to clear field if (Event.current.keyCode == KeyCode.UpArrow) { filteredCommandPreviewSelectedItem--; } else if (Event.current.keyCode == KeyCode.DownArrow) { filteredCommandPreviewSelectedItem++; } if (commandSelectedByTextInput != null && Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter) { AddCommandCallback(commandSelectedByTextInput); commandSelectedByTextInput = null; commandTextFieldContents = String.Empty; //GUI.FocusControl("dummycontrol"); Event.current.Use(); filteredCommandPreviewSelectedItem = 0; } } // Previous Command if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.PageUp)) { SelectPrevious(); GUI.FocusControl("dummycontrol"); Event.current.Use(); } // Next Command if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.PageDown)) { SelectNext(); GUI.FocusControl("dummycontrol"); Event.current.Use(); } if (GUILayout.Button(upIcon)) { SelectPrevious(); } // Down Button if (GUILayout.Button(downIcon)) { SelectNext(); } GUILayout.FlexibleSpace(); //should track if text actually changes and pass that to the ShowPartialMatches so it can cache commandTextFieldContents = GUILayout.TextField(commandTextFieldContents, GUILayout.MinWidth(20), GUILayout.MaxWidth(200)); // Add Button if (GUILayout.Button(addIcon)) { ShowCommandMenu(); } // Duplicate Button if (GUILayout.Button(duplicateIcon)) { Copy(); Paste(); } // Delete Button if (GUILayout.Button(deleteIcon)) { Delete(); } GUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(commandTextFieldContents)) ShowPartialMatches(); } //Handles showing partial matches against the text input next to the AddCommand button // Splits and matches and can use up down arrows and return/enter/numenter to confirm // TODO add sorting of results so we get best match at the not just just a match // e.g. "if" should show Flow/If at the top not Flow/Else If private void ShowPartialMatches() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); //TODO this could be cached if input hasn't changed to avoid thrashing var filteredAttributes = GetFilteredSupportedCommands(flowchart); var upperCommandText = commandTextFieldContents.ToUpper().Trim(); if (upperCommandText.Length == 0) return; var tokens = upperCommandText.Split(SPLIT_INPUT_ON); //we want commands that have all the elements you have typed filteredAttributes = filteredAttributes.Where((x) => { bool catAny = tokens.Any(x.Value.Category.ToUpper().Contains); bool comAny = tokens.Any(x.Value.CommandName.ToUpper().Contains); bool catAll = tokens.All(x.Value.Category.ToUpper().Contains); bool comAll = tokens.All(x.Value.CommandName.ToUpper().Contains); //so if both category and command found something, then there are multiple tokens and they line up with category and command if (catAny && comAny) return true; //or its a single token or a complex token that matches entirely in cat or com else if (catAll || comAll) return true; //this setup avoids multiple bad suggestions due to a complex category name that gives many false matches on complex partials return false; }).ToList(); if (filteredAttributes == null || filteredAttributes.Count == 0) return; //show results GUILayout.Space(5); GUILayout.BeginHorizontal(); filteredCommandPreviewSelectedItem = Mathf.Clamp(filteredCommandPreviewSelectedItem, 0, filteredAttributes.Count - 1); var toShow = filteredAttributes.Select(x => x.Value.Category + "/" + x.Value.CommandName).ToArray(); //show the first x max that match our filters if(toShow.Length > MAX_PREVIEW_GRID) { toShow = toShow.Take(MAX_PREVIEW_GRID).ToArray(); toShow[MAX_PREVIEW_GRID - 1] = ELIPSIS; } filteredCommandPreviewSelectedItem = GUILayout.SelectionGrid(filteredCommandPreviewSelectedItem, toShow, 1); if (toShow[filteredCommandPreviewSelectedItem] != ELIPSIS) { commandSelectedByTextInput = filteredAttributes[filteredCommandPreviewSelectedItem].Key; } else { commandSelectedByTextInput = null; } GUILayout.EndHorizontal(); GUILayout.Space(5); } protected virtual void DrawEventHandlerGUI(Flowchart flowchart) { // Show available Event Handlers in a drop down list with type of current // event handler selected. Block block = target as Block; System.Type currentType = null; if (block._EventHandler != null) { currentType = block._EventHandler.GetType(); } string currentHandlerName = "<None>"; if (currentType != null) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(currentType); if (info != null) { currentHandlerName = info.EventHandlerName; } } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(new GUIContent("Execute On Event")); if (GUILayout.Button(new GUIContent(currentHandlerName), EditorStyles.popup)) { SetEventHandlerOperation noneOperation = new SetEventHandlerOperation(); noneOperation.block = block; noneOperation.eventHandlerType = null; GenericMenu eventHandlerMenu = new GenericMenu(); eventHandlerMenu.AddItem(new GUIContent("None"), false, OnSelectEventHandler, noneOperation); // Add event handlers with no category first foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info != null && info.Category.Length == 0) { SetEventHandlerOperation operation = new SetEventHandlerOperation(); operation.block = block; operation.eventHandlerType = type; eventHandlerMenu.AddItem(new GUIContent(info.EventHandlerName), false, OnSelectEventHandler, operation); } } // Add event handlers with a category afterwards foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info != null && info.Category.Length > 0) { SetEventHandlerOperation operation = new SetEventHandlerOperation(); operation.block = block; operation.eventHandlerType = type; string typeName = info.Category + "/" + info.EventHandlerName; eventHandlerMenu.AddItem(new GUIContent(typeName), false, OnSelectEventHandler, operation); } } eventHandlerMenu.ShowAsContext(); } EditorGUILayout.EndHorizontal(); if (block._EventHandler != null) { EventHandlerEditor eventHandlerEditor = Editor.CreateEditor(block._EventHandler) as EventHandlerEditor; if (eventHandlerEditor != null) { eventHandlerEditor.DrawInspectorGUI(); DestroyImmediate(eventHandlerEditor); } } } protected void OnSelectEventHandler(object obj) { SetEventHandlerOperation operation = obj as SetEventHandlerOperation; Block block = operation.block; System.Type selectedType = operation.eventHandlerType; if (block == null) { return; } Undo.RecordObject(block, "Set Event Handler"); if (block._EventHandler != null) { Undo.DestroyObjectImmediate(block._EventHandler); } if (selectedType != null) { EventHandler newHandler = Undo.AddComponent(block.gameObject, selectedType) as EventHandler; newHandler.ParentBlock = block; block._EventHandler = newHandler; } // Because this is an async call, we need to force prefab instances to record changes PrefabUtility.RecordPrefabInstancePropertyModifications(block); } public static void BlockField(SerializedProperty property, GUIContent label, GUIContent nullLabel, Flowchart flowchart) { if (flowchart == null) { return; } var block = property.objectReferenceValue as Block; // Build dictionary of child blocks List<GUIContent> blockNames = new List<GUIContent>(); int selectedIndex = 0; blockNames.Add(nullLabel); var blocks = flowchart.GetComponents<Block>(); for (int i = 0; i < blocks.Length; ++i) { blockNames.Add(new GUIContent(blocks[i].BlockName)); if (block == blocks[i]) { selectedIndex = i + 1; } } selectedIndex = EditorGUILayout.Popup(label, selectedIndex, blockNames.ToArray()); if (selectedIndex == 0) { block = null; // Option 'None' } else { block = blocks[selectedIndex - 1]; } property.objectReferenceValue = block; } public static Block BlockField(Rect position, GUIContent nullLabel, Flowchart flowchart, Block block) { if (flowchart == null) { return null; } Block result = block; // Build dictionary of child blocks List<GUIContent> blockNames = new List<GUIContent>(); int selectedIndex = 0; blockNames.Add(nullLabel); Block[] blocks = flowchart.GetComponents<Block>(); for (int i = 0; i < blocks.Length; ++i) { blockNames.Add(new GUIContent(blocks[i].name)); if (block == blocks[i]) { selectedIndex = i + 1; } } selectedIndex = EditorGUI.Popup(position, selectedIndex, blockNames.ToArray()); if (selectedIndex == 0) { result = null; // Option 'None' } else { result = blocks[selectedIndex - 1]; } return result; } // Compare delegate for sorting the list of command attributes protected static int CompareCommandAttributes(KeyValuePair<System.Type, CommandInfoAttribute> x, KeyValuePair<System.Type, CommandInfoAttribute> y) { int compare = (x.Value.Category.CompareTo(y.Value.Category)); if (compare == 0) { compare = (x.Value.CommandName.CompareTo(y.Value.CommandName)); } return compare; } [MenuItem("Tools/Fungus/Utilities/Export Reference Docs")] protected static void ExportReferenceDocs() { const string path = "./Docs"; ExportCommandInfo(path); ExportEventHandlerInfo(path); FlowchartWindow.ShowNotification("Exported Reference Documentation"); } protected static void ExportCommandInfo(string path) { // Dump command info List<System.Type> menuTypes = EditorExtensions.FindDerivedTypes(typeof(Command)).ToList(); List<KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = GetFilteredCommandInfoAttribute(menuTypes); filteredAttributes.Sort(CompareCommandAttributes); // Build list of command categories List<string> commandCategories = new List<string>(); foreach (var keyPair in filteredAttributes) { CommandInfoAttribute info = keyPair.Value; if (info.Category != "" && !commandCategories.Contains(info.Category)) { commandCategories.Add(info.Category); } } commandCategories.Sort(); // Output the commands in each category foreach (string category in commandCategories) { string markdown = "# " + category + " commands # {#" + category.ToLower() + "_commands}\n\n"; markdown += "[TOC]\n"; foreach (var keyPair in filteredAttributes) { CommandInfoAttribute info = keyPair.Value; if (info.Category == category || info.Category == "" && category == "Scripting") { markdown += "# " + info.CommandName + " # {#" + info.CommandName.Replace(" ", "") + "}\n"; markdown += info.HelpText + "\n\n"; markdown += "Defined in " + keyPair.Key.FullName + "\n"; markdown += GetPropertyInfo(keyPair.Key); } } string filePath = path + "/command_ref/" + category.ToLower() + "_commands.md"; Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, markdown); } } protected static void ExportEventHandlerInfo(string path) { List<System.Type> eventHandlerTypes = EditorExtensions.FindDerivedTypes(typeof(EventHandler)).ToList(); List<string> eventHandlerCategories = new List<string>(); eventHandlerCategories.Add("Core"); foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info != null && info.Category != "" && !eventHandlerCategories.Contains(info.Category)) { eventHandlerCategories.Add(info.Category); } } eventHandlerCategories.Sort(); // Output the commands in each category foreach (string category in eventHandlerCategories) { string markdown = "# " + category + " event handlers # {#" + category.ToLower() + "_events}\n\n"; markdown += "[TOC]\n"; foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info != null && info.Category == category || info.Category == "" && category == "Core") { markdown += "# " + info.EventHandlerName + " # {#" + info.EventHandlerName.Replace(" ", "") + "}\n"; markdown += info.HelpText + "\n\n"; markdown += "Defined in " + type.FullName + "\n"; markdown += GetPropertyInfo(type); } } string filePath = path + "/command_ref/" + category.ToLower() + "_events.md"; Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, markdown); } } protected static string GetPropertyInfo(System.Type type) { string markdown = ""; foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { TooltipAttribute attribute = (TooltipAttribute)Attribute.GetCustomAttribute(field, typeof(TooltipAttribute)); if (attribute == null) { continue; } // Change field name to how it's displayed in the inspector string propertyName = Regex.Replace(field.Name, "(\\B[A-Z])", " $1"); if (propertyName.Length > 1) { propertyName = propertyName.Substring(0, 1).ToUpper() + propertyName.Substring(1); } else { propertyName = propertyName.ToUpper(); } markdown += propertyName + " | " + field.FieldType + " | " + attribute.tooltip + "\n"; } if (markdown.Length > 0) { markdown = "\nProperty | Type | Description\n --- | --- | ---\n" + markdown + "\n"; } return markdown; } protected virtual void ShowCommandMenu() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); GenericMenu commandMenu = new GenericMenu(); // Build menu list var filteredAttributes = GetFilteredSupportedCommands(flowchart); foreach (var keyPair in filteredAttributes) { AddCommandOperation commandOperation = new AddCommandOperation(); commandOperation.commandType = keyPair.Key; GUIContent menuItem; if (keyPair.Value.Category == "") { menuItem = new GUIContent(keyPair.Value.CommandName); } else { menuItem = new GUIContent(keyPair.Value.Category + "/" + keyPair.Value.CommandName); } commandMenu.AddItem(menuItem, false, AddCommandCallback, commandOperation); } commandMenu.ShowAsContext(); } protected static List<KeyValuePair<System.Type, CommandInfoAttribute>> GetFilteredSupportedCommands(Flowchart flowchart) { List<KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = GetFilteredCommandInfoAttribute(commandTypes); filteredAttributes.Sort(CompareCommandAttributes); filteredAttributes = filteredAttributes.Where(x => flowchart.IsCommandSupported(x.Value)).ToList(); return filteredAttributes; } protected static List<KeyValuePair<System.Type, CommandInfoAttribute>> GetFilteredCommandInfoAttribute(List<System.Type> menuTypes) { Dictionary<string, KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = new Dictionary<string, KeyValuePair<System.Type, CommandInfoAttribute>>(); foreach (System.Type type in menuTypes) { object[] attributes = type.GetCustomAttributes(false); foreach (object obj in attributes) { CommandInfoAttribute infoAttr = obj as CommandInfoAttribute; if (infoAttr != null) { string dictionaryName = string.Format("{0}/{1}", infoAttr.Category, infoAttr.CommandName); int existingItemPriority = -1; if (filteredAttributes.ContainsKey(dictionaryName)) { existingItemPriority = filteredAttributes[dictionaryName].Value.Priority; } if (infoAttr.Priority > existingItemPriority) { KeyValuePair<System.Type, CommandInfoAttribute> keyValuePair = new KeyValuePair<System.Type, CommandInfoAttribute>(type, infoAttr); filteredAttributes[dictionaryName] = keyValuePair; } } } } return filteredAttributes.Values.ToList<KeyValuePair<System.Type, CommandInfoAttribute>>(); } //Used by GenericMenu Delegate protected void AddCommandCallback(object obj) { AddCommandOperation commandOperation = obj as AddCommandOperation; if (commandOperation != null) { AddCommandCallback(commandOperation.commandType); } } protected void AddCommandCallback(Type commandType) { var block = target as Block; if (block == null) { return; } var flowchart = (Flowchart)block.GetFlowchart(); // Use index of last selected command in list, or end of list if nothing selected. int index = -1; foreach (var command in flowchart.SelectedCommands) { if (command.CommandIndex + 1 > index) { index = command.CommandIndex + 1; } } if (index == -1) { index = block.CommandList.Count; } var newCommand = Undo.AddComponent(block.gameObject, commandType) as Command; block.GetFlowchart().AddSelectedCommand(newCommand); newCommand.ParentBlock = block; newCommand.ItemId = flowchart.NextItemId(); // Let command know it has just been added to the block newCommand.OnCommandAdded(block); Undo.RecordObject(block, "Set command type"); if (index < block.CommandList.Count - 1) { block.CommandList.Insert(index, newCommand); } else { block.CommandList.Add(newCommand); } // Because this is an async call, we need to force prefab instances to record changes PrefabUtility.RecordPrefabInstancePropertyModifications(block); flowchart.ClearSelectedCommands(); commandTextFieldContents = string.Empty; } public virtual void ShowContextMenu() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); if (flowchart == null) { return; } bool showCut = false; bool showCopy = false; bool showDelete = false; bool showPaste = false; bool showPlay = false; if (flowchart.SelectedCommands.Count > 0) { showCut = true; showCopy = true; showDelete = true; if (flowchart.SelectedCommands.Count == 1 && Application.isPlaying) { showPlay = true; } } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); if (commandCopyBuffer.HasCommands()) { showPaste = true; } GenericMenu commandMenu = new GenericMenu(); if (showCut) { commandMenu.AddItem(new GUIContent("Cut"), false, Cut); } else { commandMenu.AddDisabledItem(new GUIContent("Cut")); } if (showCopy) { commandMenu.AddItem(new GUIContent("Copy"), false, Copy); } else { commandMenu.AddDisabledItem(new GUIContent("Copy")); } if (showPaste) { commandMenu.AddItem(new GUIContent("Paste"), false, Paste); } else { commandMenu.AddDisabledItem(new GUIContent("Paste")); } if (showDelete) { commandMenu.AddItem(new GUIContent("Delete"), false, Delete); } else { commandMenu.AddDisabledItem(new GUIContent("Delete")); } if (showPlay) { commandMenu.AddItem(new GUIContent("Play from selected"), false, PlayCommand); commandMenu.AddItem(new GUIContent("Stop all and play"), false, StopAllPlayCommand); } commandMenu.AddSeparator(""); commandMenu.AddItem(new GUIContent("Select All"), false, SelectAll); commandMenu.AddItem(new GUIContent("Select None"), false, SelectNone); commandMenu.ShowAsContext(); } protected void SelectAll() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); if (flowchart == null || flowchart.SelectedBlock == null) { return; } flowchart.ClearSelectedCommands(); Undo.RecordObject(flowchart, "Select All"); foreach (Command command in flowchart.SelectedBlock.CommandList) { flowchart.AddSelectedCommand(command); } Repaint(); } protected void SelectNone() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); if (flowchart == null || flowchart.SelectedBlock == null) { return; } Undo.RecordObject(flowchart, "Select None"); flowchart.ClearSelectedCommands(); Repaint(); } protected void Cut() { Copy(); Delete(); } protected void Copy() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); if (flowchart == null || flowchart.SelectedBlock == null) { return; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); commandCopyBuffer.Clear(); // Scan through all commands in execution order to see if each needs to be copied foreach (Command command in flowchart.SelectedBlock.CommandList) { if (flowchart.SelectedCommands.Contains(command)) { var type = command.GetType(); Command newCommand = Undo.AddComponent(commandCopyBuffer.gameObject, type) as Command; var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); foreach (var field in fields) { // Copy all public fields bool copy = field.IsPublic; // Copy non-public fields that have the SerializeField attribute var attributes = field.GetCustomAttributes(typeof(SerializeField), true); if (attributes.Length > 0) { copy = true; } if (copy) { field.SetValue(newCommand, field.GetValue(command)); } } } } } protected void Paste() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); if (flowchart == null || flowchart.SelectedBlock == null) { return; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); // Find where to paste commands in block (either at end or after last selected command) int pasteIndex = flowchart.SelectedBlock.CommandList.Count; if (flowchart.SelectedCommands.Count > 0) { for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; ++i) { Command command = flowchart.SelectedBlock.CommandList[i]; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (command == selectedCommand) { pasteIndex = i + 1; } } } } foreach (Command command in commandCopyBuffer.GetCommands()) { // Using the Editor copy / paste functionality instead instead of reflection // because this does a deep copy of the command properties. if (ComponentUtility.CopyComponent(command)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { Command[] commands = flowchart.GetComponents<Command>(); Command pastedCommand = commands.Last<Command>(); if (pastedCommand != null) { pastedCommand.ItemId = flowchart.NextItemId(); flowchart.SelectedBlock.CommandList.Insert(pasteIndex++, pastedCommand); } } // This stops the user pasting the command manually into another game object. ComponentUtility.CopyComponent(flowchart.transform); } } // Because this is an async call, we need to force prefab instances to record changes PrefabUtility.RecordPrefabInstancePropertyModifications(block); Repaint(); } protected void Delete() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); if (flowchart == null || flowchart.SelectedBlock == null) { return; } int lastSelectedIndex = 0; for (int i = flowchart.SelectedBlock.CommandList.Count - 1; i >= 0; --i) { Command command = flowchart.SelectedBlock.CommandList[i]; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (command == selectedCommand) { command.OnCommandRemoved(block); // Order of destruction is important here for undo to work Undo.DestroyObjectImmediate(command); Undo.RecordObject((Block)flowchart.SelectedBlock, "Delete"); flowchart.SelectedBlock.CommandList.RemoveAt(i); lastSelectedIndex = i; break; } } } Undo.RecordObject(flowchart, "Delete"); flowchart.ClearSelectedCommands(); if (lastSelectedIndex < flowchart.SelectedBlock.CommandList.Count) { var nextCommand = flowchart.SelectedBlock.CommandList[lastSelectedIndex]; block.GetFlowchart().AddSelectedCommand(nextCommand); } Repaint(); } protected void PlayCommand() { var targetBlock = target as Block; var flowchart = (Flowchart)targetBlock.GetFlowchart(); Command command = flowchart.SelectedCommands[0]; if (targetBlock.IsExecuting()) { // The Block is already executing. // Tell the Block to stop, wait a little while so the executing command has a // chance to stop, and then start execution again from the new command. targetBlock.Stop(); flowchart.StartCoroutine(RunBlock(flowchart, targetBlock, command.CommandIndex, 0.2f)); } else { // Block isn't executing yet so can start it now. flowchart.ExecuteBlock(targetBlock, command.CommandIndex); } } protected void StopAllPlayCommand() { var targetBlock = target as Block; var flowchart = (Flowchart)targetBlock.GetFlowchart(); Command command = flowchart.SelectedCommands[0]; // Stop all active blocks then run the selected block. flowchart.StopAllBlocks(); flowchart.StartCoroutine(RunBlock(flowchart, targetBlock, command.CommandIndex, 0.2f)); } protected IEnumerator RunBlock(Flowchart flowchart, Block targetBlock, int commandIndex, float delay) { yield return new WaitForSeconds(delay); flowchart.ExecuteBlock(targetBlock, commandIndex); } protected void SelectPrevious() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); int firstSelectedIndex = flowchart.SelectedBlock.CommandList.Count; bool firstSelectedCommandFound = false; if (flowchart.SelectedCommands.Count > 0) { for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; i++) { Command commandInBlock = flowchart.SelectedBlock.CommandList[i]; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (commandInBlock == selectedCommand) { if (!firstSelectedCommandFound) { firstSelectedIndex = i; firstSelectedCommandFound = true; break; } } } if (firstSelectedCommandFound) { break; } } } if (firstSelectedIndex > 0) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(flowchart.SelectedBlock.CommandList[firstSelectedIndex - 1]); } Repaint(); } protected void SelectNext() { var block = target as Block; var flowchart = (Flowchart)block.GetFlowchart(); int lastSelectedIndex = -1; if (flowchart.SelectedCommands.Count > 0) { for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; i++) { Command commandInBlock = flowchart.SelectedBlock.CommandList[i]; foreach (Command selectedCommand in flowchart.SelectedCommands) { if (commandInBlock == selectedCommand) { lastSelectedIndex = i; } } } } if (lastSelectedIndex < flowchart.SelectedBlock.CommandList.Count - 1) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(flowchart.SelectedBlock.CommandList[lastSelectedIndex + 1]); } Repaint(); } } }
// // MpqLibDecompress.cs // // Authors: // Foole (fooleau@gmail.com) // // (C) 2006 Foole (fooleau@gmail.com) // Based on code from StormLib by Ladislav Zezula // // 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; namespace Foole.Mpq { enum CompressionType { Binary = 0, Ascii = 1 } /// <summary> /// A decompressor for PKLib implode/explode /// </summary> public class PKLibDecompress { private BitStream _bitstream; private CompressionType _compressionType; private int _dictSizeBits; // Dictionary size in bits private static byte[] sPosition1; private static byte[] sPosition2; private static readonly byte[] sLenBits = { 3, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7 }; private static readonly byte[] sLenCode = { 5, 3, 1, 6, 10, 2, 12, 20, 4, 24, 8, 48, 16, 32, 64, 0 }; private static readonly byte[] sExLenBits = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 }; private static readonly UInt16[] sLenBase = { 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x000A, 0x000E, 0x0016, 0x0026, 0x0046, 0x0086, 0x0106 }; private static readonly byte[] sDistBits = { 2, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; private static readonly byte[] sDistCode = { 0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A, 0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C, 0x74, 0x34, 0x54, 0x14, 0x64, 0x24, 0x44, 0x04, 0x78, 0x38, 0x58, 0x18, 0x68, 0x28, 0x48, 0x08, 0xF0, 0x70, 0xB0, 0x30, 0xD0, 0x50, 0x90, 0x10, 0xE0, 0x60, 0xA0, 0x20, 0xC0, 0x40, 0x80, 0x00 }; static PKLibDecompress() { sPosition1 = GenerateDecodeTable(sDistBits, sDistCode); sPosition2 = GenerateDecodeTable(sLenBits, sLenCode); } public PKLibDecompress(Stream input) { _bitstream = new BitStream(input); _compressionType = (CompressionType)input.ReadByte(); if (_compressionType != CompressionType.Binary && _compressionType != CompressionType.Ascii) throw new InvalidDataException("Invalid compression type: " + _compressionType); _dictSizeBits = input.ReadByte(); // This is 6 in test cases if(4 > _dictSizeBits || _dictSizeBits > 6) throw new InvalidDataException("Invalid dictionary size: " + _dictSizeBits); } public byte[] Explode(int expectedSize) { byte[] outputbuffer = new byte[expectedSize]; Stream outputstream = new MemoryStream(outputbuffer); int instruction; while((instruction = DecodeLit()) != -1) { if(instruction < 0x100) { outputstream.WriteByte((byte)instruction); } else { // If instruction is greater than 0x100, it means "Repeat n - 0xFE bytes" int copylength = instruction - 0xFE; int moveback = DecodeDist(copylength); if (moveback == 0) break; int source = (int)outputstream.Position - moveback; // We can't just outputstream.Write the section of the array // because it might overlap with what is currently being written while(copylength-- > 0) outputstream.WriteByte(outputbuffer[source++]); } } if (outputstream.Position == expectedSize) { return outputbuffer; } else { // Resize the array byte[] result = new byte[outputstream.Position]; Array.Copy(outputbuffer, 0, result, 0, result.Length); return result; } } // Return values: // 0x000 - 0x0FF : One byte from compressed file. // 0x100 - 0x305 : Copy previous block (0x100 = 1 byte) // -1 : EOF private int DecodeLit() { switch(_bitstream.ReadBits(1)) { case -1: return -1; case 1: // The next bits are position in buffers int pos = sPosition2[_bitstream.PeekByte()]; // Skip the bits we just used if (_bitstream.ReadBits(sLenBits[pos]) == -1) return -1; int nbits = sExLenBits[pos]; if(nbits != 0) { // TODO: Verify this conversion int val2 = _bitstream.ReadBits(nbits); if (val2 == -1 && (pos + val2 != 0x10e)) return -1; pos = sLenBase[pos] + val2; } return pos + 0x100; // Return number of bytes to repeat case 0: if (_compressionType == CompressionType.Binary) return _bitstream.ReadBits(8); // TODO: Text mode throw new NotImplementedException("Text mode is not yet implemented"); default: return 0; } } private int DecodeDist(int length) { if (_bitstream.EnsureBits(8) == false) return 0; int pos = sPosition1[_bitstream.PeekByte()]; byte skip = sDistBits[pos]; // Number of bits to skip // Skip the appropriate number of bits if (_bitstream.ReadBits(skip) == -1) return 0; if(length == 2) { if (_bitstream.EnsureBits(2) == false) return 0; pos = (pos << 2) | _bitstream.ReadBits(2); } else { if (_bitstream.EnsureBits(_dictSizeBits) == false) return 0; pos = ((pos << _dictSizeBits)) | _bitstream.ReadBits(_dictSizeBits); } return pos+1; } private static byte[] GenerateDecodeTable(byte[] bits, byte[] codes) { byte[] result = new byte[256]; for(int i = bits.Length - 1; i >= 0; i--) { UInt32 idx1 = codes[i]; UInt32 idx2 = (UInt32)1 << bits[i]; do { result[idx1] = (byte)i; idx1 += idx2; } while(idx1 < 0x100); } return result; } } }
//! \file ImageWEBP.cs //! \date Wed Apr 06 07:16:39 2016 //! \brief Google WEBP image format. // // Copyright (C) 2016 by morkt // // 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.ComponentModel; using System.ComponentModel.Composition; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.Google { internal class WebPMetaData : ImageMetaData { public WebPFeature Flags; public bool IsLossless; public bool HasAlpha; public long DataOffset; public int DataSize; public long AlphaOffset; public int AlphaSize; } [Flags] internal enum WebPFeature : uint { Fragments = 0x0001, Animation = 0x0002, Xmp = 0x0004, Exif = 0x0008, Alpha = 0x0010, Iccp = 0x0020, } [Export(typeof(ImageFormat))] public class WebPFormat : ImageFormat { public override string Tag { get { return "WEBP"; } } public override string Description { get { return "Google WebP image format"; } } public override uint Signature { get { return 0; } } public override ImageMetaData ReadMetaData (IBinaryStream stream) { if (0x46464952 != stream.Signature) // 'RIFF' return null; if (!stream.ReadHeader (12).AsciiEqual (8, "WEBP")) return null; var header = new byte[0x10]; bool found_vp8x = false; var info = new WebPMetaData { BPP = 32 }; int chunk_size; for (;;) { if (8 != stream.Read (header, 0, 8)) return null; chunk_size = LittleEndian.ToInt32 (header, 4); int aligned_size = (chunk_size + 1) & ~1; if (!found_vp8x && Binary.AsciiEqual (header, 0, "VP8X")) { found_vp8x = true; if (chunk_size < 10) return null; if (chunk_size > header.Length) header = new byte[chunk_size]; if (chunk_size != stream.Read (header, 0, chunk_size)) return null; info.Flags = (WebPFeature)LittleEndian.ToUInt32 (header, 0); info.Width = 1 + (uint)header.ToInt24 (4); info.Height = 1 + (uint)header.ToInt24 (7); if ((long)info.Width * info.Height >= (1L << 32)) return null; continue; } if (Binary.AsciiEqual (header, 0, "VP8 ") || Binary.AsciiEqual (header, 0, "VP8L")) { info.IsLossless = header[3] == 'L'; info.DataOffset = stream.Position; info.DataSize = aligned_size; if (!found_vp8x) { if (chunk_size < 10 || 10 != stream.Read (header, 0, 10)) return null; if (info.IsLossless) { if (header[0] != 0x2F || (header[4] >> 5) != 0) return null; uint wh = LittleEndian.ToUInt32 (header, 1); info.Width = (wh & 0x3FFFu) + 1; info.Height = ((wh >> 14) & 0x3FFFu) + 1; info.HasAlpha = 0 != (header[4] & 0x10); } else { if (header[3] != 0x9D || header[4] != 1 || header[5] != 0x2A) return null; if (0 != (header[0] & 1)) // not a keyframe return null; info.Width = LittleEndian.ToUInt16 (header, 6) & 0x3FFFu; info.Height = LittleEndian.ToUInt16 (header, 8) & 0x3FFFu; } } break; } if (Binary.AsciiEqual (header, 0, "ALPH")) { info.AlphaOffset = stream.Position; info.AlphaSize = chunk_size; } stream.Seek (aligned_size, SeekOrigin.Current); } if (0 == info.Width || 0 == info.Height) return null; return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { LibWebPLoader.Load(); var input = stream.ReadBytes ((int)stream.Length); var bitmap = new WriteableBitmap ((int)info.Width, (int)info.Height, ImageData.DefaultDpiX, ImageData.DefaultDpiY, PixelFormats.Bgra32, null); bitmap.Lock(); try { var output = bitmap.BackBuffer; int stride = bitmap.BackBufferStride; unsafe { fixed (byte* data = input) { var result = WebPDecodeBGRAInto ((IntPtr)data, (UIntPtr)input.Length, output, (UIntPtr)(stride * info.Height), stride); if (result != output) throw new InvalidFormatException ("WebP image decoder failed."); } } bitmap.AddDirtyRect (new Int32Rect (0, 0, (int)info.Width, (int)info.Height)); } finally { bitmap.Unlock(); } bitmap.Freeze(); return new ImageData (bitmap, info); } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("WebPFormat.Write not implemented"); } [DllImport ("libwebp.dll", EntryPoint = "WebPDecodeBGRAInto", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr WebPDecodeBGRAInto ([InAttribute()] IntPtr data, UIntPtr data_size, IntPtr output_buffer, UIntPtr output_buffer_size, int output_stride); } internal static class LibWebPLoader { [DllImport ("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern IntPtr LoadLibraryEx (string lpFileName, IntPtr hReservedNull, uint dwFlags); static bool loaded = false; const uint LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x00000100; const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800; public static void Load () { if (loaded) return; var folder = Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location); folder = Path.Combine (folder, (IntPtr.Size == 4) ? "x86" : "x64"); var fullPath = Path.Combine (folder, "libwebp.dll"); fullPath = Path.GetFullPath (fullPath); var handle = LoadLibraryEx (fullPath, IntPtr.Zero, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); if (IntPtr.Zero == handle) throw new Win32Exception (Marshal.GetLastWin32Error()); loaded = true; } } }
using System; using System.Collections.Generic; using AldursLab.PersistentObjects; using Newtonsoft.Json; namespace AldursLab.WurmAssistant3.Areas.Granger { [KernelBind(BindingHint.Singleton), PersistentObject("GrangerFeature_DefaultBreedingEvaluatorOptions")] public class DefaultBreedingEvaluatorOptionsData : PersistentObjectBase { [JsonProperty] bool ignoreNotInMood; [JsonProperty] bool ignorePregnant; [JsonProperty] bool ignoreRecentlyPregnant; [JsonProperty] bool ignoreOtherHerds; [JsonProperty] bool ignorePairedCreatures; [JsonProperty] bool ignoreSold; [JsonProperty] bool ignoreDead; [JsonProperty] bool ignoreFoals; [JsonProperty] bool ignoreYoung; [JsonProperty] bool ignoreAdolescent; [JsonProperty] bool ageIgnoreOnlyOtherCreatures; [JsonProperty] bool includePotentialValue; [JsonProperty] bool preferUniqueTraits; [JsonProperty] bool discardOnInbreeding; [JsonProperty] int numPotentialTraitsToConsider; [JsonProperty] bool excludeExactAgeEnabled; [JsonProperty] TimeSpan excludeExactAgeValue; [JsonProperty] bool discardOnAnyNegativeTraits; [JsonProperty] double potentialValuePositiveWeight; [JsonProperty] double potentialValueNegativeWeight; [JsonProperty] double uniqueTraitWeight; [JsonProperty] double negativeTraitPenaltyWeight; [JsonProperty] double inbreedingPenaltyWeight; [JsonProperty] readonly Dictionary<string, float> creatureColorValuesForEntityId; public DefaultBreedingEvaluatorOptionsData() { IgnoreNotInMood = true; IgnorePregnant = true; IgnoreRecentlyPregnant = true; IgnoreOtherHerds = false; IgnorePairedCreatures = false; IgnoreSold = false; IgnoreFoals = true; IgnoreYoung = true; IgnoreAdolescent = false; AgeIgnoreOnlyOtherCreatures = false; IncludePotentialValue = false; PotentialValuePositiveWeight = 1.0; PotentialValueNegativeWeight = 1.0; PreferUniqueTraits = false; UniqueTraitWeight = 3.0; DiscardOnAnyNegativeTraits = false; BadTraitWeight = 1.0; DiscardOnInbreeding = true; InbreedingPenaltyWeight = 1.0; creatureColorValuesForEntityId = new Dictionary<string, float>(); } public bool IgnoreNotInMood { get { return ignoreNotInMood; } set { ignoreNotInMood = value; FlagAsChanged(); } } public bool IgnorePregnant { get { return ignorePregnant; } set { ignorePregnant = value; FlagAsChanged(); } } public bool IgnoreRecentlyPregnant { get { return ignoreRecentlyPregnant; } set { ignoreRecentlyPregnant = value; FlagAsChanged(); } } public bool IgnoreOtherHerds { get { return ignoreOtherHerds; } set { ignoreOtherHerds = value; FlagAsChanged(); } } public bool IgnorePairedCreatures { get { return ignorePairedCreatures; } set { ignorePairedCreatures = value; FlagAsChanged(); } } public bool IgnoreSold { get { return ignoreSold; } set { ignoreSold = value; FlagAsChanged(); } } public bool IgnoreDead { get { return ignoreDead; } set { ignoreDead = value; FlagAsChanged(); } } public bool IgnoreFoals { get { return ignoreFoals; } set { ignoreFoals = value; FlagAsChanged(); } } public bool IgnoreYoung { get { return ignoreYoung; } set { ignoreYoung = value; FlagAsChanged(); } } public bool IgnoreAdolescent { get { return ignoreAdolescent; } set { ignoreAdolescent = value; FlagAsChanged(); } } public bool AgeIgnoreOnlyOtherCreatures { get { return ageIgnoreOnlyOtherCreatures; } set { ageIgnoreOnlyOtherCreatures = value; FlagAsChanged(); } } public bool IncludePotentialValue { get { return includePotentialValue; } set { includePotentialValue = value; FlagAsChanged(); } } public bool PreferUniqueTraits { get { return preferUniqueTraits; } set { preferUniqueTraits = value; FlagAsChanged(); } } public bool DiscardOnInbreeding { get { return discardOnInbreeding; } set { discardOnInbreeding = value; FlagAsChanged(); } } public int NumPotentialTraitsToConsider { get { return numPotentialTraitsToConsider; } set { numPotentialTraitsToConsider = value; FlagAsChanged(); } } public bool ExcludeExactAgeEnabled { get { return excludeExactAgeEnabled; } set { excludeExactAgeEnabled = value; FlagAsChanged(); } } public TimeSpan ExcludeExactAgeValue { get { return excludeExactAgeValue; } set { excludeExactAgeValue = value; FlagAsChanged(); } } public bool DiscardOnAnyNegativeTraits { get { return discardOnAnyNegativeTraits; } set { discardOnAnyNegativeTraits = value; FlagAsChanged(); } } public double PotentialValuePositiveWeight { get { return potentialValuePositiveWeight; } set { if (potentialValuePositiveWeight < 0) potentialValuePositiveWeight = 0; else potentialValuePositiveWeight = value; FlagAsChanged(); } } public double PotentialValueNegativeWeight { get { return potentialValueNegativeWeight; } set { if (potentialValueNegativeWeight < 0) potentialValueNegativeWeight = 0; else potentialValueNegativeWeight = value; FlagAsChanged(); } } public double UniqueTraitWeight { get { return uniqueTraitWeight; } set { if (uniqueTraitWeight < 0) uniqueTraitWeight = 0; else uniqueTraitWeight = value; FlagAsChanged(); } } public double BadTraitWeight { get { return negativeTraitPenaltyWeight; } set { if (negativeTraitPenaltyWeight < 0) negativeTraitPenaltyWeight = 0; else negativeTraitPenaltyWeight = value; FlagAsChanged(); } } public double InbreedingPenaltyWeight { get { return inbreedingPenaltyWeight; } set { if (inbreedingPenaltyWeight < 0) inbreedingPenaltyWeight = 0; else inbreedingPenaltyWeight = value; FlagAsChanged(); } } public Dictionary<string, float> CreatureColorValuesForEntityId => creatureColorValuesForEntityId; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Security.Cryptography.Asn1 { public partial class AsnReader { /// <summary> /// Reads the next value as a NamedBitList with tag UNIVERSAL 3, converting it to the /// [<see cref="FlagsAttribute"/>] enum specfied by <typeparamref name="TFlagsEnum"/>. /// </summary> /// <typeparam name="TFlagsEnum">Destination enum type</typeparam> /// <returns> /// the NamedBitList value converted to a <typeparamref name="TFlagsEnum"/>. /// </returns> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <typeparamref name="TFlagsEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <typeparamref name="TFlagsEnum"/> is not an enum type --OR-- /// <typeparamref name="TFlagsEnum"/> was not declared with <see cref="FlagsAttribute"/> /// </exception> /// <seealso cref="ReadNamedBitListValue{TFlagsEnum}(Asn1Tag)"/> public TFlagsEnum ReadNamedBitListValue<TFlagsEnum>() where TFlagsEnum : struct => ReadNamedBitListValue<TFlagsEnum>(Asn1Tag.PrimitiveBitString); /// <summary> /// Reads the next value as a NamedBitList with tag UNIVERSAL 3, converting it to the /// [<see cref="FlagsAttribute"/>] enum specfied by <typeparamref name="TFlagsEnum"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <typeparam name="TFlagsEnum">Destination enum type</typeparam> /// <returns> /// the NamedBitList value converted to a <typeparamref name="TFlagsEnum"/>. /// </returns> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <typeparamref name="TFlagsEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <typeparamref name="TFlagsEnum"/> is not an enum type --OR-- /// <typeparamref name="TFlagsEnum"/> was not declared with <see cref="FlagsAttribute"/> /// --OR-- /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <remarks> /// The bit alignment performed by this method is to interpret the most significant bit /// in the first byte of the value as the least significant bit in <typeparamref name="TFlagsEnum"/>, /// with bits increasing in value until the least significant bit of the first byte, proceeding /// with the most significant bit of the second byte, and so on. Under this scheme, the following /// ASN.1 type declaration and C# enumeration can be used together: /// /// <code> /// KeyUsage ::= BIT STRING { /// digitalSignature (0), /// nonRepudiation (1), /// keyEncipherment (2), /// dataEncipherment (3), /// keyAgreement (4), /// keyCertSign (5), /// cRLSign (6), /// encipherOnly (7), /// decipherOnly (8) } /// </code> /// /// <code> /// [Flags] /// enum KeyUsage /// { /// None = 0, /// DigitalSignature = 1 &lt;&lt; (0), /// NonRepudiation = 1 &lt;&lt; (1), /// KeyEncipherment = 1 &lt;&lt; (2), /// DataEncipherment = 1 &lt;&lt; (3), /// KeyAgreement = 1 &lt;&lt; (4), /// KeyCertSign = 1 &lt;&lt; (5), /// CrlSign = 1 &lt;&lt; (6), /// EncipherOnly = 1 &lt;&lt; (7), /// DecipherOnly = 1 &lt;&lt; (8), /// } /// </code> /// /// Note that while the example here uses the KeyUsage NamedBitList from /// <a href="https://tools.ietf.org/html/rfc3280#section-4.2.1.3">RFC 3280 (4.2.1.3)</a>, /// the example enum uses values thar are different from /// <see cref="System.Security.Cryptography.X509Certificates.X509KeyUsageFlags"/>. /// </remarks> public TFlagsEnum ReadNamedBitListValue<TFlagsEnum>(Asn1Tag expectedTag) where TFlagsEnum : struct { Type tFlagsEnum = typeof(TFlagsEnum); return (TFlagsEnum)Enum.ToObject(tFlagsEnum, ReadNamedBitListValue(expectedTag, tFlagsEnum)); } /// <summary> /// Reads the next value as a NamedBitList with tag UNIVERSAL 3, converting it to the /// [<see cref="FlagsAttribute"/>] enum specfied by <paramref name="tFlagsEnum"/>. /// </summary> /// <param name="tFlagsEnum">Type object representing the destination type.</param> /// <returns> /// the NamedBitList value converted to a <paramref name="tFlagsEnum"/>. /// </returns> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the encoded value is too big to fit in a <paramref name="tFlagsEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="tFlagsEnum"/> is not an enum type --OR-- /// <paramref name="tFlagsEnum"/> was not declared with <see cref="FlagsAttribute"/> /// </exception> /// <seealso cref="ReadNamedBitListValue{TFlagsEnum}(Asn1Tag)"/> public Enum ReadNamedBitListValue(Type tFlagsEnum) => ReadNamedBitListValue(Asn1Tag.PrimitiveBitString, tFlagsEnum); /// <summary> /// Reads the next value as a NamedBitList with tag UNIVERSAL 3, converting it to the /// [<see cref="FlagsAttribute"/>] enum specfied by <paramref name="tFlagsEnum"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="tFlagsEnum">Type object representing the destination type.</param> /// <returns> /// the NamedBitList value converted to a <paramref name="tFlagsEnum"/>. /// </returns> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR--- /// the encoded value is too big to fit in a <paramref name="tFlagsEnum"/> value /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="tFlagsEnum"/> is not an enum type --OR-- /// <paramref name="tFlagsEnum"/> was not declared with <see cref="FlagsAttribute"/> /// --OR-- /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <seealso cref="ReadNamedBitListValue{TFlagsEnum}(Asn1Tag)"/> public Enum ReadNamedBitListValue(Asn1Tag expectedTag, Type tFlagsEnum) { // This will throw an ArgumentException if TEnum isn't an enum type, // so we don't need to validate it. Type backingType = tFlagsEnum.GetEnumUnderlyingType(); if (!tFlagsEnum.IsDefined(typeof(FlagsAttribute), false)) { throw new ArgumentException( SR.Cryptography_Asn_NamedBitListRequiresFlagsEnum, nameof(tFlagsEnum)); } int sizeLimit = Marshal.SizeOf(backingType); Span<byte> stackSpan = stackalloc byte[sizeLimit]; ReadOnlyMemory<byte> saveData = _data; // If TryCopyBitStringBytes succeeds but anything else fails _data will have moved, // so if anything throws here just move _data back to what it was. try { if (!TryCopyBitStringBytes(expectedTag, stackSpan, out int unusedBitCount, out int bytesWritten)) { throw new CryptographicException( SR.Format(SR.Cryptography_Asn_NamedBitListValueTooBig, tFlagsEnum.Name)); } if (bytesWritten == 0) { // The mode isn't relevant, zero is always zero. return (Enum)Enum.ToObject(tFlagsEnum, 0); } ReadOnlySpan<byte> valueSpan = stackSpan.Slice(0, bytesWritten); // Now that the 0-bounds check is out of the way: // // T-REC-X.690-201508 sec 11.2.2 if (RuleSet == AsnEncodingRules.DER || RuleSet == AsnEncodingRules.CER) { byte lastByte = valueSpan[bytesWritten - 1]; // No unused bits tests 0x01, 1 is 0x02, 2 is 0x04, etc. // We already know that TryCopyBitStringBytes checked that the // declared unused bits were 0, this checks that the last "used" bit // isn't also zero. byte testBit = (byte)(1 << unusedBitCount); if ((lastByte & testBit) == 0) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } // Consider a NamedBitList defined as // // SomeList ::= BIT STRING { // a(0), b(1), c(2), d(3), e(4), f(5), g(6), h(7), i(8), j(9), k(10) // } // // The BIT STRING encoding of (a | j) is // unusedBitCount = 6, // contents: 0x80 0x40 (0b10000000_01000000) // // A the C# exposure of this structure we adhere to is // // [Flags] // enum SomeList // { // A = 1, // B = 1 << 1, // C = 1 << 2, // ... // } // // Which happens to be exactly backwards from how the bits are encoded, but the complexity // only needs to live here. return (Enum)Enum.ToObject(tFlagsEnum, InterpretNamedBitListReversed(valueSpan)); } catch { _data = saveData; throw; } } private static long InterpretNamedBitListReversed(ReadOnlySpan<byte> valueSpan) { Debug.Assert(valueSpan.Length <= sizeof(long)); long accum = 0; long currentBitValue = 1; for (int byteIdx = 0; byteIdx < valueSpan.Length; byteIdx++) { byte byteVal = valueSpan[byteIdx]; for (int bitIndex = 7; bitIndex >= 0; bitIndex--) { int test = 1 << bitIndex; if ((byteVal & test) != 0) { accum |= currentBitValue; } currentBitValue <<= 1; } } return accum; } } }
using System; using NUnit.Framework; using System.Drawing; using NUnit.Framework.Constraints; namespace OpenQA.Selenium { [TestFixture] public class JavascriptEnabledBrowserTest : DriverTestFixture { [Test] public void DocumentShouldReflectLatestTitle() { driver.Url = javascriptPage; Assert.AreEqual("Testing Javascript", driver.Title); driver.FindElement(By.LinkText("Change the page title!")).Click(); Assert.AreEqual("Changed", driver.Title); } [Test] public void DocumentShouldReflectLatestDom() { driver.Url = javascriptPage; String currentText = driver.FindElement(By.XPath("//div[@id='dynamo']")).Text; Assert.AreEqual("What's for dinner?", currentText); IWebElement element = driver.FindElement(By.LinkText("Update a div")); element.Click(); String newText = driver.FindElement(By.XPath("//div[@id='dynamo']")).Text; Assert.AreEqual("Fish and chips!", newText); } [Test] public void ShouldWaitForLoadsToCompleteAfterJavascriptCausesANewPageToLoad() { driver.Url = formsPage; driver.FindElement(By.Id("changeme")).Click(); WaitFor(() => { return driver.Title == "Page3"; }, "Browser title was not 'Page3'"); Assert.AreEqual("Page3", driver.Title); } [Test] public void ShouldBeAbleToFindElementAfterJavascriptCausesANewPageToLoad() { driver.Url = formsPage; driver.FindElement(By.Id("changeme")).Click(); WaitFor(() => { return driver.Title == "Page3"; }, "Browser title was not 'Page3'"); Assert.AreEqual("3", driver.FindElement(By.Id("pageNumber")).Text); } [Test] public void ShouldFireOnChangeEventWhenSettingAnElementsValue() { driver.Url = javascriptPage; driver.FindElement(By.Id("change")).SendKeys("foo"); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual("change", result); } [Test] public void ShouldBeAbleToSubmitFormsByCausingTheOnClickEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("jsSubmitButton")); element.Click(); WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); } [Test] public void ShouldBeAbleToClickOnSubmitButtons() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("submittingButton")); element.Click(); WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); } [Test] public void Issue80ClickShouldGenerateClickEvent() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("clickField")); Assert.AreEqual("Hello", element.GetAttribute("value")); element.Click(); Assert.AreEqual("Clicked", element.GetAttribute("value")); } [Test] public void ShouldBeAbleToSwitchToFocusedElement() { driver.Url = javascriptPage; driver.FindElement(By.Id("switchFocus")).Click(); IWebElement element = driver.SwitchTo().ActiveElement(); Assert.AreEqual("theworks", element.GetAttribute("id")); } [Test] public void IfNoElementHasFocusTheActiveElementIsTheBody() { driver.Url = simpleTestPage; IWebElement element = driver.SwitchTo().ActiveElement(); Assert.AreEqual("body", element.GetAttribute("name")); } [Test] [IgnoreBrowser(Browser.Firefox, "Window demands focus to work.")] public void ChangeEventIsFiredAppropriatelyWhenFocusIsLost() { driver.Url = javascriptPage; IWebElement input = driver.FindElement(By.Id("changeable")); input.SendKeys("test"); driver.FindElement(By.Id("clickField")).Click(); // move focus EqualConstraint firstConstraint = new EqualConstraint("focus change blur"); EqualConstraint secondConstraint = new EqualConstraint("focus change blur"); Assert.That(driver.FindElement(By.Id("result")).Text.Trim(), firstConstraint | secondConstraint); input.SendKeys(Keys.Backspace + "t"); driver.FindElement(By.Id("clickField")).Click(); // move focus firstConstraint = new EqualConstraint("focus change blur focus blur"); secondConstraint = new EqualConstraint("focus blur change focus blur"); EqualConstraint thirdConstraint = new EqualConstraint("focus blur change focus blur change"); EqualConstraint fourthConstraint = new EqualConstraint("focus change blur focus change blur"); //What Chrome does // I weep. Assert.That(driver.FindElement(By.Id("result")).Text.Trim(), firstConstraint | secondConstraint | thirdConstraint | fourthConstraint); } /** * If the click handler throws an exception, the firefox driver freezes. This is suboptimal. */ [Test] public void ShouldBeAbleToClickIfEvenSomethingHorribleHappens() { driver.Url = javascriptPage; driver.FindElement(By.Id("error")).Click(); // If we get this far then the test has passed, but let's do something basic to prove the point String text = driver.FindElement(By.Id("error")).Text; Assert.That(text, Is.Not.Null); } [Test] public void ShouldBeAbleToGetTheLocationOfAnElement() { driver.Url = javascriptPage; if (!(driver is IJavaScriptExecutor)) { return; } ((IJavaScriptExecutor)driver).ExecuteScript("window.focus();"); IWebElement element = driver.FindElement(By.Id("keyUp")); if (!(element is ILocatable)) { return; } Point point = ((ILocatable)element).LocationOnScreenOnceScrolledIntoView; Assert.That(point.X, Is.GreaterThan(1)); Assert.That(point.Y, Is.GreaterThanOrEqualTo(0)); } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] [IgnoreBrowser(Browser.Opera)] public void ShouldBeAbleToClickALinkThatClosesAWindow() { if (TestUtilities.IsMarionette(driver)) { Assert.Ignore("Marionette hangs the browser in this case"); } driver.Url = javascriptPage; String handle = driver.CurrentWindowHandle; driver.FindElement(By.Id("new_window")).Click(); WaitFor(() => { driver.SwitchTo().Window("close_me"); return true; }, "Could not find window with name 'close_me'"); driver.FindElement(By.Id("close")).Click(); driver.SwitchTo().Window(handle); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for NetworkInterfacesOperations. /// </summary> public static partial class NetworkInterfacesOperationsExtensions { /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static void Delete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { operations.DeleteAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets information about the specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> public static NetworkInterface Get(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, networkInterfaceName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> GetAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface operation. /// </param> public static NetworkInterface CreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> CreateOrUpdateAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NetworkInterface> ListAll(this INetworkInterfacesOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListAllAsync(this INetworkInterfacesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<NetworkInterface> List(this INetworkInterfacesOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListAsync(this INetworkInterfacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static EffectiveRouteListResult GetEffectiveRouteTable(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.GetEffectiveRouteTableAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EffectiveRouteListResult> GetEffectiveRouteTableAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static EffectiveNetworkSecurityGroupListResult ListEffectiveNetworkSecurityGroups(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.ListEffectiveNetworkSecurityGroupsAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EffectiveNetworkSecurityGroupListResult> ListEffectiveNetworkSecurityGroupsAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about all network interfaces in a virtual machine in a /// virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex) { return operations.ListVirtualMachineScaleSetVMNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex).GetAwaiter().GetResult(); } /// <summary> /// Gets information about all network interfaces in a virtual machine in a /// virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName) { return operations.ListVirtualMachineScaleSetNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName).GetAwaiter().GetResult(); } /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get the specified network interface in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> public static NetworkInterface GetVirtualMachineScaleSetNetworkInterface(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string)) { return operations.GetVirtualMachineScaleSetNetworkInterfaceAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand).GetAwaiter().GetResult(); } /// <summary> /// Get the specified network interface in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> GetVirtualMachineScaleSetNetworkInterfaceAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static void BeginDelete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { operations.BeginDeleteAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface operation. /// </param> public static NetworkInterface BeginCreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> BeginCreateOrUpdateAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static EffectiveRouteListResult BeginGetEffectiveRouteTable(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.BeginGetEffectiveRouteTableAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EffectiveRouteListResult> BeginGetEffectiveRouteTableAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static EffectiveNetworkSecurityGroupListResult BeginListEffectiveNetworkSecurityGroups(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { return operations.BeginListEffectiveNetworkSecurityGroupsAsync(resourceGroupName, networkInterfaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<EffectiveNetworkSecurityGroupListResult> BeginListEffectiveNetworkSecurityGroupsAsync(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListAllNext(this INetworkInterfacesOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListAllNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListNext(this INetworkInterfacesOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about all network interfaces in a virtual machine in a /// virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink) { return operations.ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets information about all network interfaces in a virtual machine in a /// virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink) { return operations.ListVirtualMachineScaleSetNetworkInterfacesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesNextAsync(this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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; namespace System.Collections.Immutable.Test { #if !NET45PLUS extern alias rax; using rax::System.Collections.Generic; #endif public abstract class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase { [Fact] public void Add() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add(new KeyValuePair<string, int>("six", 6)); Assert.Equal(5, builder["five"]); Assert.Equal(6, builder["six"]); Assert.False(builder.ContainsKey("four")); } /// <summary> /// Verifies that "adding" an entry to the dictionary that already exists /// with exactly the same key and value will *not* throw an exception. /// </summary> /// <remarks> /// The BCL Dictionary type would throw in this circumstance. /// But in an immutable world, not only do we not care so much since the result is the same. /// </remarks> [Fact] public void AddExactDuplicate() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add("five", 5); Assert.Equal(1, builder.Count); } [Fact] public void AddExistingKeyWithDifferentValue() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); Assert.Throws<ArgumentException>(() => builder.Add("five", 6)); } [Fact] public void Indexer() { var builder = this.GetBuilder<string, int>(); // Set and set again. builder["five"] = 5; Assert.Equal(5, builder["five"]); builder["five"] = 5; Assert.Equal(5, builder["five"]); // Set to a new value. builder["five"] = 50; Assert.Equal(50, builder["five"]); // Retrieve an invalid value. Assert.Throws<KeyNotFoundException>(() => builder["foo"]); } [Fact] public void ContainsPair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5))); } [Fact] public void RemovePair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5))); Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1))); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void RemoveKey() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); builder.Remove("five"); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void CopyTo() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); var array = new KeyValuePair<string, int>[2]; // intentionally larger than source. builder.CopyTo(array, 1); Assert.Equal(new KeyValuePair<string, int>(), array[0]); Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]); Assert.Throws<ArgumentNullException>(() => builder.CopyTo(null, 0)); } [Fact] public void IsReadOnly() { var builder = this.GetBuilder<string, int>(); Assert.False(builder.IsReadOnly); } [Fact] public void Keys() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys); CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray()); } [Fact] public void Values() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values); CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray()); } [Fact] public void TryGetValue() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); int value; Assert.True(builder.TryGetValue("five", out value) && value == 5); Assert.True(builder.TryGetValue("six", out value) && value == 6); Assert.False(builder.TryGetValue("four", out value)); Assert.Equal(0, value); } [Fact] public void TryGetKey() { var builder = Empty<int>(StringComparer.OrdinalIgnoreCase) .Add("a", 1).ToBuilder(); string actualKey; Assert.True(TryGetKeyHelper(builder, "a", out actualKey)); Assert.Equal("a", actualKey); Assert.True(TryGetKeyHelper(builder, "A", out actualKey)); Assert.Equal("a", actualKey); Assert.False(TryGetKeyHelper(builder, "b", out actualKey)); Assert.Equal("b", actualKey); } [Fact] public void EnumerateTest() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); using (var enumerator = builder.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } var manualEnum = builder.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } [Fact] public void IDictionaryMembers() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); Assert.True(dictionary.Contains("a")); Assert.Equal(1, dictionary["a"]); Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray()); dictionary["a"] = 2; Assert.Equal(2, dictionary["a"]); dictionary.Remove("a"); Assert.False(dictionary.Contains("a")); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); } [Fact] public void IDictionaryEnumerator() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void ICollectionMembers() { var builder = this.GetBuilder<string, int>(); var collection = (ICollection)builder; collection.CopyTo(new object[0], 0); builder.Add("b", 2); Assert.True(builder.ContainsKey("b")); var array = new object[builder.Count + 1]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new object[] { null, new DictionaryEntry("b", 2), }, array); Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey); /// <summary> /// Gets the Builder for a given dictionary instance. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The builder.</returns> protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis = null); /// <summary> /// Gets an empty immutable dictionary. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The immutable dictionary.</returns> protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>(); protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); } }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.Geometry; using System.IO; namespace gView.Framework.Geometry.SpatialRefTranslation { public class WktCoordinateSystemReader { public static object Create(string wkt) { object returnObject = null; bool includeAuthority = (wkt.ToLower().IndexOf("authority") != -1); StringReader reader = new StringReader(wkt); WktStreamTokenizer tokenizer = new WktStreamTokenizer(reader); tokenizer.NextToken(); string objectName = tokenizer.GetStringValue(); switch (objectName) { case "UNIT": Unit unit = ReadUnit(tokenizer, includeAuthority); returnObject = unit; break; case "VERT_DATUM": VerticalDatum verticalDatum = ReadVerticalDatum(tokenizer, includeAuthority); returnObject = verticalDatum; break; case "SPHEROID": Ellipsoid ellipsoid = ReadEllipsoid(tokenizer, includeAuthority); returnObject = ellipsoid; break; case "TOWGS84": WGS84ConversionInfo wgsInfo = ReadWGS84ConversionInfo(tokenizer, includeAuthority); returnObject = wgsInfo; break; case "DATUM": HorizontalDatum horizontalDatum = ReadHorizontalDatum(tokenizer, includeAuthority); returnObject = horizontalDatum; break; case "PRIMEM": PrimeMeridian primeMeridian = ReadPrimeMeridian(tokenizer, includeAuthority); returnObject = primeMeridian; break; case "VERT_CS": VerticalCoordinateSystem verticalCS = ReadVerticalCoordinateSystem(tokenizer, includeAuthority); returnObject = verticalCS; break; case "GEOGCS": GeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer, includeAuthority); returnObject = geographicCS; break; case "PROJCS": ProjectedCoordinateSystem projectedCS = ReadProjectedCoordinateSystem(tokenizer, includeAuthority); returnObject = projectedCS; break; case "COMPD_CS": CompoundCoordinateSystem compoundCS = ReadCompoundCoordinateSystem(tokenizer, includeAuthority); returnObject = compoundCS; break; case "GEOCCS": case "FITTED_CS": case "LOCAL_CS": throw new NotSupportedException(String.Format("{0} is not implemented.", objectName)); default: throw new ParseException(String.Format("'{0'} is not recongnized.", objectName)); } reader.Close(); return returnObject; } private static Unit ReadUnit(WktStreamTokenizer tokenizer, bool includeAuthority) { //UNIT["degree",0.01745329251994433,AUTHORITY["EPSG","9102"]] Unit unit = null; tokenizer.ReadToken("["); string unitName = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.NextToken(); double unitsPerUnit = tokenizer.GetNumericValue(); string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } tokenizer.ReadToken("]"); switch (unitName.ToUpper()) { // take into account the different spellings of the word meter/metre. case "METER": case "METRE": case "KILOMETRE": case "KILOMETER": unit = new LinearUnit(unitsPerUnit, String.Empty, authority, authorityCode, unitName, String.Empty, String.Empty); break; case "DEGREE": case "RADIAN": case "GRAD": unit = new AngularUnit(unitsPerUnit, String.Empty, authority, authorityCode, unitName, String.Empty, String.Empty); break; //case "CLARKE'S LINK": //case "GOLD COAST FOOT": //case "US SURVEY FOOT": //case "CLARKE'S FOOT": //case "FOOT": //case "LINK": //case "INDIAN YARD": //case "GERMAN LEGAL METRE": //case "BRITISH CHAIN (SEARS 1922)": //case "BRITISH FOOT (SEARS 1922)": //case "BRITISH CHAIN (SEARS 1922 TRUNCATED)": //case "BRITISH CHAIN (BENOIT 1922 TRUNCATED)": // unit = new LinearUnit(unitsPerUnit, String.Empty, authority, authorityCode, unitName, String.Empty, String.Empty); // break; default: string u = unitName.ToUpper(); if (u.Contains("YARD") || u.Contains("CHAIN") || u.Contains("FOOT") || u.Contains("LINK") || u.Contains("METRE") || u.Contains("METER") || u.Contains("KILOMETER") || u.Contains("KILOMETRE")) { unit = new LinearUnit(unitsPerUnit, String.Empty, authority, authorityCode, unitName, String.Empty, String.Empty); } else { throw new NotImplementedException(String.Format("{0} is not recognized a unit of measure.", unitName)); } break; } return unit; } private static CoordinateSystem ReadCoordinateSystem(string coordinateSystem, WktStreamTokenizer tokenizer, bool includeAuthority) { CoordinateSystem returnCS = null; switch (coordinateSystem) { case "VERT_CS": VerticalCoordinateSystem verticalCS = ReadVerticalCoordinateSystem(tokenizer, includeAuthority); returnCS = verticalCS; break; case "GEOGCS": GeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer, includeAuthority); returnCS = geographicCS; break; case "PROJCS": ProjectedCoordinateSystem projectedCS = ReadProjectedCoordinateSystem(tokenizer, includeAuthority); returnCS = projectedCS; break; case "COMPD_CS": CompoundCoordinateSystem compoundCS = ReadCompoundCoordinateSystem(tokenizer, includeAuthority); returnCS = compoundCS; break; case "GEOCCS": case "FITTED_CS": case "LOCAL_CS": throw new InvalidOperationException(String.Format("{0} coordinate system is not recongized.", coordinateSystem)); } return returnCS; } private static WGS84ConversionInfo ReadWGS84ConversionInfo(WktStreamTokenizer tokenizer, bool includeAuthority) { //TOWGS84[0,0,0,0,0,0,0] tokenizer.ReadToken("["); WGS84ConversionInfo info = new WGS84ConversionInfo(); tokenizer.NextToken(); info.Dx = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); info.Dy = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); info.Dz = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); info.Ex = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); info.Ey = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); info.Ez = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); info.Ppm = tokenizer.GetNumericValue(); tokenizer.ReadToken("]"); info.IsInUse = true; return info; } private static CompoundCoordinateSystem ReadCompoundCoordinateSystem(WktStreamTokenizer tokenizer, bool includeAuthority) { //COMPD_CS[ //"OSGB36 / British National Grid + ODN", //PROJCS[] //VERT_CS[] //AUTHORITY["EPSG","7405"] //] //TODO add a ReadCoordinateSystem - that determines the correct coordinate system to //read. Right now this hard coded for a projected and a vertical coord sys - so the UK //national grid works. tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.NextToken(); string headCSCode = tokenizer.GetStringValue(); CoordinateSystem headCS = ReadCoordinateSystem(headCSCode, tokenizer, includeAuthority); tokenizer.ReadToken(","); tokenizer.NextToken(); string tailCSCode = tokenizer.GetStringValue(); CoordinateSystem tailCS = ReadCoordinateSystem(tailCSCode, tokenizer, includeAuthority); string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } tokenizer.ReadToken("]"); CompoundCoordinateSystem compoundCS = new CompoundCoordinateSystem(headCS, tailCS, String.Empty, authority, authorityCode, name, String.Empty, String.Empty); return compoundCS; } private static Ellipsoid ReadEllipsoid(WktStreamTokenizer tokenizer, bool includeAuthority) { //SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.NextToken(); double majorAxis = tokenizer.GetNumericValue(); tokenizer.ReadToken(","); tokenizer.NextToken(); double e = tokenizer.GetNumericValue(); string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } tokenizer.ReadToken("]"); Ellipsoid ellipsoid = new Ellipsoid(majorAxis, 0.0, e, true, LinearUnit.Meters, String.Empty, authority, authorityCode, name, String.Empty, String.Empty); return ellipsoid; } private static Projection ReadProjection(WktStreamTokenizer tokenizer, bool includeAuthority) { //tokenizer.NextToken();// PROJECTION tokenizer.ReadToken("PROJECTION"); tokenizer.ReadToken("[");//[ string projectionName = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken("]");//] tokenizer.ReadToken(",");//, tokenizer.ReadToken("PARAMETER"); ParameterList paramList = new ParameterList(); while (tokenizer.GetStringValue() == "PARAMETER") { tokenizer.ReadToken("["); string paramName = tokenizer.ReadDoubleQuotedWord(); //added by monoGIS team: parameters names may be capitalized, but the code works only with lower-case! paramName = paramName.ToLower(); tokenizer.ReadToken(","); tokenizer.NextToken(); double paramValue = tokenizer.GetNumericValue(); tokenizer.ReadToken("]"); paramList.Add(paramName, paramValue); if (!tokenizer.TryReadToken(",")) break; if (!tokenizer.TryReadToken("PARAMETER")) break; } ProjectionParameter[] paramArray = new ProjectionParameter[paramList.Count]; int i = 0; foreach (string key in paramList.Keys) { ProjectionParameter param = new ProjectionParameter(); param.Name = key; param.Value = (double)paramList[key]; paramArray[i] = param; i++; } string authority = String.Empty; string authorityCode = String.Empty; Projection projection = new Projection(projectionName, paramArray, String.Empty, String.Empty, authority, authorityCode); return projection; } private static ProjectedCoordinateSystem ReadProjectedCoordinateSystem(WktStreamTokenizer tokenizer, bool includeAuthority) { //PROJCS[ // "OSGB 1936 / British National Grid", // GEOGCS[ // "OSGB 1936", // DATUM[...] // PRIMEM[...] // AXIS["Geodetic latitude",NORTH] // AXIS["Geodetic longitude",EAST] // AUTHORITY["EPSG","4277"] // ], // PROJECTION["Transverse Mercator"], // PARAMETER["latitude_of_natural_origin",49], // PARAMETER["longitude_of_natural_origin",-2], // PARAMETER["scale_factor_at_natural_origin",0.999601272], // PARAMETER["false_easting",400000], // PARAMETER["false_northing",-100000], // AXIS["Easting",EAST], // AXIS["Northing",NORTH], // AUTHORITY["EPSG","27700"] //] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.ReadToken("GEOGCS"); GeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer, includeAuthority); tokenizer.ReadToken(","); Projection projection = ReadProjection(tokenizer, includeAuthority); tokenizer.ReadToken("UNIT"); Unit unit = ReadUnit(tokenizer, includeAuthority); AxisInfo axisInfo1 = null, axisInfo2 = null; if (tokenizer.TryReadToken(",")) { if (tokenizer.TryReadToken("AXIS")) axisInfo1 = ReadAxisInfo(tokenizer); if (tokenizer.TryReadToken(",")) if (tokenizer.TryReadToken("AXIS")) axisInfo2 = ReadAxisInfo(tokenizer); } string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } tokenizer.ReadToken("]"); int axisInfoDim = 0; if (axisInfo1 != null) axisInfoDim = 1; if (axisInfo2 != null) axisInfoDim = 2; AxisInfo[] axisArray = new AxisInfo[axisInfoDim]; if (axisInfo1 != null) axisArray[0] = axisInfo1; if (axisInfo2 != null) axisArray[1] = axisInfo2; ProjectedCoordinateSystem projectedCS = new ProjectedCoordinateSystem(geographicCS.HorizontalDatum, axisArray, geographicCS, unit as LinearUnit, projection, String.Empty, authority, authorityCode, name, String.Empty, String.Empty); return projectedCS; } internal static GeographicCoordinateSystem ReadGeographicCoordinateSystem(WktStreamTokenizer tokenizer, bool includeAuthority) { //GEOGCS["OSGB 1936", //DATUM["OSGB 1936",SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6277"]] //PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]] //UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]] //AXIS["Geodetic latitude","NORTH"] //AXIS["Geodetic longitude","EAST"] //AUTHORITY["EPSG","4277"] //] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.ReadToken("DATUM"); HorizontalDatum horizontalDatum = ReadHorizontalDatum(tokenizer, includeAuthority); tokenizer.ReadToken(","); tokenizer.ReadToken("PRIMEM"); PrimeMeridian primeMeridian = ReadPrimeMeridian(tokenizer, includeAuthority); tokenizer.ReadToken(","); tokenizer.ReadToken("UNIT"); Unit angularUnit = ReadUnit(tokenizer, includeAuthority); AxisInfo axisInfo1 = null, axisInfo2 = null; if (tokenizer.TryReadToken(",")) { if (tokenizer.TryReadToken("AXIS")) axisInfo1 = ReadAxisInfo(tokenizer); if(tokenizer.TryReadToken(",")) if (tokenizer.TryReadToken("AXIS")) axisInfo2 = ReadAxisInfo(tokenizer); } string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } tokenizer.ReadToken("]"); GeographicCoordinateSystem geographicCS = new GeographicCoordinateSystem(angularUnit as AngularUnit, horizontalDatum, primeMeridian, axisInfo1, axisInfo2, String.Empty, authority, authorityCode, name, String.Empty, String.Empty); return geographicCS; } private static AxisInfo ReadAxisInfo(WktStreamTokenizer tokenizer) { //AXIS["Geodetic longitude","EAST"] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); string orientationString = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken("]"); AxisOrientation orientation = (AxisOrientation)Enum.Parse(typeof(AxisOrientation), orientationString, true); AxisInfo axis = new AxisInfo(name, orientation); return axis; } private static HorizontalDatum ReadHorizontalDatum(WktStreamTokenizer tokenizer, bool includeAuthority) { //DATUM["OSGB 1936", // SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]], // TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6277"]] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.ReadToken("SPHEROID"); Ellipsoid ellipsoid = ReadEllipsoid(tokenizer, includeAuthority); string authority = String.Empty; string authorityCode = String.Empty; WGS84ConversionInfo wgsInfo = new WGS84ConversionInfo(); wgsInfo.IsInUse = false; if (tokenizer.TryReadToken(",")) { if (tokenizer.TryReadToken("TOWGS84")) { wgsInfo = ReadWGS84ConversionInfo(tokenizer, includeAuthority); } if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } } tokenizer.ReadToken("]"); // make an assumption about the datum type. DatumType datumType = DatumType.IHD_Geocentric; HorizontalDatum horizontalDatum = new HorizontalDatum(name, datumType, ellipsoid, wgsInfo, String.Empty, authority, authorityCode, String.Empty, String.Empty); return horizontalDatum; } private static PrimeMeridian ReadPrimeMeridian(WktStreamTokenizer tokenizer, bool includeAuthority) { //PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.NextToken(); double longitude = tokenizer.GetNumericValue(); string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } // make an assumption about the Angular units - degrees. PrimeMeridian primeMeridian = new PrimeMeridian(name, new AngularUnit(180 / Math.PI), longitude, String.Empty, authority, authorityCode, String.Empty, String.Empty); tokenizer.ReadToken("]"); return primeMeridian; } private static VerticalCoordinateSystem ReadVerticalCoordinateSystem(WktStreamTokenizer tokenizer, bool includeAuthority) { //VERT_CS["Newlyn", //VERT_DATUM["Ordnance Datum Newlyn",2005,AUTHORITY["EPSG","5101"]] //UNIT["metre",1,AUTHORITY["EPSG","9001"]] //AUTHORITY["EPSG","5701"] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.ReadToken("VERT_DATUM"); VerticalDatum verticalDatum = ReadVerticalDatum(tokenizer, includeAuthority); tokenizer.ReadToken("UNIT"); Unit unit = ReadUnit(tokenizer, includeAuthority); string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) tokenizer.ReadAuthority(ref authority, ref authorityCode); tokenizer.ReadToken("]"); VerticalCoordinateSystem verticalCS = new VerticalCoordinateSystem(name, verticalDatum, String.Empty, authority, authorityCode, String.Empty, String.Empty); return verticalCS; } private static VerticalDatum ReadVerticalDatum(WktStreamTokenizer tokenizer, bool includeAuthority) { //VERT_DATUM["Ordnance Datum Newlyn",2005,AUTHORITY["5101","EPSG"]] tokenizer.ReadToken("["); string datumName = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.NextToken(); string datumTypeNumber = tokenizer.GetStringValue(); string authority = String.Empty; string authorityCode = String.Empty; if (includeAuthority) { tokenizer.ReadToken(","); tokenizer.ReadAuthority(ref authority, ref authorityCode); } DatumType datumType = (DatumType)Enum.Parse(typeof(DatumType), datumTypeNumber); VerticalDatum verticalDatum = new VerticalDatum(datumType, String.Empty, authorityCode, authority, datumName, String.Empty, String.Empty); tokenizer.ReadToken("]"); return verticalDatum; } } public class ESRIGeotransWktCoordinateReader { public static object Create(string wkt) { object returnObject = null; bool includeAuthority = (wkt.ToLower().IndexOf("authority") != -1); StringReader reader = new StringReader(wkt); WktStreamTokenizer tokenizer = new WktStreamTokenizer(reader); tokenizer.NextToken(); string objectName = tokenizer.GetStringValue(); switch (objectName) { case "GEOGTRAN": Geotransformation geotrans = ReadGeotransformation(tokenizer, includeAuthority); returnObject = geotrans; break; default: throw new ParseException(String.Format("'{0'} is not recongnized.", objectName)); } reader.Close(); return returnObject; } private static Geotransformation ReadGeotransformation(WktStreamTokenizer tokenizer, bool includeAuthority) { // GEOGTRAN[ // "MGI_To_WGS_1984_2", // GEOGCS[ // "GCS_MGI", // DATUM["D_MGI",SPHEROID["Bessel_1841",6377397.155,299.1528128]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]], // METHOD["Position_Vector"], // PARAMETER["X_Axis_Translation",577.326], // PARAMETER["Y_Axis_Translation",90.129], // PARAMETER["Z_Axis_Translation",463.919], // PARAMETER["X_Axis_Rotation",5.1365988], // PARAMETER["Y_Axis_Rotation",1.4742], // PARAMETER["Z_Axis_Rotation",5.2970436], // PARAMETER["Scale_Difference",2.4232] //] tokenizer.ReadToken("["); string name = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken(","); tokenizer.ReadToken("GEOGCS"); GeographicCoordinateSystem geographicCS1 = WktCoordinateSystemReader.ReadGeographicCoordinateSystem(tokenizer, includeAuthority); tokenizer.ReadToken(","); tokenizer.ReadToken("GEOGCS"); GeographicCoordinateSystem geographicCS2 = WktCoordinateSystemReader.ReadGeographicCoordinateSystem(tokenizer, includeAuthority); tokenizer.ReadToken(","); string method = String.Empty; ParameterList paramList = new ParameterList(); if (tokenizer.TryReadToken("METHOD")) { tokenizer.ReadToken("["); method = tokenizer.ReadDoubleQuotedWord(); tokenizer.ReadToken("]"); } if (tokenizer.TryReadToken(",")) { tokenizer.ReadToken("PARAMETER"); while (tokenizer.GetStringValue() == "PARAMETER") { tokenizer.ReadToken("["); string paramName = tokenizer.ReadDoubleQuotedWord(); paramName = paramName.ToLower(); tokenizer.ReadToken(","); tokenizer.NextToken(); double paramValue = tokenizer.GetNumericValue(); tokenizer.ReadToken("]"); paramList.Add(paramName, paramValue); if (!tokenizer.TryReadToken(",")) break; if (!tokenizer.TryReadToken("PARAMETER")) break; } } return new Geotransformation(name, method, geographicCS1, geographicCS2, paramList, "", "", "", ""); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //permutations for (((class_s.a+class_s.b)+class_s.c)+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+(class_s.b+class_s.c)) //(class_s.b+(class_s.a+class_s.c)) //(class_s.b+class_s.c) //(class_s.a+class_s.c) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //((class_s.a+class_s.b)+(class_s.c+class_s.d)) //(class_s.c+((class_s.a+class_s.b)+class_s.d)) //(class_s.c+class_s.d) //((class_s.a+class_s.b)+class_s.d) //(class_s.a+(class_s.b+class_s.d)) //(class_s.b+(class_s.a+class_s.d)) //(class_s.b+class_s.d) //(class_s.a+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; class_s s = new class_s(); class_s.a = return_int(false, 32); class_s.b = return_int(false, 77); class_s.c = return_int(false, 7); class_s.d = return_int(false, 33); int v = 0; #if LOOP do { #endif #if TRY try { #endif #if LOOP do { for (int i = 0; i < 10; i++) { #endif v = (((class_s.a + class_s.b) + class_s.c) + class_s.d); if (v != 149) { Console.WriteLine("test0: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); if (v != 149) { Console.WriteLine("test1: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((class_s.a + class_s.b) + class_s.c); if (v != 116) { Console.WriteLine("test2: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.c + (class_s.a + class_s.b)); if (v != 116) { Console.WriteLine("test3: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.a + class_s.b); if (v != 109) { Console.WriteLine("test4: for (class_s.a+class_s.b) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.b + class_s.a); if (v != 109) { Console.WriteLine("test5: for (class_s.b+class_s.a) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.a + class_s.b); if (v != 109) { Console.WriteLine("test6: for (class_s.a+class_s.b) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.b + class_s.a); if (v != 109) { Console.WriteLine("test7: for (class_s.b+class_s.a) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.a + (class_s.b + class_s.c)); if (v != 116) { Console.WriteLine("test8: for (class_s.a+(class_s.b+class_s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.b + (class_s.a + class_s.c)); if (v != 116) { Console.WriteLine("test9: for (class_s.b+(class_s.a+class_s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.b + class_s.c); if (v != 84) { Console.WriteLine("test10: for (class_s.b+class_s.c) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.a + class_s.c); if (v != 39) { Console.WriteLine("test11: for (class_s.a+class_s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((class_s.a + class_s.b) + class_s.c); if (v != 116) { Console.WriteLine("test12: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.c + (class_s.a + class_s.b)); if (v != 116) { Console.WriteLine("test13: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((class_s.a + class_s.b) + (class_s.c + class_s.d)); if (v != 149) { Console.WriteLine("test14: for ((class_s.a+class_s.b)+(class_s.c+class_s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.c + ((class_s.a + class_s.b) + class_s.d)); if (v != 149) { Console.WriteLine("test15: for (class_s.c+((class_s.a+class_s.b)+class_s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.c + class_s.d); if (v != 40) { Console.WriteLine("test16: for (class_s.c+class_s.d) failed actual value {0} ", v); ret = ret + 1; } v = ((class_s.a + class_s.b) + class_s.d); if (v != 142) { Console.WriteLine("test17: for ((class_s.a+class_s.b)+class_s.d) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.a + (class_s.b + class_s.d)); if (v != 142) { Console.WriteLine("test18: for (class_s.a+(class_s.b+class_s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.b + (class_s.a + class_s.d)); if (v != 142) { Console.WriteLine("test19: for (class_s.b+(class_s.a+class_s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.b + class_s.d); if (v != 110) { Console.WriteLine("test20: for (class_s.b+class_s.d) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.a + class_s.d); if (v != 65) { Console.WriteLine("test21: for (class_s.a+class_s.d) failed actual value {0} ", v); ret = ret + 1; } v = (((class_s.a + class_s.b) + class_s.c) + class_s.d); if (v != 149) { Console.WriteLine("test22: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v); ret = ret + 1; } v = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); if (v != 149) { Console.WriteLine("test23: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v); ret = ret + 1; } class_s.d = return_int(false, 33); #if LOOP } } while (v == 0); #endif #if TRY } finally { } #endif #if LOOP } while (v== 0); #endif Console.WriteLine(ret); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } public class class_s { public static int a; public static int b; public static int c; public static int d; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.GrainDirectory; using Orleans.Runtime.Scheduler; using Orleans.Configuration; using System.Collections.Immutable; namespace Orleans.Runtime.GrainDirectory { internal class LocalGrainDirectory : ILocalGrainDirectory, ISiloStatusListener { private readonly AdaptiveDirectoryCacheMaintainer maintainer; private readonly ILogger log; private readonly SiloAddress seed; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly object writeLock = new object(); private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved; private DirectoryMembership directoryMembership = DirectoryMembership.Default; // Consider: move these constants into an apropriate place internal const int HOP_LIMIT = 6; // forward a remote request no more than 5 times public static readonly TimeSpan RETRY_DELAY = TimeSpan.FromMilliseconds(200); // Pause 200ms between forwards to let the membership directory settle down protected SiloAddress Seed { get { return seed; } } internal ILogger Logger { get { return log; } } // logger is shared with classes that manage grain directory internal bool Running; internal SiloAddress MyAddress { get; private set; } internal IGrainDirectoryCache DirectoryCache { get; private set; } internal GrainDirectoryPartition DirectoryPartition { get; private set; } public RemoteGrainDirectory RemoteGrainDirectory { get; private set; } public RemoteGrainDirectory CacheValidator { get; private set; } internal OrleansTaskScheduler Scheduler { get; private set; } internal GrainDirectoryHandoffManager HandoffManager { get; private set; } public string ClusterId { get; } private readonly CounterStatistic localLookups; private readonly CounterStatistic localSuccesses; private readonly CounterStatistic fullLookups; private readonly CounterStatistic cacheLookups; private readonly CounterStatistic cacheSuccesses; private readonly CounterStatistic registrationsIssued; private readonly CounterStatistic registrationsSingleActIssued; private readonly CounterStatistic unregistrationsIssued; private readonly CounterStatistic unregistrationsManyIssued; private readonly IntValueStatistic directoryPartitionCount; internal readonly CounterStatistic RemoteLookupsSent; internal readonly CounterStatistic RemoteLookupsReceived; internal readonly CounterStatistic LocalDirectoryLookups; internal readonly CounterStatistic LocalDirectorySuccesses; internal readonly CounterStatistic CacheValidationsSent; internal readonly CounterStatistic CacheValidationsReceived; internal readonly CounterStatistic RegistrationsLocal; internal readonly CounterStatistic RegistrationsRemoteSent; internal readonly CounterStatistic RegistrationsRemoteReceived; internal readonly CounterStatistic RegistrationsSingleActLocal; internal readonly CounterStatistic RegistrationsSingleActRemoteSent; internal readonly CounterStatistic RegistrationsSingleActRemoteReceived; internal readonly CounterStatistic UnregistrationsLocal; internal readonly CounterStatistic UnregistrationsRemoteSent; internal readonly CounterStatistic UnregistrationsRemoteReceived; internal readonly CounterStatistic UnregistrationsManyRemoteSent; internal readonly CounterStatistic UnregistrationsManyRemoteReceived; public LocalGrainDirectory( ILocalSiloDetails siloDetails, OrleansTaskScheduler scheduler, ISiloStatusOracle siloStatusOracle, IInternalGrainFactory grainFactory, Factory<GrainDirectoryPartition> grainDirectoryPartitionFactory, IOptions<DevelopmentClusterMembershipOptions> developmentClusterMembershipOptions, IOptions<GrainDirectoryOptions> grainDirectoryOptions, ILoggerFactory loggerFactory) { this.log = loggerFactory.CreateLogger<LocalGrainDirectory>(); var clusterId = siloDetails.ClusterId; MyAddress = siloDetails.SiloAddress; Scheduler = scheduler; this.siloStatusOracle = siloStatusOracle; this.grainFactory = grainFactory; ClusterId = clusterId; DirectoryCache = GrainDirectoryCacheFactory.CreateGrainDirectoryCache(grainDirectoryOptions.Value); /* TODO - investigate dynamic config changes using IOptions - jbragg clusterConfig.OnConfigChange("Globals/Caching", () => { lock (membershipCache) { DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(globalConfig); } }); */ maintainer = GrainDirectoryCacheFactory.CreateGrainDirectoryCacheMaintainer( this, this.DirectoryCache, grainFactory, loggerFactory); var primarySiloEndPoint = developmentClusterMembershipOptions.Value.PrimarySiloEndpoint; if (primarySiloEndPoint != null) { this.seed = this.MyAddress.Endpoint.Equals(primarySiloEndPoint) ? this.MyAddress : SiloAddress.New(primarySiloEndPoint, 0); } DirectoryPartition = grainDirectoryPartitionFactory(); HandoffManager = new GrainDirectoryHandoffManager(this, siloStatusOracle, grainFactory, grainDirectoryPartitionFactory, loggerFactory); RemoteGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceType, loggerFactory); CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorType, loggerFactory); // add myself to the list of members AddServer(MyAddress); Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) => String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode()); localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED); localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES); fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED); RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT); RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED); LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED); LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES); cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED); cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () => { long delta1, delta2; long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1); long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2); return String.Format("{0}, Delta={1}", (curr2 != 0 ? (float)curr1 / (float)curr2 : 0) ,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0)); }); CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT); CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED); registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED); RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL); RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT); RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED); registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED); RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL); RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT); RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED); unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED); UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL); UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT); UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED); unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED); UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT); UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED); directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor()); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)this.RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => { var ring = this.directoryMembership.MembershipRingList; return ring.Count == 0 ? 0 : ((float)100 / (float)ring.Count); }); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => this.directoryMembership.MembershipRingList.Count); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () => { var ring = this.directoryMembership.MembershipRingList; return Utils.EnumerableToString(ring, siloAddressPrint); }); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(this.FindPredecessors(this.MyAddress, 1), siloAddressPrint)); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(this.FindSuccessors(this.MyAddress, 1), siloAddressPrint)); } public void Start() { log.Info("Start"); Running = true; if (maintainer != null) { maintainer.Start(); } } // Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised. // This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of // grains (for update purposes), which could cause application requests that require a new activation to be created to time out. // The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes // would receive successful responses but would not be reflected in the eventual state of the directory. // It's easy to change this, if we think the trade-off is better the other way. public void Stop() { // This will cause remote write requests to be forwarded to the silo that will become the new owner. // Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the // new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've // begun stopping, which could cause them to not get handed off to the new owner. //mark Running as false will exclude myself from CalculateGrainDirectoryPartition(grainId) Running = false; if (maintainer != null) { maintainer.Stop(); } DirectoryPartition.Clear(); DirectoryCache.Clear(); } /// <inheritdoc /> public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); lock (this.writeLock) { this.catalogOnSiloRemoved = callback; } } protected void AddServer(SiloAddress silo) { lock (this.writeLock) { var existing = this.directoryMembership; if (existing.MembershipCache.Contains(silo)) { // we have already cached this silo return; } // insert new silo in the sorted order long hash = silo.GetConsistentHashCode(); // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former. // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then // 'index' will get 0, as needed. int index = existing.MembershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; this.directoryMembership = new DirectoryMembership( existing.MembershipRingList.Insert(index, silo), existing.MembershipCache.Add(silo)); HandoffManager.ProcessSiloAddEvent(silo); AdjustLocalDirectory(silo, dead: false); AdjustLocalCache(silo, dead: false); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} added silo {1}", MyAddress, silo); } } protected void RemoveServer(SiloAddress silo, SiloStatus status) { lock (this.writeLock) { try { // Only notify the catalog once. Order is important: call BEFORE updating membershipRingList. this.catalogOnSiloRemoved?.Invoke(silo, status); } catch (Exception exc) { log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception, String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc); } var existing = this.directoryMembership; if (!existing.MembershipCache.Contains(silo)) { // we have already removed this silo return; } // the call order is important HandoffManager.ProcessSiloRemoveEvent(silo); this.directoryMembership = new DirectoryMembership( existing.MembershipRingList.Remove(silo), existing.MembershipCache.Remove(silo)); AdjustLocalDirectory(silo, dead: true); AdjustLocalCache(silo, dead: true); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} removed silo {1}", MyAddress, silo); } } /// <summary> /// Adjust local directory following the addition/removal of a silo /// </summary> protected void AdjustLocalDirectory(SiloAddress silo, bool dead) { // Determine which activations to remove. var activationsToRemove = new List<(GrainId, ActivationId)>(); foreach (var entry in this.DirectoryPartition.GetItems()) { var (grain, grainInfo) = (entry.Key, entry.Value); foreach (var instance in grainInfo.Instances) { var (activationId, activationInfo) = (instance.Key, instance.Value); // Include any activations from dead silos and from predecessors. var siloIsDead = dead && activationInfo.SiloAddress.Equals(silo); var siloIsPredecessor = activationInfo.SiloAddress.IsPredecessorOf(silo); if (siloIsDead || siloIsPredecessor) { activationsToRemove.Add((grain, activationId)); } } } // Remove all defunct activations. foreach (var activation in activationsToRemove) { DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2); } } /// Adjust local cache following the removal of a silo by dropping: /// 1) entries that point to activations located on the removed silo /// 2) entries for grains that are now owned by this silo (me) /// 3) entries for grains that were owned by this removed silo - we currently do NOT do that. /// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership). /// We don't do that since first cache refresh handles that. /// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo. /// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner). protected void AdjustLocalCache(SiloAddress silo, bool dead) { // For dead silos, remove any activation registered to that silo or one of its predecessors. // For new silos, remove any activation registered to one of its predecessors. Func<Tuple<SiloAddress, ActivationId>, bool> predicate; if (dead) predicate = t => t.Item1.Equals(silo) || t.Item1.IsPredecessorOf(silo); else predicate = t => t.Item1.IsPredecessorOf(silo); // remove all records of activations located on the removed silo foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues) { // 2) remove entries now owned by me (they should be retrieved from my directory partition) if (MyAddress.Equals(CalculateGrainDirectoryPartition(tuple.Item1))) { DirectoryCache.Remove(tuple.Item1); } // 1) remove entries that point to activations located on the removed silo RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, predicate); } } internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count) { var existing = this.directoryMembership; int index = existing.MembershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = existing.MembershipRingList.Count; for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--) { result.Add(existing.MembershipRingList[(i + numMembers) % numMembers]); } return result; } internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count) { var existing = this.directoryMembership; int index = existing.MembershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = existing.MembershipRingList.Count; for (int i = index + 1; i % numMembers != index && result.Count < count; i++) { result.Add(existing.MembershipRingList[i % numMembers]); } return result; } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (!Equals(updatedSilo, MyAddress)) // Status change for some other silo { if (status.IsTerminating()) { // QueueAction up the "Remove" to run on a system turn Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator); } else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active { // QueueAction up the "Remove" to run on a system turn Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator); } } } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } /// <summary> /// Finds the silo that owns the directory information for the given grain ID. /// This method will only be null when I'm the only silo in the cluster and I'm shutting down /// </summary> /// <param name="grainId"></param> /// <returns></returns> public SiloAddress CalculateGrainDirectoryPartition(GrainId grainId) { // give a special treatment for special grains if (grainId.IsSystemTarget()) { if (Constants.SystemMembershipTableType.Equals(grainId)) { if (Seed == null) { var errorMsg = $"Development clustering cannot run without a primary silo. " + $"Please configure {nameof(DevelopmentClusterMembershipOptions)}.{nameof(DevelopmentClusterMembershipOptions.PrimarySiloEndpoint)} " + "or provide a primary silo address to the UseDevelopmentClustering extension. " + "Alternatively, you may want to use reliable membership, such as Azure Table."; throw new ArgumentException(errorMsg, "grainId = " + grainId); } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress); // every silo owns its system targets return MyAddress; } SiloAddress siloAddress = null; int hash = unchecked((int)grainId.GetUniformHashCode()); // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. // excludeThisSIloIfStopping flag was removed because we believe that flag complicates things unnecessarily. We can add it back if it turns out that flag // is doing something valuable. bool excludeMySelf = !Running; var existing = this.directoryMembership; if (existing.MembershipRingList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return !Running ? null : MyAddress; } // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes for (var index = existing.MembershipRingList.Count - 1; index >= 0; --index) { var item = existing.MembershipRingList[index]; if (IsSiloNextInTheRing(item, hash, excludeMySelf)) { siloAddress = item; break; } } if (siloAddress == null) { // If not found in the traversal, last silo will do (we are on a ring). // We checked above to make sure that the list isn't empty, so this should always be safe. siloAddress = existing.MembershipRingList[existing.MembershipRingList.Count - 1]; // Make sure it's not us... if (siloAddress.Equals(MyAddress) && excludeMySelf) { siloAddress = existing.MembershipRingList.Count > 1 ? existing.MembershipRingList[existing.MembershipRingList.Count - 2] : null; } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress?.GetConsistentHashCode()); return siloAddress; } public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription) { SiloAddress owner = CalculateGrainDirectoryPartition(grainId); if (owner == null) { // We don't know about any other silos, and we're stopping, so throw throw new InvalidOperationException("Grain directory is stopping"); } if (owner.Equals(MyAddress)) { // if I am the owner, perform the operation locally return null; } if (hopCount >= HOP_LIMIT) { // we are not forwarding because there were too many hops already throw new OrleansException($"Silo {MyAddress} is not owner of {grainId}, cannot forward {operationDescription} to owner {owner} because hop limit is reached"); } // forward to the silo that we think is the owner return owner; } public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount) { var counterStatistic = singleActivation ? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued) : (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued); counterStatistic.Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync"); if (forwardAddress is object) { int hash = unchecked((int)address.Grain.GetUniformHashCode()); this.log.LogWarning($"RegisterAsync - It seems we are not the owner of activation {address} (hash: {hash:X}), trying to forward it to {forwardAddress} (hopCount={hopCount})"); } } if (forwardAddress == null) { (singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment(); if (singleActivation) { var result = DirectoryPartition.AddSingleActivation(address.Grain, address.Activation, address.Silo); return result; } else { var tag = DirectoryPartition.AddActivation(address.Grain, address.Activation, address.Silo); return new AddressAndTag() { Address = address, VersionTag = tag }; } } else { (singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment(); // otherwise, notify the owner AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1); if (singleActivation) { // Caching optimization: // cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! if (result.Address == null) return result; if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result; var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) }; // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag); } else { if (IsValidSilo(address.Silo)) { // Caching optimization: // cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached; if (!DirectoryCache.LookUp(address.Grain, out cached)) { cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) }; } else { var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1); newcached.AddRange(cached); newcached.Add(Tuple.Create(address.Silo, address.Activation)); cached = newcached; } // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag); } } return result; } } public Task UnregisterAfterNonexistingActivation(ActivationAddress addr, SiloAddress origin) { log.Trace("UnregisterAfterNonexistingActivation addr={0} origin={1}", addr, origin); if (origin == null || this.directoryMembership.MembershipCache.Contains(origin)) { // the request originated in this cluster, call unregister here return UnregisterAsync(addr, UnregistrationCause.NonexistentActivation, 0); } else { // the request originated in another cluster, call unregister there var remoteDirectory = GetDirectoryReference(origin); return remoteDirectory.UnregisterAsync(addr, UnregistrationCause.NonexistentActivation); } } public async Task UnregisterAsync(ActivationAddress address, UnregistrationCause cause, int hopCount) { (hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment(); if (hopCount == 0) InvalidateCacheEntry(address); // see if the owner is somewhere else (returns null if we are owner) var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardaddress != null) { await Task.Delay(RETRY_DELAY); forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync"); this.log.LogWarning($"UnregisterAsync - It seems we are not the owner of activation {address}, trying to forward it to {forwardaddress} (hopCount={hopCount})"); } if (forwardaddress == null) { // we are the owner UnregistrationsLocal.Increment(); DirectoryPartition.RemoveActivation(address.Grain, address.Activation, cause); } else { UnregistrationsRemoteSent.Increment(); // otherwise, notify the owner await GetDirectoryReference(forwardaddress).UnregisterAsync(address, cause, hopCount + 1); } } private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value) { if (dictionary == null) dictionary = new Dictionary<K,List<V>>(); List<V> list; if (! dictionary.TryGetValue(key, out list)) dictionary[key] = list = new List<V>(); list.Add(value); } // helper method to avoid code duplication inside UnregisterManyAsync private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, UnregistrationCause cause, int hopCount, ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context) { foreach (var address in addresses) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context); if (forwardAddress != null) { AddToDictionary(ref forward, forwardAddress, address); } else { // we are the owner UnregistrationsLocal.Increment(); DirectoryPartition.RemoveActivation(address.Grain, address.Activation, cause); } } } public async Task UnregisterManyAsync(List<ActivationAddress> addresses, UnregistrationCause cause, int hopCount) { (hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment(); Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null; var tasks = new List<Task>(); UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist, tasks, "UnregisterManyAsync"); // before forwarding to other silos, we insert a retry delay and re-check destination if (hopCount > 0 && forwardlist != null) { await Task.Delay(RETRY_DELAY); Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null; UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist2, tasks, "UnregisterManyAsync"); forwardlist = forwardlist2; if (forwardlist != null) { this.log.LogWarning($"RegisterAsync - It seems we are not the owner of some activations, trying to forward it to {forwardlist.Count} silos (hopCount={hopCount})"); } } // forward the requests if (forwardlist != null) { foreach (var kvp in forwardlist) { UnregistrationsManyRemoteSent.Increment(); tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, cause, hopCount + 1)); } } // wait for all the requests to finish await Task.WhenAll(tasks); } public bool LocalLookup(GrainId grain, out AddressesAndTag result) { localLookups.Increment(); SiloAddress silo = CalculateGrainDirectoryPartition(grain); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo?.GetConsistentHashCode()); //this will only happen if I'm the only silo in the cluster and I'm shutting down if (silo == null) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain); result = new AddressesAndTag(); return false; } // check if we own the grain if (silo.Equals(MyAddress)) { LocalDirectoryLookups.Increment(); result = GetLocalDirectoryData(grain); if (result.Addresses == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain); return false; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings()); LocalDirectorySuccesses.Increment(); localSuccesses.Increment(); return true; } // handle cache result = new AddressesAndTag(); cacheLookups.Increment(); result.Addresses = GetLocalCacheData(grain); if (result.Addresses == null) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("TryFullLookup else {0}=null", grain); return false; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings()); cacheSuccesses.Increment(); localSuccesses.Increment(); return true; } public AddressesAndTag GetLocalDirectoryData(GrainId grain) { return DirectoryPartition.LookUpActivations(grain); } public List<ActivationAddress> GetLocalCacheData(GrainId grain) { IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached; return DirectoryCache.LookUp(grain, out cached) ? cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() : null; } public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0) { (hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync"); if (forwardAddress is object) { int hash = unchecked((int)grainId.GetUniformHashCode()); this.log.LogWarning($"LookupAsync - It seems we are not the owner of grain {grainId} (hash: {hash:X}), trying to forward it to {forwardAddress} (hopCount={hopCount})"); } } if (forwardAddress == null) { // we are the owner LocalDirectoryLookups.Increment(); var localResult = DirectoryPartition.LookUpActivations(grainId); if (localResult.Addresses == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}=none", grainId); localResult.Addresses = new List<ActivationAddress>(); localResult.VersionTag = GrainInfo.NO_ETAG; return localResult; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings()); LocalDirectorySuccesses.Increment(); return localResult; } else { // Just a optimization. Why sending a message to someone we know is not valid. if (!IsValidSilo(forwardAddress)) { throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress)); } RemoteLookupsSent.Increment(); var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1); // update the cache result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList(); if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings()); var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList(); if (entries.Count > 0) DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag); return result; } } public async Task DeleteGrainAsync(GrainId grainId, int hopCount) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync"); this.log.LogWarning($"DeleteGrainAsync - It seems we are not the owner of grain {grainId}, trying to forward it to {forwardAddress} (hopCount={hopCount})"); } if (forwardAddress == null) { // we are the owner DirectoryPartition.RemoveGrain(grainId); } else { // otherwise, notify the owner DirectoryCache.Remove(grainId); await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1); } } public void InvalidateCacheEntry(ActivationAddress activationAddress, bool invalidateDirectoryAlso = false) { int version; IReadOnlyList<Tuple<SiloAddress, ActivationId>> list; var grainId = activationAddress.Grain; var activationId = activationAddress.Activation; // look up grainId activations if (DirectoryCache.LookUp(grainId, out list, out version)) { RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId)); } } /// <summary> /// For testing purposes only. /// Returns the silo that this silo thinks is the primary owner of directory information for /// the provided grain ID. /// </summary> /// <param name="grain"></param> /// <returns></returns> public SiloAddress GetPrimaryForGrain(GrainId grain) { return CalculateGrainDirectoryPartition(grain); } public override string ToString() { var sb = new StringBuilder(); long localLookupsDelta; long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta); long localLookupsSucceededDelta; long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta); long fullLookupsDelta; long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta); long directoryPartitionSize = directoryPartitionCount.GetCurrentValue(); sb.AppendLine("Local Grain Directory:"); sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine(); sb.AppendLine(" Since last call:"); sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine(); if (localLookupsDelta > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine(); sb.AppendLine(" Since start:"); sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine(); if (localLookupsCurrent > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine(); sb.Append(DirectoryCache.ToString()); return sb.ToString(); } private long RingDistanceToSuccessor() { long distance; List<SiloAddress> successorList = FindSuccessors(MyAddress, 1); if (successorList == null || successorList.Count == 0) { distance = 0; } else { SiloAddress successor = successorList.First(); distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor); } return distance; } private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2) { const long ringSize = int.MaxValue * 2L; long hash1 = silo1.GetConsistentHashCode(); long hash2 = silo2.GetConsistentHashCode(); if (hash2 > hash1) return hash2 - hash1; if (hash2 < hash1) return ringSize - (hash1 - hash2); return 0; } public string RingStatusToString() { var sb = new StringBuilder(); sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine(); sb.AppendLine("Ring is:"); var membershipRingList = this.directoryMembership.MembershipRingList; foreach (var silo in membershipRingList) sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine(); sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine(); sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")); return sb.ToString(); } internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo) { return this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceType, silo); } private bool IsSiloNextInTheRing(SiloAddress siloAddr, int hash, bool excludeMySelf) { return siloAddr.GetConsistentHashCode() <= hash && (!excludeMySelf || !siloAddr.Equals(MyAddress)); } private static void RemoveActivations(IGrainDirectoryCache directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove) { int removeCount = activations.Count(doRemove); if (removeCount == 0) { return; // nothing to remove, done here } if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation { var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount); newList.AddRange(activations.Where(t => !doRemove(t))); directoryCache.AddOrUpdate(key, newList, version); } else // no activations left, remove from cache { directoryCache.Remove(key); } } public bool IsSiloInCluster(SiloAddress silo) { return this.directoryMembership.MembershipCache.Contains(silo); } private class DirectoryMembership { public DirectoryMembership(ImmutableList<SiloAddress> membershipRingList, ImmutableHashSet<SiloAddress> membershipCache) { this.MembershipRingList = membershipRingList; this.MembershipCache = membershipCache; } public static DirectoryMembership Default { get; } = new DirectoryMembership(ImmutableList<SiloAddress>.Empty, ImmutableHashSet<SiloAddress>.Empty); public ImmutableList<SiloAddress> MembershipRingList { get; } public ImmutableHashSet<SiloAddress> MembershipCache { get; } } } }
/* * CID0013.cs - nl culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "nl.txt". namespace I18N.West { using System; using System.Globalization; using I18N.Common; public class CID0013 : RootCulture { public CID0013() : base(0x0013) {} public CID0013(int culture) : base(culture) {} public override String Name { get { return "nl"; } } public override String ThreeLetterISOLanguageName { get { return "nld"; } } public override String ThreeLetterWindowsLanguageName { get { return "NLD"; } } public override String TwoLetterISOLanguageName { get { return "nl"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AbbreviatedDayNames = new String[] {"zo", "ma", "di", "wo", "do", "vr", "za"}; dfi.DayNames = new String[] {"zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"}; dfi.AbbreviatedMonthNames = new String[] {"jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec", ""}; dfi.MonthNames = new String[] {"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december", ""}; dfi.DateSeparator = "-"; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "d MMMM yyyy"; dfi.LongTimePattern = "H:mm:ss z"; dfi.ShortDatePattern = "d-M-yy"; dfi.ShortTimePattern = "H:mm"; dfi.FullDateTimePattern = "dddd d MMMM yyyy H:mm:ss' uur' z"; dfi.I18NSetDateTimePatterns(new String[] { "d:d-M-yy", "D:dddd d MMMM yyyy", "f:dddd d MMMM yyyy H:mm:ss' uur' z", "f:dddd d MMMM yyyy H:mm:ss z", "f:dddd d MMMM yyyy H:mm:ss", "f:dddd d MMMM yyyy H:mm", "F:dddd d MMMM yyyy HH:mm:ss", "g:d-M-yy H:mm:ss' uur' z", "g:d-M-yy H:mm:ss z", "g:d-M-yy H:mm:ss", "g:d-M-yy H:mm", "G:d-M-yy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:H:mm:ss' uur' z", "t:H:mm:ss z", "t:H:mm:ss", "t:H:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "."; nfi.NumberGroupSeparator = "."; nfi.PercentGroupSeparator = "."; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "nl": return "Nederlands"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "NL": return "Nederland"; case "BE": return "Belgi\u00EB"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int EBCDICCodePage { get { return 500; } } public override int OEMCodePage { get { return 850; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0013 public class CNnl : CID0013 { public CNnl() : base() {} }; // class CNnl }; // namespace I18N.West
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Datadruid.WebService.Areas.HelpPage.Models; namespace Datadruid.WebService.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; namespace System { public partial class Uri { // // All public ctors go through here // private void CreateThis(string uri, bool dontEscape, UriKind uriKind) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } _string = uri == null ? string.Empty : uri; if (dontEscape) _flags |= Flags.UserEscaped; ParsingError err = ParseScheme(_string, ref _flags, ref _syntax); UriFormatException e; InitializeUri(err, uriKind, out e); if (e != null) throw e; } private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e) { if (err == ParsingError.None) { if (IsImplicitFile) { // V1 compat // A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and // uriKind != Absolute if (NotAny(Flags.DosPath) && uriKind != UriKind.Absolute && (uriKind == UriKind.Relative || (_string.Length >= 2 && (_string[0] != '\\' || _string[1] != '\\')))) { _syntax = null; //make it be relative Uri _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otheriwse an absolute file Uri wins when it's of the form "\\something" } // // V1 compat issue // We should support relative Uris of the form c:\bla or c:/bla // else if (uriKind == UriKind.Relative && InFact(Flags.DosPath)) { _syntax = null; //make it be relative Uri _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otheriwse an absolute file Uri wins when it's of the form "c:\something" } } } else if (err > ParsingError.LastRelativeUriOkErrIndex) { //This is a fatal error based solely on scheme name parsing _string = null; // make it be invalid Uri e = GetException(err); return; } bool hasUnicode = false; _iriParsing = (s_IriParsing && ((_syntax == null) || _syntax.InFact(UriSyntaxFlags.AllowIriParsing))); if (_iriParsing && (CheckForUnicode(_string) || CheckForEscapedUnreserved(_string))) { _flags |= Flags.HasUnicode; hasUnicode = true; // switch internal strings _originalUnicodeString = _string; // original string location changed } if (_syntax != null) { if (_syntax.IsSimple) { if ((err = PrivateParseMinimal()) != ParsingError.None) { if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { // RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri. _syntax = null; // convert to relative uri e = null; _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } else e = GetException(err); } else if (uriKind == UriKind.Relative) { // Here we know that we can create an absolute Uri, but the user has requested only a relative one e = GetException(ParsingError.CannotCreateRelative); } else e = null; // will return from here if (_iriParsing && hasUnicode) { // In this scenario we need to parse the whole string EnsureParseRemaining(); } } else { // offer custom parser to create a parsing context _syntax = _syntax.InternalOnNewUri(); // incase they won't call us _flags |= Flags.UserDrivenParsing; // Ask a registered type to validate this uri _syntax.InternalValidate(this, out e); if (e != null) { // Can we still take it as a relative Uri? if (uriKind != UriKind.Absolute && err != ParsingError.None && err <= ParsingError.LastRelativeUriOkErrIndex) { _syntax = null; // convert it to relative e = null; _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } } else // e == null { if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion)) { // User parser took over on an invalid Uri SetUserDrivenParsing(); } else if (uriKind == UriKind.Relative) { // Here we know that custom parser can create an absolute Uri, but the user has requested only a // relative one e = GetException(ParsingError.CannotCreateRelative); } if (_iriParsing && hasUnicode) { // In this scenario we need to parse the whole string EnsureParseRemaining(); } } // will return from here } } // If we encountered any parsing errors that indicate this may be a relative Uri, // and we'll allow relative Uri's, then create one. else if (err != ParsingError.None && uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { e = null; _flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri if (_iriParsing && hasUnicode) { // Iri'ze and then normalize relative uris _string = EscapeUnescapeIri(_originalUnicodeString, 0, _originalUnicodeString.Length, (UriComponents)0); } } else { _string = null; // make it be invalid Uri e = GetException(err); } } // // Unescapes entire string and checks if it has unicode chars // private bool CheckForUnicode(string data) { bool hasUnicode = false; char[] chars = new char[data.Length]; int count = 0; chars = UriHelper.UnescapeString(data, 0, data.Length, chars, ref count, c_DummyChar, c_DummyChar, c_DummyChar, UnescapeMode.Unescape | UnescapeMode.UnescapeAll, null, false); for (int i = 0; i < count; ++i) { if (chars[i] > '\x7f') { // Unicode hasUnicode = true; break; } } return hasUnicode; } // Does this string have any %6A sequences that are 3986 Unreserved characters? These should be un-escaped. private unsafe bool CheckForEscapedUnreserved(string data) { fixed (char* tempPtr = data) { for (int i = 0; i < data.Length - 2; ++i) { if (tempPtr[i] == '%' && IsHexDigit(tempPtr[i + 1]) && IsHexDigit(tempPtr[i + 2]) && tempPtr[i + 1] >= '0' && tempPtr[i + 1] <= '7') // max 0x7F { char ch = UriHelper.EscapedAscii(tempPtr[i + 1], tempPtr[i + 2]); if (ch != c_DummyChar && UriHelper.Is3986Unreserved(ch)) { return true; } } } } return false; } // // Returns true if the string represents a valid argument to the Uri ctor // If uriKind != AbsoluteUri then certain parsing erros are ignored but Uri usage is limited // public static bool TryCreate(string uriString, UriKind uriKind, out Uri result) { if ((object)uriString == null) { result = null; return false; } UriFormatException e = null; result = CreateHelper(uriString, false, uriKind, ref e); return (object)e == null && result != null; } public static bool TryCreate(Uri baseUri, string relativeUri, out Uri result) { Uri relativeLink; if (TryCreate(relativeUri, UriKind.RelativeOrAbsolute, out relativeLink)) { if (!relativeLink.IsAbsoluteUri) return TryCreate(baseUri, relativeLink, out result); result = relativeLink; return true; } result = null; return false; } public static bool TryCreate(Uri baseUri, Uri relativeUri, out Uri result) { result = null; //TODO: Work out the baseUri==null case if ((object)baseUri == null || (object)relativeUri == null) return false; if (baseUri.IsNotAbsoluteUri) return false; UriFormatException e; string newUriString = null; bool dontEscape; if (baseUri.Syntax.IsSimple) { dontEscape = relativeUri.UserEscaped; result = ResolveHelper(baseUri, relativeUri, ref newUriString, ref dontEscape, out e); } else { dontEscape = false; newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e); } if (e != null) return false; if ((object)result == null) result = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e); return (object)e == null && result != null && result.IsAbsoluteUri; } public string GetComponents(UriComponents components, UriFormat format) { if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString) throw new ArgumentOutOfRangeException("components", components, SR.net_uri_NotJustSerialization); if ((format & ~UriFormat.SafeUnescaped) != 0) throw new ArgumentOutOfRangeException("format"); if (IsNotAbsoluteUri) { if (components == UriComponents.SerializationInfoString) return GetRelativeSerializationString(format); else throw new InvalidOperationException(SR.net_uri_NotAbsolute); } if (Syntax.IsSimple) return GetComponentsHelper(components, format); return Syntax.InternalGetComponents(this, components, format); } // // This is for languages that do not support == != operators overloading // // Note that Uri.Equals will get an optimized path but is limited to true/fasle result only // public static int Compare(Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType) { if ((object)uri1 == null) { if (uri2 == null) return 0; // Equal return -1; // null < non-null } if ((object)uri2 == null) return 1; // non-null > null // a relative uri is always less than an absolute one if (!uri1.IsAbsoluteUri || !uri2.IsAbsoluteUri) return uri1.IsAbsoluteUri ? 1 : uri2.IsAbsoluteUri ? -1 : string.Compare(uri1.OriginalString, uri2.OriginalString, comparisonType); return string.Compare( uri1.GetParts(partsToCompare, compareFormat), uri2.GetParts(partsToCompare, compareFormat), comparisonType ); } public bool IsWellFormedOriginalString() { if (IsNotAbsoluteUri || Syntax.IsSimple) return InternalIsWellFormedOriginalString(); return Syntax.InternalIsWellFormedOriginalString(this); } // TODO: (perf) Making it to not create a Uri internally public static bool IsWellFormedUriString(string uriString, UriKind uriKind) { Uri result; if (!Uri.TryCreate(uriString, uriKind, out result)) return false; return result.IsWellFormedOriginalString(); } // // Internal stuff // // Returns false if OriginalString value // (1) is not correctly escaped as per URI spec excluding intl UNC name case // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file" // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file" // (4) or contains unescaped backslashes even if they will be treated // as forward slashes like http:\\host/path\file or file:\\\c:\path // internal unsafe bool InternalIsWellFormedOriginalString() { if (UserDrivenParsing) throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString())); fixed (char* str = _string) { ushort idx = 0; // // For a relative Uri we only care about escaping and backslashes // if (!IsAbsoluteUri) { // my:scheme/path?query is not well formed because the colon is ambiguous if (CheckForColonInFirstPathSegment(_string)) { return false; } return (CheckCanonical(str, ref idx, (ushort)_string.Length, c_EOL) & (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical; } // // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file" // if (IsImplicitFile) return false; //This will get all the offsets, a Host name will be checked separatelly below EnsureParseRemaining(); Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical)); // User, Path, Query or Fragment may have some non escaped characters if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical | Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero) && (!_iriParsing || (_iriParsing && (((nonCanonical & Flags.E_UserNotCanonical) == 0) || ((nonCanonical & Flags.UserIriCanonical) == 0)) && (((nonCanonical & Flags.E_PathNotCanonical) == 0) || ((nonCanonical & Flags.PathIriCanonical) == 0)) && (((nonCanonical & Flags.E_QueryNotCanonical) == 0) || ((nonCanonical & Flags.QueryIriCanonical) == 0)) && (((nonCanonical & Flags.E_FragmentNotCanonical) == 0) || ((nonCanonical & Flags.FragmentIriCanonical) == 0))))) { return false; } // checking on scheme:\\ or file://// if (InFact(Flags.AuthorityFound)) { idx = (ushort)(_info.Offset.Scheme + _syntax.SchemeName.Length + 2); if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\') return false; if (InFact(Flags.UncPath | Flags.DosPath)) { while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\')) return false; } } // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file" // Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash // (which looks absent) then the method has to fail. // Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check. if (InFact(Flags.FirstSlashAbsent) && _info.Offset.Query > _info.Offset.Path) return false; // (4) or contains unescaped backslashes even if they will be treated // as forward slashes like http:\\host/path\file or file:\\\c:\path // Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid if (InFact(Flags.BackslashInPath)) return false; // Capturing a rare case like file:///c|/dir if (IsDosPath && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|') return false; // // May need some real CPU processing to anwser the request // // // Check escaping for authority // // IPv6 hosts cannot be properly validated by CheckCannonical if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType) { idx = _info.Offset.User; Check result = CheckCanonical(str, ref idx, (ushort)_info.Offset.Path, '/'); if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical)) != Check.EscapedCanonical) && (!_iriParsing || (_iriParsing && ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical)) != (Check.DisplayCanonical | Check.FoundNonAscii))))) { return false; } } // Want to ensure there are slashes after the scheme if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound)) == (Flags.SchemeNotCanonical | Flags.AuthorityFound)) { idx = (ushort)_syntax.SchemeName.Length; while (str[idx++] != ':') ; if (idx + 1 >= _string.Length || str[idx] != '/' || str[idx + 1] != '/') return false; } } // // May be scheme, host, port or path need some canonicalization but still the uri string is found to be a // "well formed" one // return true; } public static string UnescapeDataString(string stringToUnescape) { if ((object)stringToUnescape == null) throw new ArgumentNullException("stringToUnescape"); if (stringToUnescape.Length == 0) return string.Empty; unsafe { fixed (char* pStr = stringToUnescape) { int position; for (position = 0; position < stringToUnescape.Length; ++position) if (pStr[position] == '%') break; if (position == stringToUnescape.Length) return stringToUnescape; UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll; position = 0; char[] dest = new char[stringToUnescape.Length]; dest = UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, dest, ref position, c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false); return new string(dest, 0, position); } } } // // Where stringToEscape is intented to be a completely unescaped URI string. // This method will escape any character that is not a reserved or unreserved character, including percent signs. // Note that EscapeUriString will also do not escape a '#' sign. // public static string EscapeUriString(string stringToEscape) { if ((object)stringToEscape == null) throw new ArgumentNullException("stringToEscape"); if (stringToEscape.Length == 0) return string.Empty; int position = 0; char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if ((object)dest == null) return stringToEscape; return new string(dest, 0, position); } // // Where stringToEscape is intended to be URI data, but not an entire URI. // This method will escape any character that is not an unreserved character, including percent signs. // public static string EscapeDataString(string stringToEscape) { if ((object)stringToEscape == null) throw new ArgumentNullException("stringToEscape"); if (stringToEscape.Length == 0) return string.Empty; int position = 0; char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, false, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return stringToEscape; return new string(dest, 0, position); } // // Cleans up the specified component according to Iri rules // a) Chars allowed by iri in a component are unescaped if found escaped // b) Bidi chars are stripped // // should be called only if IRI parsing is switched on internal unsafe string EscapeUnescapeIri(string input, int start, int end, UriComponents component) { fixed (char* pInput = input) { return IriHelper.EscapeUnescapeIri(pInput, start, end, component); } } // Should never be used except by the below method private Uri(Flags flags, UriParser uriParser, string uri) { _flags = flags; _syntax = uriParser; _string = uri; } // // a Uri.TryCreate() method goes through here. // internal static Uri CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException e) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } UriParser syntax = null; Flags flags = Flags.Zero; ParsingError err = ParseScheme(uriString, ref flags, ref syntax); if (dontEscape) flags |= Flags.UserEscaped; // We won't use User factory for these errors if (err != ParsingError.None) { // If it looks as a relative Uri, custom factory is ignored if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) return new Uri((flags & Flags.UserEscaped), null, uriString); return null; } // Cannot be relative Uri if came here Uri result = new Uri(flags, syntax, uriString); // Validate instance using ether built in or a user Parser try { result.InitializeUri(err, uriKind, out e); if (e == null) return result; return null; } catch (UriFormatException ee) { Debug.Assert(!syntax.IsSimple, "A UriPraser threw on InitializeAndValidate."); e = ee; // A precaution since custom Parser should never throw in this case. return null; } } // // Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString // to return combined URI strings from both Uris // otherwise if e != null on output the operation has failed // internal static Uri ResolveHelper(Uri baseUri, Uri relativeUri, ref string newUriString, ref bool userEscaped, out UriFormatException e) { Debug.Assert(!baseUri.IsNotAbsoluteUri && !baseUri.UserDrivenParsing, "Uri::ResolveHelper()|baseUri is not Absolute or is controlled by User Parser."); e = null; string relativeStr = string.Empty; if ((object)relativeUri != null) { if (relativeUri.IsAbsoluteUri) return relativeUri; relativeStr = relativeUri.OriginalString; userEscaped = relativeUri.UserEscaped; } else relativeStr = string.Empty; // Here we can assert that passed "relativeUri" is indeed a relative one if (relativeStr.Length > 0 && (IsLWS(relativeStr[0]) || IsLWS(relativeStr[relativeStr.Length - 1]))) relativeStr = relativeStr.Trim(s_WSchars); if (relativeStr.Length == 0) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri, baseUri.UserEscaped ? UriFormat.UriEscaped : UriFormat.SafeUnescaped); return null; } // Check for a simple fragment in relative part if (relativeStr[0] == '#' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveFragment)) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.UriEscaped) + relativeStr; return null; } // Check for a simple query in relative part if (relativeStr[0] == '?' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveQuery)) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Query & ~UriComponents.Fragment, UriFormat.UriEscaped) + relativeStr; return null; } // Check on the DOS path in the relative Uri (a special case) if (relativeStr.Length >= 3 && (relativeStr[1] == ':' || relativeStr[1] == '|') && IsAsciiLetter(relativeStr[0]) && (relativeStr[2] == '\\' || relativeStr[2] == '/')) { if (baseUri.IsImplicitFile) { // It could have file:/// prepended to the result but we want to keep it as *Implicit* File Uri newUriString = relativeStr; return null; } else if (baseUri.Syntax.InFact(UriSyntaxFlags.AllowDOSPath)) { // The scheme is not changed just the path gets replaced string prefix; if (baseUri.InFact(Flags.AuthorityFound)) prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":///" : "://"; else prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":/" : ":"; newUriString = baseUri.Scheme + prefix + relativeStr; return null; } // If we are here then input like "http://host/path/" + "C:\x" will produce the result http://host/path/c:/x } ParsingError err = GetCombinedString(baseUri, relativeStr, userEscaped, ref newUriString); if (err != ParsingError.None) { e = GetException(err); return null; } if ((object)newUriString == (object)baseUri._string) return baseUri; return null; } private unsafe string GetRelativeSerializationString(UriFormat format) { if (format == UriFormat.UriEscaped) { if (_string.Length == 0) return string.Empty; int position = 0; char[] dest = UriHelper.EscapeString(_string, 0, _string.Length, null, ref position, true, c_DummyChar, c_DummyChar, '%'); if ((object)dest == null) return _string; return new string(dest, 0, position); } else if (format == UriFormat.Unescaped) return UnescapeDataString(_string); else if (format == UriFormat.SafeUnescaped) { if (_string.Length == 0) return string.Empty; char[] dest = new char[_string.Length]; int position = 0; dest = UriHelper.UnescapeString(_string, 0, _string.Length, dest, ref position, c_DummyChar, c_DummyChar, c_DummyChar, UnescapeMode.EscapeUnescape, null, false); return new string(dest, 0, position); } else throw new ArgumentOutOfRangeException("format"); } // // UriParser helpers methods // internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFormat) { if (uriComponents == UriComponents.Scheme) return _syntax.SchemeName; // A serialzation info is "almost" the same as AbsoluteUri except for IPv6 + ScopeID hostname case if ((uriComponents & UriComponents.SerializationInfoString) != 0) uriComponents |= UriComponents.AbsoluteUri; //This will get all the offsets, HostString will be created below if needed EnsureParseRemaining(); if ((uriComponents & UriComponents.NormalizedHost) != 0) { // Down the path we rely on Host to be ON for NormalizedHost uriComponents |= UriComponents.Host; } //Check to see if we need the host/authotity string if ((uriComponents & UriComponents.Host) != 0) EnsureHostString(true); //This, single Port request is always processed here if (uriComponents == UriComponents.Port || uriComponents == UriComponents.StrongPort) { if (((_flags & Flags.NotDefaultPort) != 0) || (uriComponents == UriComponents.StrongPort && _syntax.DefaultPort != UriParser.NoDefaultPort)) { // recreate string from the port value return _info.Offset.PortValue.ToString(CultureInfo.InvariantCulture); } return string.Empty; } if ((uriComponents & UriComponents.StrongPort) != 0) { // Down the path we rely on Port to be ON for StrongPort uriComponents |= UriComponents.Port; } //This request sometime is faster to process here if (uriComponents == UriComponents.Host && (uriFormat == UriFormat.UriEscaped || ((_flags & (Flags.HostNotCanonical | Flags.E_HostNotCanonical)) == 0))) { EnsureHostString(false); return _info.Host; } switch (uriFormat) { case UriFormat.UriEscaped: return GetEscapedParts(uriComponents); case V1ToStringUnescape: case UriFormat.SafeUnescaped: case UriFormat.Unescaped: return GetUnescapedParts(uriComponents, uriFormat); default: throw new ArgumentOutOfRangeException("uriFormat"); } } public bool IsBaseOf(Uri uri) { if ((object)uri == null) throw new ArgumentNullException("uri"); if (!IsAbsoluteUri) return false; if (Syntax.IsSimple) return IsBaseOfHelper(uri); return Syntax.InternalIsBaseOf(this, uri); } internal bool IsBaseOfHelper(Uri uriLink) { if (!IsAbsoluteUri || UserDrivenParsing) return false; if (!uriLink.IsAbsoluteUri) { //a relative uri could have quite tricky form, it's better to fix it now. string newUriString = null; UriFormatException e; bool dontEscape = false; uriLink = ResolveHelper(this, uriLink, ref newUriString, ref dontEscape, out e); if (e != null) return false; if ((object)uriLink == null) uriLink = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e); if (e != null) return false; } if (Syntax.SchemeName != uriLink.Syntax.SchemeName) return false; // Canonicalize and test for substring match up to the last path slash string self = GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped); string other = uriLink.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped); unsafe { fixed (char* selfPtr = self) { fixed (char* otherPtr = other) { return UriHelper.TestForSubPath(selfPtr, (ushort)self.Length, otherPtr, (ushort)other.Length, IsUncOrDosPath || uriLink.IsUncOrDosPath); } } } } // // Only a ctor time call // private void CreateThisFromUri(Uri otherUri) { // Clone the other guy but develop own UriInfo member _info = null; _flags = otherUri._flags; if (InFact(Flags.MinimalUriInfoSet)) { _flags &= ~(Flags.MinimalUriInfoSet | Flags.AllUriInfoSet | Flags.IndexMask); // Port / Path offset int portIndex = otherUri._info.Offset.Path; if (InFact(Flags.NotDefaultPort)) { // Find the start of the port. Account for non-canonical ports like :00123 while (otherUri._string[portIndex] != ':' && portIndex > otherUri._info.Offset.Host) { portIndex--; } if (otherUri._string[portIndex] != ':') { // Something wrong with the NotDefaultPort flag. Reset to path index Debug.Assert(false, "Uri failed to locate custom port at index: " + portIndex); portIndex = otherUri._info.Offset.Path; } } _flags |= (Flags)portIndex; // Port or path } _syntax = otherUri._syntax; _string = otherUri._string; _iriParsing = otherUri._iriParsing; if (otherUri.OriginalStringSwitched) { _originalUnicodeString = otherUri._originalUnicodeString; } if (otherUri.AllowIdn && (otherUri.InFact(Flags.IdnHost) || otherUri.InFact(Flags.UnicodeHost))) { _dnsSafeHost = otherUri._dnsSafeHost; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using log4net; using NetGore.Collections; namespace NetGore.Features.NPCChat.Conditionals { /// <summary> /// The base class for a conditional used in the NPC chatting. Each instanceable derived class /// must include a parameterless constructor (preferably private). /// </summary> public abstract class NPCChatConditionalBase { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Array used for an empty set of <see cref="NPCChatConditionalParameterType"/>s. /// </summary> static readonly NPCChatConditionalParameterType[] _emptyParameterTypes; /// <summary> /// Array used for an empty set of <see cref="NPCChatConditionalParameter"/>s. /// </summary> static readonly NPCChatConditionalParameter[] _emptyParameters; /// <summary> /// Dictionary that contains the <see cref="NPCChatConditionalBase"/> instance /// of each derived class, with the <see cref="Name"/> as the key. /// </summary> static readonly Dictionary<string, NPCChatConditionalBase> _instances = new Dictionary<string, NPCChatConditionalBase>(StringComparer.Ordinal); readonly string _name; readonly NPCChatConditionalParameterType[] _parameterTypes; /// <summary> /// Initializes the <see cref="NPCChatConditionalBase"/> class. /// </summary> static NPCChatConditionalBase() { _emptyParameters = new NPCChatConditionalParameter[0]; _emptyParameterTypes = new NPCChatConditionalParameterType[0]; var filter = new TypeFilterCreator { IsClass = true, IsAbstract = false, Subclass = typeof(NPCChatConditionalBase), RequireConstructor = true, ConstructorParameters = Type.EmptyTypes }; new TypeFactory(filter.GetFilter(), OnLoadTypeHandler); } /// <summary> /// Initializes a new instance of the <see cref="NPCChatConditionalBase"/> class. /// </summary> /// <param name="name">The unique display name of this <see cref="NPCChatConditionalBase"/>. This name /// must be unique for each derived class type. This string is case-sensitive.</param> /// <param name="parameterTypes">The parameter types.</param> /// <exception cref="ArgumentNullException">Argument is null.</exception> protected NPCChatConditionalBase(string name, params NPCChatConditionalParameterType[] parameterTypes) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); if (parameterTypes == null || parameterTypes.Length == 0) parameterTypes = _emptyParameterTypes; _name = name; _parameterTypes = parameterTypes; } /// <summary> /// Gets an IEnumerable of the <see cref="NPCChatConditionalBase"/>s. /// </summary> public static IEnumerable<NPCChatConditionalBase> Conditionals { get { return _instances.Values; } } /// <summary> /// Gets the unique name for this <see cref="NPCChatConditionalBase"/>. This string is case-sensitive. /// </summary> public string Name { get { return _name; } } /// <summary> /// Gets the number of parameters required by this <see cref="NPCChatConditionalBase"/>. /// </summary> public int ParameterCount { get { return _parameterTypes.Length; } } /// <summary> /// Gets an IEnumerable of the <see cref="NPCChatConditionalParameterType"/> used in this /// <see cref="NPCChatConditionalBase"/>. /// </summary> public IEnumerable<NPCChatConditionalParameterType> ParameterTypes { get { return _parameterTypes; } } /// <summary> /// Gets if a <see cref="NPCChatConditionalBase"/> with the given <paramref name="name"/> exists. /// </summary> /// <param name="name">The name of the <see cref="NPCChatConditionalBase"/>.</param> /// <returns>True if a <see cref="NPCChatConditionalBase"/> with the given <paramref name="name"/> /// exists; otherwise false.</returns> public static bool ContainsConditional(string name) { if (string.IsNullOrEmpty(name)) return false; return _instances.ContainsKey(name); } /// <summary> /// When overridden in the derived class, performs the actual conditional evaluation. /// </summary> /// <param name="user">The User.</param> /// <param name="npc">The NPC.</param> /// <param name="parameters">The parameters to use. </param> /// <returns>True if the conditional returns true for the given <paramref name="user"/>, /// <paramref name="npc"/>, and <paramref name="parameters"/>; otherwise false.</returns> protected abstract bool DoEvaluate(object user, object npc, NPCChatConditionalParameter[] parameters); /// <summary> /// Checks the conditional against the given <paramref name="user"/> and <paramref name="npc"/>. /// </summary> /// <param name="user">The User.</param> /// <param name="npc">The NPC.</param> /// <param name="parameters">The parameters to use for performing the conditional check.</param> /// <returns>True if the conditional returns true for the given <paramref name="user"/>, /// <paramref name="npc"/>, and <paramref name="parameters"/>; otherwise false.</returns> /// <exception cref="ArgumentNullException">The <paramref name="user"/> or <paramref name="npc"/> is null.</exception> /// <exception cref="ArgumentException">An invalid number of INPCChatConditionalParameters specified in the /// <paramref name="parameters"/>, or one or more of the ValueTypes in the <paramref name="parameters"/> /// are not of the correct type.</exception> public bool Evaluate(object user, object npc, params NPCChatConditionalParameter[] parameters) { const string errmsgNumberOfParameters = "Invalid number of parameters. Expected {0}, but was given {1}."; const string errmsgValueType = "Invalid ValueType for parameter {0}. Expected `{1}`, but was given `{2}`."; // Check for valid arguments if (user == null) throw new ArgumentNullException("user"); if (npc == null) throw new ArgumentNullException("npc"); // Use an empty array instead of a null one if (parameters == null) parameters = _emptyParameters; // Check for a valid number of parameters if (parameters.Length != _parameterTypes.Length) { var err = string.Format(errmsgNumberOfParameters, _parameterTypes.Length, parameters.Length); throw new ArgumentException(err, "parameters"); } // Check that the parameters are of the correct type for (var i = 0; i < parameters.Length; i++) { if (parameters[i].ValueType != _parameterTypes[i]) { var err = string.Format(errmsgValueType, i, _parameterTypes[i], parameters[i].ValueType); throw new ArgumentException(err, "parameters"); } } // Parameters are all valid, so process the conditional return DoEvaluate(user, npc, parameters); } /// <summary> /// Gets the NPCChatConditionalBase with the given <paramref name="name"/>. /// </summary> /// <param name="name">The name of the NPCChatConditionalBase to get.</param> /// <returns>The NPCChatConditionalBase with the given <paramref name="name"/>.</returns> public static NPCChatConditionalBase GetConditional(string name) { return _instances[name]; } /// <summary> /// Gets the NPCChatConditionalParameterType for the parameter at the given <paramref name="index"/>. /// </summary> /// <param name="index">Index of the parameter to get the NPCChatConditionalParameterType for.</param> /// <returns>The NPCChatConditionalParameterType for the parameter at the given <paramref name="index"/>.</returns> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="index"/> is less than 0 or greater /// than ParameterCount.</exception> public NPCChatConditionalParameterType GetParameter(int index) { if (index < 0 || index >= _parameterTypes.Length) throw new ArgumentOutOfRangeException("index"); return _parameterTypes[index]; } /// <summary> /// Handles when a new type has been loaded into the <see cref="TypeFactory"/>. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="NetGore.Collections.TypeFactoryLoadedEventArgs"/> instance containing the event data.</param> /// <exception cref="ArgumentException">The loaded type in <paramref name="e"/> was invalid or already loaded.</exception> static void OnLoadTypeHandler(TypeFactory sender, TypeFactoryLoadedEventArgs e) { var instance = (NPCChatConditionalBase)sender.GetTypeInstance(e.Name); // Make sure the name is not already in use if (ContainsConditional(instance.Name)) { const string errmsg = "Could not add Type `{0}` - a NPC chat conditional named `{1}` already exists as Type `{2}`."; var err = string.Format(errmsg, e.LoadedType, instance.Name, _instances[instance.Name].GetType()); if (log.IsFatalEnabled) log.Fatal(err); Debug.Fail(err); throw new ArgumentException(err); } // Add the value to the Dictionary _instances.Add(instance.Name, instance); if (log.IsDebugEnabled) log.DebugFormat("Loaded NPC chat conditional `{0}` from Type `{1}`.", instance.Name, e.LoadedType); } /// <summary> /// Tries to get the <see cref="NPCChatConditionalBase"/> with the given <paramref name="name"/>. /// </summary> /// <param name="name">The name of the <see cref="NPCChatConditionalBase"/> to get.</param> /// <param name="value">If the method returns true, contains the <see cref="NPCChatConditionalBase"/> /// with the given <paramref name="name"/>.</param> /// <returns>True if the <paramref name="value"/> was successfully acquired; otherwise false.</returns> public static bool TryGetResponseAction(string name, out NPCChatConditionalBase value) { return _instances.TryGetValue(name, out value); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations of Azure SQL Database Transparent Data /// Encryption. Contains operations to: Retrieve, and Update Transparent /// Data Encryption. /// </summary> internal partial class TransparentDataEncryptionOperations : IServiceOperations<SqlManagementClient>, ITransparentDataEncryptionOperations { /// <summary> /// Initializes a new instance of the /// TransparentDataEncryptionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TransparentDataEncryptionOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Creates or updates an Azure SQL Database Transparent Data /// Encryption Operation. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which setting the /// Transparent Data Encryption applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating /// transparent data encryption. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Get for a Azure Sql Database /// Transparent Data Encryption request. /// </returns> public async Task<TransparentDataEncryptionGetResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string databaseName, TransparentDataEncryptionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/transparentDataEncryption/current"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject transparentDataEncryptionCreateOrUpdateParametersValue = new JObject(); requestDoc = transparentDataEncryptionCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); transparentDataEncryptionCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.State != null) { propertiesValue["status"] = parameters.Properties.State; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TransparentDataEncryptionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TransparentDataEncryptionGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TransparentDataEncryption transparentDataEncryptionInstance = new TransparentDataEncryption(); result.TransparentDataEncryption = transparentDataEncryptionInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { TransparentDataEncryptionProperties propertiesInstance = new TransparentDataEncryptionProperties(); transparentDataEncryptionInstance.Properties = propertiesInstance; JToken statusValue = propertiesValue2["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.State = statusInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); transparentDataEncryptionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); transparentDataEncryptionInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); transparentDataEncryptionInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); transparentDataEncryptionInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); transparentDataEncryptionInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database Transparent Data Encryption Response. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the /// Transparent Data Encryption applies. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Get for a Azure Sql Database /// Transparent Data Encryption request. /// </returns> public async Task<TransparentDataEncryptionGetResponse> GetAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/transparentDataEncryption/current"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TransparentDataEncryptionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TransparentDataEncryptionGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { TransparentDataEncryption transparentDataEncryptionInstance = new TransparentDataEncryption(); result.TransparentDataEncryption = transparentDataEncryptionInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { TransparentDataEncryptionProperties propertiesInstance = new TransparentDataEncryptionProperties(); transparentDataEncryptionInstance.Properties = propertiesInstance; JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.State = statusInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); transparentDataEncryptionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); transparentDataEncryptionInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); transparentDataEncryptionInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); transparentDataEncryptionInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); transparentDataEncryptionInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database Transparent Data Encryption Activity /// Response. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the /// Transparent Data Encryption applies. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Database Transparent /// Data Encryption Activity request. /// </returns> public async Task<TransparentDataEncryptionActivityListResponse> ListActivityAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "ListActivityAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/transparentDataEncryption/current/operationResults"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TransparentDataEncryptionActivityListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TransparentDataEncryptionActivityListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { TransparentDataEncryptionActivity transparentDataEncryptionActivityInstance = new TransparentDataEncryptionActivity(); result.TransparentDataEncryptionActivities.Add(transparentDataEncryptionActivityInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { TransparentDataEncryptionActivityProperties propertiesInstance = new TransparentDataEncryptionActivityProperties(); transparentDataEncryptionActivityInstance.Properties = propertiesInstance; JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken percentCompleteValue = propertiesValue["percentComplete"]; if (percentCompleteValue != null && percentCompleteValue.Type != JTokenType.Null) { float percentCompleteInstance = ((float)percentCompleteValue); propertiesInstance.PercentComplete = percentCompleteInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); transparentDataEncryptionActivityInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); transparentDataEncryptionActivityInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); transparentDataEncryptionActivityInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); transparentDataEncryptionActivityInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); transparentDataEncryptionActivityInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Controls; namespace Fluent { /// <summary> /// This interface must be implemented for controls /// which are intended to insert to quick access toolbar /// </summary> public interface IQuickAccessItemProvider { /// <summary> /// Gets control which represents shortcut item. /// This item MUST be syncronized with the original /// and send command to original one control. /// </summary> /// <returns>Control which represents shortcut item</returns> FrameworkElement CreateQuickAccessItem(); /// <summary> /// Gets or sets whether control can be added to quick access toolbar /// </summary> bool CanAddToQuickAccessToolBar { get; set; } } /// <summary> /// Peresents quick access shortcut to another control /// </summary> [ContentProperty("Target")] public class QuickAccessMenuItem : MenuItem { #region Fields internal Ribbon Ribbon; #endregion #region Initialization [SuppressMessage("Microsoft.Performance", "CA1810")] static QuickAccessMenuItem() { IsCheckableProperty.AddOwner(typeof(QuickAccessMenuItem), new FrameworkPropertyMetadata(true)); } /// <summary> /// Default constructor /// </summary> public QuickAccessMenuItem() { this.Checked += this.OnChecked; this.Unchecked += this.OnUnchecked; this.Loaded += this.OnFirstLoaded; this.Loaded += this.OnItemLoaded; } #endregion #region Target Property /// <summary> /// Gets or sets shortcut to the target control /// </summary> public Control Target { get { return (Control)this.GetValue(TargetProperty); } set { this.SetValue(TargetProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for shortcut. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty TargetProperty = DependencyProperty.Register("Target", typeof(Control), typeof(QuickAccessMenuItem), new UIPropertyMetadata(null,OnTargetChanged)); private static void OnTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var quickAccessMenuItem = (QuickAccessMenuItem)d; var ribbonControl = e.NewValue as IRibbonControl; if (quickAccessMenuItem.Header == null && ribbonControl != null) { // Set Default Text Value RibbonControl.Bind(ribbonControl, quickAccessMenuItem, "Header", HeaderProperty, BindingMode.OneWay); } if (ribbonControl != null) { var parent = LogicalTreeHelper.GetParent((DependencyObject)ribbonControl); if (parent == null) { quickAccessMenuItem.AddLogicalChild(ribbonControl); } } var oldRibbonControl = e.OldValue as IRibbonControl; if (oldRibbonControl!=null) { var parent = LogicalTreeHelper.GetParent((DependencyObject)oldRibbonControl); if (parent == quickAccessMenuItem) { quickAccessMenuItem.RemoveLogicalChild(oldRibbonControl); } } } #endregion #region Overrides /// <summary> /// Gets an enumerator for logical child elements of this element. /// </summary> protected override IEnumerator LogicalChildren { get { if (this.Target != null) { var parent = LogicalTreeHelper.GetParent(this.Target); if (ReferenceEquals(parent, this)) { var list = new ArrayList { this.Target }; return list.GetEnumerator(); } } return base.LogicalChildren; } } #endregion #region Event Handlers private void OnChecked(object sender, RoutedEventArgs e) { if (this.Ribbon != null) { this.Ribbon.AddToQuickAccessToolBar(this.Target); } } private void OnUnchecked(object sender, RoutedEventArgs e) { if (!this.IsLoaded) { return; } if (this.Ribbon != null) { this.Ribbon.RemoveFromQuickAccessToolBar(this.Target); } } private void OnItemLoaded(object sender, RoutedEventArgs e) { if (!this.IsLoaded) { return; } if (this.Ribbon != null) { this.IsChecked = this.Ribbon.IsInQuickAccessToolBar(this.Target); } } private void OnFirstLoaded(object sender, RoutedEventArgs e) { this.Loaded -= this.OnFirstLoaded; if (this.IsChecked && this.Ribbon != null) { this.Ribbon.AddToQuickAccessToolBar(this.Target); } } #endregion } /// <summary> /// The class responds to mine controls for QuickAccessToolBar /// </summary> internal static class QuickAccessItemsProvider { #region Public Methods /// <summary> /// Determines whether the given control can provide a quick access toolbar item /// </summary> /// <param name="element">Control</param> /// <returns>True if this control is able to provide /// a quick access toolbar item, false otherwise</returns> public static bool IsSupported(UIElement element) { var provider = element as IQuickAccessItemProvider; if (provider != null && provider.CanAddToQuickAccessToolBar) { return true; } return false; } /// <summary> /// Gets control which represents quick access toolbar item /// </summary> /// <param name="element">Host control</param> /// <returns>Control which represents quick access toolbar item</returns> [SuppressMessage("Microsoft.Performance", "CA1800")] public static FrameworkElement GetQuickAccessItem(UIElement element) { FrameworkElement result = null; // If control supports the interface just return what it provides var provider = element as IQuickAccessItemProvider; if (provider != null && provider.CanAddToQuickAccessToolBar) { result = ((IQuickAccessItemProvider)element).CreateQuickAccessItem(); } // The control isn't supported if (result == null) { throw new ArgumentException("The contol " + element.GetType().Name + " is not able to provide a quick access toolbar item"); } if (BindingOperations.IsDataBound(result, UIElement.VisibilityProperty) == false) { RibbonControl.Bind(element, result, "Visibility", UIElement.VisibilityProperty, BindingMode.OneWay); } if (BindingOperations.IsDataBound(result, UIElement.IsEnabledProperty) == false) { RibbonControl.Bind(element, result, "IsEnabled", UIElement.IsEnabledProperty, BindingMode.OneWay); } return result; } /// <summary> /// Finds the top supported control /// </summary> /// <param name="visual">Visual</param> /// <param name="point">Point</param> /// <returns>Point</returns> public static FrameworkElement FindSupportedControl(Visual visual, Point point) { var result = VisualTreeHelper.HitTest(visual, point); if (result == null) { return null; } // Try to find in visual (or logical) tree var element = result.VisualHit as FrameworkElement; while (element != null) { if (IsSupported(element)) { return element; } var visualParent = VisualTreeHelper.GetParent(element) as FrameworkElement; var logicalParent = LogicalTreeHelper.GetParent(element) as FrameworkElement; element = visualParent ?? logicalParent; } return null; } #endregion } }
using System; using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Index; namespace Lucene.Net.Analysis { using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using System.IO; using AtomicReader = Lucene.Net.Index.AtomicReader; using Automaton = Lucene.Net.Util.Automaton.Automaton; using AutomatonTestUtil = Lucene.Net.Util.Automaton.AutomatonTestUtil; using BasicAutomata = Lucene.Net.Util.Automaton.BasicAutomata; using BasicOperations = Lucene.Net.Util.Automaton.BasicOperations; using BytesRef = Lucene.Net.Util.BytesRef; using CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; /* * 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 Document = Documents.Document; using Field = Field; using Fields = Lucene.Net.Index.Fields; using FieldType = FieldType; using IOUtils = Lucene.Net.Util.IOUtils; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using RegExp = Lucene.Net.Util.Automaton.RegExp; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestMockAnalyzer : BaseTokenStreamTestCase { /// <summary> /// Test a configuration that behaves a lot like WhitespaceAnalyzer </summary> [Test] public virtual void TestWhitespace() { Analyzer a = new MockAnalyzer(Random()); AssertAnalyzesTo(a, "A bc defg hiJklmn opqrstuv wxy z ", new string[] { "a", "bc", "defg", "hijklmn", "opqrstuv", "wxy", "z" }); AssertAnalyzesTo(a, "aba cadaba shazam", new string[] { "aba", "cadaba", "shazam" }); AssertAnalyzesTo(a, "break on whitespace", new string[] { "break", "on", "whitespace" }); } /// <summary> /// Test a configuration that behaves a lot like SimpleAnalyzer </summary> [Test] public virtual void TestSimple() { Analyzer a = new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true); AssertAnalyzesTo(a, "a-bc123 defg+hijklmn567opqrstuv78wxy_z ", new string[] { "a", "bc", "defg", "hijklmn", "opqrstuv", "wxy", "z" }); AssertAnalyzesTo(a, "aba4cadaba-Shazam", new string[] { "aba", "cadaba", "shazam" }); AssertAnalyzesTo(a, "break+on/Letters", new string[] { "break", "on", "letters" }); } /// <summary> /// Test a configuration that behaves a lot like KeywordAnalyzer </summary> [Test] public virtual void TestKeyword() { Analyzer a = new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false); AssertAnalyzesTo(a, "a-bc123 defg+hijklmn567opqrstuv78wxy_z ", new string[] { "a-bc123 defg+hijklmn567opqrstuv78wxy_z " }); AssertAnalyzesTo(a, "aba4cadaba-Shazam", new string[] { "aba4cadaba-Shazam" }); AssertAnalyzesTo(a, "break+on/Nothing", new string[] { "break+on/Nothing" }); // currently though emits no tokens for empty string: maybe we can do it, // but we don't want to emit tokens infinitely... AssertAnalyzesTo(a, "", new string[0]); } // Test some regular expressions as tokenization patterns /// <summary> /// Test a configuration where each character is a term </summary> [Test] public virtual void TestSingleChar() { var single = new CharacterRunAutomaton((new RegExp(".")).ToAutomaton()); Analyzer a = new MockAnalyzer(Random(), single, false); AssertAnalyzesTo(a, "foobar", new[] { "f", "o", "o", "b", "a", "r" }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 1, 2, 3, 4, 5, 6 }); CheckRandomData(Random(), a, 100); } /// <summary> /// Test a configuration where two characters makes a term </summary> [Test] public virtual void TestTwoChars() { CharacterRunAutomaton single = new CharacterRunAutomaton((new RegExp("..")).ToAutomaton()); Analyzer a = new MockAnalyzer(Random(), single, false); AssertAnalyzesTo(a, "foobar", new string[] { "fo", "ob", "ar" }, new int[] { 0, 2, 4 }, new int[] { 2, 4, 6 }); // make sure when last term is a "partial" match that End() is correct AssertTokenStreamContents(a.TokenStream("bogus", new StringReader("fooba")), new string[] { "fo", "ob" }, new int[] { 0, 2 }, new int[] { 2, 4 }, new int[] { 1, 1 }, new int?(5)); CheckRandomData(Random(), a, 100); } /// <summary> /// Test a configuration where three characters makes a term </summary> [Test] public virtual void TestThreeChars() { CharacterRunAutomaton single = new CharacterRunAutomaton((new RegExp("...")).ToAutomaton()); Analyzer a = new MockAnalyzer(Random(), single, false); AssertAnalyzesTo(a, "foobar", new string[] { "foo", "bar" }, new int[] { 0, 3 }, new int[] { 3, 6 }); // make sure when last term is a "partial" match that End() is correct AssertTokenStreamContents(a.TokenStream("bogus", new StringReader("fooba")), new string[] { "foo" }, new int[] { 0 }, new int[] { 3 }, new int[] { 1 }, new int?(5)); CheckRandomData(Random(), a, 100); } /// <summary> /// Test a configuration where word starts with one uppercase </summary> [Test] public virtual void TestUppercase() { CharacterRunAutomaton single = new CharacterRunAutomaton((new RegExp("[A-Z][a-z]*")).ToAutomaton()); Analyzer a = new MockAnalyzer(Random(), single, false); AssertAnalyzesTo(a, "FooBarBAZ", new string[] { "Foo", "Bar", "B", "A", "Z" }, new int[] { 0, 3, 6, 7, 8 }, new int[] { 3, 6, 7, 8, 9 }); AssertAnalyzesTo(a, "aFooBar", new string[] { "Foo", "Bar" }, new int[] { 1, 4 }, new int[] { 4, 7 }); CheckRandomData(Random(), a, 100); } /// <summary> /// Test a configuration that behaves a lot like StopAnalyzer </summary> [Test] public virtual void TestStop() { Analyzer a = new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET); AssertAnalyzesTo(a, "the quick brown a fox", new string[] { "quick", "brown", "fox" }, new int[] { 2, 1, 2 }); } /// <summary> /// Test a configuration that behaves a lot like KeepWordFilter </summary> [Test] public virtual void TestKeep() { CharacterRunAutomaton keepWords = new CharacterRunAutomaton(BasicOperations.Complement(Automaton.Union(Arrays.AsList(BasicAutomata.MakeString("foo"), BasicAutomata.MakeString("bar"))))); Analyzer a = new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true, keepWords); AssertAnalyzesTo(a, "quick foo brown bar bar fox foo", new string[] { "foo", "bar", "bar", "foo" }, new int[] { 2, 2, 1, 2 }); } /// <summary> /// Test a configuration that behaves a lot like LengthFilter </summary> [Test] public virtual void TestLength() { CharacterRunAutomaton length5 = new CharacterRunAutomaton((new RegExp(".{5,}")).ToAutomaton()); Analyzer a = new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, true, length5); AssertAnalyzesTo(a, "ok toolong fine notfine", new string[] { "ok", "fine" }, new int[] { 1, 2 }); } /// <summary> /// Test MockTokenizer encountering a too long token </summary> [Test] public virtual void TestTooLongToken() { Analyzer whitespace = new AnalyzerAnonymousInnerClassHelper(this); AssertTokenStreamContents(whitespace.TokenStream("bogus", new StringReader("test 123 toolong ok ")), new string[] { "test", "123", "toolo", "ng", "ok" }, new int[] { 0, 5, 9, 14, 17 }, new int[] { 4, 8, 14, 16, 19 }, new int?(20)); AssertTokenStreamContents(whitespace.TokenStream("bogus", new StringReader("test 123 toolo")), new string[] { "test", "123", "toolo" }, new int[] { 0, 5, 9 }, new int[] { 4, 8, 14 }, new int?(14)); } private class AnalyzerAnonymousInnerClassHelper : Analyzer { private readonly TestMockAnalyzer OuterInstance; public AnalyzerAnonymousInnerClassHelper(TestMockAnalyzer outerInstance) { this.OuterInstance = outerInstance; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer t = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false, 5); return new TokenStreamComponents(t, t); } } [Test] public virtual void TestLUCENE_3042() { string testString = "t"; Analyzer analyzer = new MockAnalyzer(Random()); Exception priorException = null; TokenStream stream = analyzer.TokenStream("dummy", new StringReader(testString)); try { stream.Reset(); while (stream.IncrementToken()) { // consume } stream.End(); } catch (Exception e) { priorException = e; } finally { IOUtils.CloseWhileHandlingException(priorException, stream); } AssertAnalyzesTo(analyzer, testString, new string[] { "t" }); } /// <summary> /// blast some random strings through the analyzer </summary> [Test] public virtual void TestRandomStrings() { CheckRandomData(Random(), new MockAnalyzer(Random()), AtLeast(1000)); } /// <summary> /// blast some random strings through differently configured tokenizers </summary> [Test, LongRunningTest, Timeout(int.MaxValue)] public virtual void TestRandomRegexps() { int iters = AtLeast(30); for (int i = 0; i < iters; i++) { CharacterRunAutomaton dfa = new CharacterRunAutomaton(AutomatonTestUtil.RandomAutomaton(Random())); bool lowercase = Random().NextBoolean(); int limit = TestUtil.NextInt(Random(), 0, 500); Analyzer a = new AnalyzerAnonymousInnerClassHelper2(this, dfa, lowercase, limit); CheckRandomData(Random(), a, 100); a.Dispose(); } } private class AnalyzerAnonymousInnerClassHelper2 : Analyzer { private readonly TestMockAnalyzer OuterInstance; private CharacterRunAutomaton Dfa; private bool Lowercase; private int Limit; public AnalyzerAnonymousInnerClassHelper2(TestMockAnalyzer outerInstance, CharacterRunAutomaton dfa, bool lowercase, int limit) { this.OuterInstance = outerInstance; this.Dfa = dfa; this.Lowercase = lowercase; this.Limit = limit; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer t = new MockTokenizer(reader, Dfa, Lowercase, Limit); return new TokenStreamComponents(t, t); } } [Test] public virtual void TestForwardOffsets() { int num = AtLeast(10000); for (int i = 0; i < num; i++) { string s = TestUtil.RandomHtmlishString(Random(), 20); StringReader reader = new StringReader(s); MockCharFilter charfilter = new MockCharFilter(reader, 2); MockAnalyzer analyzer = new MockAnalyzer(Random()); Exception priorException = null; TokenStream ts = analyzer.TokenStream("bogus", charfilter.input); try { ts.Reset(); while (ts.IncrementToken()) { ; } ts.End(); } catch (Exception e) { priorException = e; } finally { IOUtils.CloseWhileHandlingException(priorException, ts); } } } [Test] public virtual void TestWrapReader() { // LUCENE-5153: test that wrapping an analyzer's reader is allowed Random random = Random(); Analyzer @delegate = new MockAnalyzer(random); Analyzer a = new AnalyzerWrapperAnonymousInnerClassHelper(this, @delegate.Strategy, @delegate); CheckOneTerm(a, "abc", "aabc"); } private class AnalyzerWrapperAnonymousInnerClassHelper : AnalyzerWrapper { private readonly TestMockAnalyzer OuterInstance; private Analyzer @delegate; public AnalyzerWrapperAnonymousInnerClassHelper(TestMockAnalyzer outerInstance, ReuseStrategy getReuseStrategy, Analyzer @delegate) : base(getReuseStrategy) { this.OuterInstance = outerInstance; this.@delegate = @delegate; } protected override TextReader WrapReader(string fieldName, TextReader reader) { return new MockCharFilter(reader, 7); } protected override TokenStreamComponents WrapComponents(string fieldName, TokenStreamComponents components) { return components; } protected override Analyzer GetWrappedAnalyzer(string fieldName) { return @delegate; } } [Test] public virtual void TestChangeGaps() { // LUCENE-5324: check that it is possible to change the wrapper's gaps int positionGap = Random().Next(1000); int offsetGap = Random().Next(1000); Analyzer @delegate = new MockAnalyzer(Random()); Analyzer a = new AnalyzerWrapperAnonymousInnerClassHelper2(this, @delegate.Strategy, positionGap, offsetGap, @delegate); RandomIndexWriter writer = new RandomIndexWriter(Random(), NewDirectory()); Document doc = new Document(); FieldType ft = new FieldType(); ft.Indexed = true; ft.IndexOptions = FieldInfo.IndexOptions.DOCS_ONLY; ft.Tokenized = true; ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; ft.StoreTermVectorOffsets = true; doc.Add(new Field("f", "a", ft)); doc.Add(new Field("f", "a", ft)); writer.AddDocument(doc, a); AtomicReader reader = GetOnlySegmentReader(writer.Reader); Fields fields = reader.GetTermVectors(0); Terms terms = fields.Terms("f"); TermsEnum te = terms.Iterator(null); Assert.AreEqual(new BytesRef("a"), te.Next()); DocsAndPositionsEnum dpe = te.DocsAndPositions(null, null); Assert.AreEqual(0, dpe.NextDoc()); Assert.AreEqual(2, dpe.Freq()); Assert.AreEqual(0, dpe.NextPosition()); Assert.AreEqual(0, dpe.StartOffset()); int endOffset = dpe.EndOffset(); Assert.AreEqual(1 + positionGap, dpe.NextPosition()); Assert.AreEqual(1 + endOffset + offsetGap, dpe.EndOffset()); Assert.AreEqual(null, te.Next()); reader.Dispose(); writer.Dispose(); writer.w.Directory.Dispose(); } private class AnalyzerWrapperAnonymousInnerClassHelper2 : AnalyzerWrapper { private readonly TestMockAnalyzer OuterInstance; private int PositionGap; private int OffsetGap; private Analyzer @delegate; public AnalyzerWrapperAnonymousInnerClassHelper2(TestMockAnalyzer outerInstance, ReuseStrategy getReuseStrategy, int positionGap, int offsetGap, Analyzer @delegate) : base(getReuseStrategy) { this.OuterInstance = outerInstance; this.PositionGap = positionGap; this.OffsetGap = offsetGap; this.@delegate = @delegate; } protected override Analyzer GetWrappedAnalyzer(string fieldName) { return @delegate; } public override int GetPositionIncrementGap(string fieldName) { return PositionGap; } public override int GetOffsetGap(string fieldName) { return OffsetGap; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; namespace Lidgren.Library.Network { /// <summary> /// Helper class for encryption /// </summary> public sealed class NetEncryption { private byte[] m_symEncKeyBytes; private RSACryptoServiceProvider m_rsa; private XTEA m_xtea; private int[] m_symmetricKey; internal byte[] SymmetricEncryptionKeyBytes { get { return m_symEncKeyBytes; } } /// <summary> /// Generate an RSA keypair, divided into public and private parts /// </summary> public static void GenerateRandomKeyPair(out byte[] publicKey, out byte[] privateKey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters prm = rsa.ExportParameters(true); List<byte> pubKey = new List<byte>(131); pubKey.AddRange(prm.Exponent); pubKey.AddRange(prm.Modulus); List<byte> privKey = new List<byte>(448); privKey.AddRange(prm.D); // 128 privKey.AddRange(prm.DP); // 64 privKey.AddRange(prm.DQ); // 64 privKey.AddRange(prm.InverseQ); // 64 privKey.AddRange(prm.P); // 64 privKey.AddRange(prm.Q); // 64 publicKey = pubKey.ToArray(); privateKey = privKey.ToArray(); } public NetEncryption() { } internal void SetSymmetricKey(byte[] xteakey) { if (xteakey == null || xteakey.Length != 16) throw new NetException("Bad symmetric key length (" + xteakey.Length + ") must be 16!"); m_symEncKeyBytes = xteakey; m_symmetricKey = new int[4]; m_symmetricKey[0] = BitConverter.ToInt32(xteakey, 0); m_symmetricKey[1] = BitConverter.ToInt32(xteakey, 4); m_symmetricKey[2] = BitConverter.ToInt32(xteakey, 8); m_symmetricKey[3] = BitConverter.ToInt32(xteakey, 12); m_xtea = new XTEA(xteakey, 32); } /// <summary> /// for clients; pass null as privateKey /// </summary> internal void SetRSAKey(byte[] publicKey, byte[] privateKey) { m_rsa = new RSACryptoServiceProvider(); RSAParameters prm = new RSAParameters(); prm.Exponent = Extract(publicKey, 0, 3); prm.Modulus = Extract(publicKey, 3, 128); if (privateKey != null) { int ptr = 0; prm.D = Extract(privateKey, ptr, 128); ptr += 128; prm.DP = Extract(privateKey, ptr, 64); ptr += 64; prm.DQ = Extract(privateKey, ptr, 64); ptr += 64; prm.InverseQ = Extract(privateKey, ptr, 64); ptr += 64; prm.P = Extract(privateKey, ptr, 64); ptr += 64; prm.Q = Extract(privateKey, ptr, 64); ptr += 64; } m_rsa.ImportParameters(prm); // also generate random symmetric key byte[] newKey = new byte[16]; NetRandom.Default.NextBytes(newKey); SetSymmetricKey(newKey); } private static byte[] Extract(byte[] buf, int start, int len) { byte[] retval = new byte[len]; Array.Copy(buf, start, retval, 0, len); return retval; } /// <summary> /// Encrypt data using a public RSA key /// </summary> internal byte[] EncryptRSA(byte[] plainData) { return m_rsa.Encrypt(plainData, false); } /// <summary> /// Decrypt data using the public and private RSA key /// </summary> internal byte[] DecryptRSA(byte[] encryptedData) { try { return m_rsa.Decrypt(encryptedData, false); } catch (Exception ex) { if (NetBase.CurrentContext != null && NetBase.CurrentContext.Log != null) NetBase.CurrentContext.Log.Warning("Failed to Decrypt RSA: " + ex); return null; } } /// <summary> /// Append a CRC checksum and encrypt data in place using XTEA /// </summary> internal void EncryptSymmetric(NetBuffer buffer) { //string plain = Convert.ToBase64String(buffer.Data, 0, buffer.LengthBytes); int bufferLen = buffer.LengthBytes; // calculate number of pad bits int dataBits = buffer.LengthBits; int bitsNeeded = dataBits + 24; // 24 extra for crc and num-pad-bits int totalBits = bitsNeeded + (64 - (bitsNeeded % 64)); int padBits = totalBits - bitsNeeded; // write to ensure zeroes in buffer (crc and num-pad-bits space) buffer.Write((uint)0, 24); if (padBits > 0) buffer.Write((ulong)0, padBits); int writePadBitsPosition = buffer.LengthBits - 8; // write crc ushort crc = Checksum.Adler16(buffer.Data, 0, buffer.LengthBytes); buffer.ResetWritePointer(dataBits); buffer.Write(crc); // write num-pad-bits in LAST byte buffer.ResetWritePointer(writePadBitsPosition); buffer.Write((byte)padBits); // encrypt in place int ptr = 0; bufferLen = buffer.LengthBytes; while (ptr < bufferLen) { m_xtea.EncryptBlock(buffer.Data, ptr, buffer.Data, ptr); ptr += 8; } return; } /// <summary> /// Decrypt using XTEA algo and verify CRC /// </summary> /// <returns>true for success, false for failure</returns> internal bool DecryptSymmetric(NetBuffer buffer) { int bufLen = buffer.LengthBytes; if (bufLen % 8 != 0) { if (NetBase.CurrentContext != null && NetBase.CurrentContext.Log != null) NetBase.CurrentContext.Log.Info("Bad buffer size in DecryptSymmetricInPlace()"); return false; } //NetBase.CurrentContext.Log.Debug.Debug("Decrypting using key: " + Convert.ToBase64String(m_xtea.Key)); // decrypt for (int i = 0; i < bufLen; i += 8) m_xtea.DecryptBlock(buffer.Data, i, buffer.Data, i); int numPadBits = buffer.Data[bufLen - 1]; buffer.Data[bufLen - 1] = 0; // zap for correct crc calculation int dataBits = (bufLen * 8) - (24 + numPadBits); // include pad and crc buffer.ResetReadPointer(dataBits); ushort statedCrc = buffer.ReadUInt16(); // zap crc to be able to compare buffer.ResetWritePointer(dataBits); buffer.Write((ushort)0); ushort dataCrc = Checksum.Adler16(buffer.Data, 0, bufLen); //NetBase.CurrentContext.Log.Debug("Plain (len " + bufLen + "): " + Convert.ToBase64String(buffer.Data, 0, bufLen) + " Stated CRC: " + statedCrc + " Calc: " + realCrc); if (statedCrc != dataCrc) { if (NetBase.CurrentContext != null && NetBase.CurrentContext.Log != null) NetBase.CurrentContext.Log.Warning("CRC failure; expected " + dataCrc + " found " + statedCrc + " dropping packet!"); return false; } // clean up buffer.LengthBits = dataBits; buffer.ResetReadPointer(); return true; } public static bool SimpleUnitTest() { // encryption test NetEncryption enc = new NetEncryption(); byte[] key = new byte[16]; NetRandom.Default.NextBytes(key); enc.SetSymmetricKey(key); byte[] data = Encoding.ASCII.GetBytes("Michael"); // 7 bytes byte[] correct = new byte[data.Length]; data.CopyTo(correct, 0); NetBuffer buf = new NetBuffer(data); enc.EncryptSymmetric(buf); bool ok = enc.DecryptSymmetric(buf); if (!ok) return false; // compare if (buf.LengthBytes != correct.Length) return false; for (int i = 0; i < correct.Length; i++) if (buf.Data[i] != correct[i]) return false; return true; } } }
using System; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Schema.Testing.Documents; using Shouldly; using Xunit; using Issue = Marten.Schema.Testing.Documents.Issue; namespace Marten.Schema.Testing { public class DocumentCleanerTests : IntegrationContext { private IDocumentCleaner theCleaner => theStore.Advanced.Clean; [Fact] public void clean_table() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); theSession.Store(new Target { Number = 3 }); theSession.Store(new Target { Number = 4 }); theSession.Store(new Target { Number = 5 }); theSession.Store(new Target { Number = 6 }); theSession.SaveChanges(); theSession.Dispose(); theCleaner.DeleteDocumentsByType(typeof(Target)); using (var session = theStore.QuerySession()) { session.Query<Target>().Count().ShouldBe(0); } } [Fact] public void delete_all_documents() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); theSession.Store(new User()); theSession.Store(new Company()); theSession.Store(new Issue()); theSession.SaveChanges(); theSession.Dispose(); theCleaner.DeleteAllDocuments(); using (var session = theStore.QuerySession()) { session.Query<Target>().Count().ShouldBe(0); session.Query<User>().Count().ShouldBe(0); session.Query<Issue>().Count().ShouldBe(0); session.Query<Company>().Count().ShouldBe(0); } } [Fact] public async Task completely_remove_document_type() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); theSession.SaveChanges(); theSession.Dispose(); var tableName = theStore.Storage.MappingFor(typeof(Target)).TableName; (await theStore.Tenancy.Default.DocumentTables()).Contains(tableName) .ShouldBeTrue(); theCleaner.CompletelyRemove(typeof(Target)); (await theStore.Tenancy.Default.DocumentTables()).Contains(tableName) .ShouldBeFalse(); } [Fact] public async Task completely_remove_document_removes_the_upsert_command_too() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); await theSession.SaveChangesAsync(); var upsertName = theStore.Storage.MappingFor(typeof(Target)).As<DocumentMapping>().UpsertFunction; (await theStore.Tenancy.Default.Functions()).ShouldContain(upsertName); theCleaner.CompletelyRemove(typeof(Target)); (await theStore.Tenancy.Default.Functions()).ShouldNotContain(upsertName); } [Fact] public async Task completely_remove_everything() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); theSession.Store(new User()); theSession.Store(new Company()); theSession.Store(new Issue()); await theSession.SaveChangesAsync(); theSession.Dispose(); await theCleaner.CompletelyRemoveAllAsync(); var tables = await theStore.Tenancy.Default.DocumentTables(); tables.ShouldBeEmpty(); var functions = await theStore.Tenancy.Default.Functions(); functions.Where(x => x.Name != "mt_immutable_timestamp" || x.Name != "mt_immutable_timestamptz") .ShouldBeEmpty(); } [Fact] public void delete_all_event_data() { var streamId = Guid.NewGuid(); theSession.Events.StartStream<Quest>(streamId, new QuestStarted()); theSession.SaveChanges(); theCleaner.DeleteAllEventData(); theSession.Events.QueryRawEventDataOnly<QuestStarted>().ShouldBeEmpty(); theSession.Events.FetchStream(streamId).ShouldBeEmpty(); } [Fact] public async Task delete_all_event_data_async() { var streamId = Guid.NewGuid(); theSession.Events.StartStream<Quest>(streamId, new QuestStarted()); await theSession.SaveChangesAsync(); await theCleaner.DeleteAllEventDataAsync(); theSession.Events.QueryRawEventDataOnly<QuestStarted>().ShouldBeEmpty(); (await theSession.Events.FetchStreamAsync(streamId)).ShouldBeEmpty(); } private static void ShouldBeEmpty<T>(T[] documentTables) { var stillInDatabase = string.Join(",", documentTables); documentTables.Any().ShouldBeFalse(stillInDatabase); } [Fact] public void delete_except_types() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); theSession.Store(new User()); theSession.Store(new Company()); theSession.Store(new Issue()); theSession.SaveChanges(); theSession.Dispose(); theCleaner.DeleteDocumentsExcept(typeof(Target), typeof(User)); using (var session = theStore.OpenSession()) { // Not cleaned off session.Query<Target>().Count().ShouldBe(2); session.Query<User>().Count().ShouldBe(1); // Should be cleaned off session.Query<Issue>().Count().ShouldBe(0); session.Query<Company>().Count().ShouldBe(0); } } [Fact] public async Task delete_except_types_async() { theSession.Store(new Target { Number = 1 }); theSession.Store(new Target { Number = 2 }); theSession.Store(new User()); theSession.Store(new Company()); theSession.Store(new Issue()); await theSession.SaveChangesAsync(); theSession.Dispose(); await theCleaner.DeleteDocumentsExceptAsync(typeof(Target), typeof(User)); using var session = theStore.OpenSession(); // Not cleaned off session.Query<Target>().Count().ShouldBe(2); session.Query<User>().Count().ShouldBe(1); // Should be cleaned off session.Query<Issue>().Count().ShouldBe(0); session.Query<Company>().Count().ShouldBe(0); } [Fact] public async Task CanCleanSequences() { StoreOptions(opts => { opts.Events.AddEventType(typeof(MembersJoined)); }); await theStore.Schema.ApplyAllConfiguredChangesToDatabase(); var allSchemas = theStore.Storage.AllSchemaNames(); int GetSequenceCount(IDocumentStore store) { using var session = store.QuerySession(); return session.Query<int>(@"select count(*) from information_schema.sequences s where s.sequence_name like ? and s.sequence_schema = any(?);", "mt_%", allSchemas).First(); } GetSequenceCount(theStore).ShouldBeGreaterThan(0); theStore.Advanced.Clean.CompletelyRemoveAll(); GetSequenceCount(theStore).ShouldBe(0); } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Collision; using FlatRedBall.Math.Geometry; using FlatRedBall.Math.Splines; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; using FlatRedBall.Localization; using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; using GlueTestProject.TestFramework; using FlatRedBall.Math; namespace GlueTestProject.Screens { public partial class CollisionScreen { void CustomInitialize() { MovableRectangle.X = 1; MovableRectangle.CollideAgainstMove(ImmovableRectangle, 0, 1); if (MovableRectangle.X == 1) { throw new Exception("CollideAgainstMove didn't move the movable rectangle"); } if (ImmovableRectangle.X != 0) { throw new Exception("CollideAgainstMove moved an object when colliding against a 0 mass object"); } TestPositiveInfinitySecondCollisionMass(); TestPositiveInfinityFirstObjectCollisionMass(); Test_L_RepositonDirection(); CreateCollisionRelationships(); TestEntityListVsShapeCollection(); TestEntityVsShapeCollection(); TestNullSubcollision(); TestCollidedThisFrame(); TestCollisionRelationshipPreventDoubleCollision(); } private void TestCollisionRelationshipPreventDoubleCollision() { PositionedObjectList<Entities.CollidableEntity> bulletList = new PositionedObjectList<Entities.CollidableEntity>(); bulletList.Add(new Entities.CollidableEntity()); PositionedObjectList<Entities.CollidableEntity> enemyList = new PositionedObjectList<Entities.CollidableEntity>(); enemyList.Add(new Entities.CollidableEntity()); enemyList.Add(new Entities.CollidableEntity()); var collisionRelationship = CollisionManager.Self.CreateRelationship(bulletList, enemyList); int numberOfHits = 0; collisionRelationship.CollisionOccurred += (bullet, enemy) => { numberOfHits++; bullet.Destroy(); }; collisionRelationship.DoCollisions(); numberOfHits.ShouldBe(1, "because the bullet is destroyed on the first collision, so it shouldn't hit the second enemy"); while(enemyList.Count > 0) { enemyList[0].Destroy(); } } private void TestPositiveInfinitySecondCollisionMass() { // try positive infinity: MovableRectangle.X = 1; MovableRectangle.CollideAgainstMove(ImmovableRectangle, 1, float.PositiveInfinity); if (MovableRectangle.X == 1) { throw new Exception("CollideAgainstMove didn't move the movable rectangle"); } if (ImmovableRectangle.X != 0) { throw new Exception("CollideAgainstMove moved an object with positive infinity"); } } private void TestPositiveInfinityFirstObjectCollisionMass() { // Try positive infinity, call with the immovable: MovableRectangle.X = 1; ImmovableRectangle.CollideAgainstMove(MovableRectangle, float.PositiveInfinity, 1); if (MovableRectangle.X == 1) { throw new Exception("CollideAgainstMove didn't move the movable rectangle"); } if (ImmovableRectangle.X != 0) { throw new Exception("CollideAgainstMove moved an object with positive infinity"); } } private void TestCollidedThisFrame() { var firstEntity = new Entities.CollidableEntity(); var secondEntity = new Entities.CollidableEntity(); var relationship = CollisionManager.Self.CreateRelationship(firstEntity, secondEntity); relationship.CollidedThisFrame.ShouldBe(false); var collided = relationship.DoCollisions(); collided.ShouldBe(true); relationship.CollidedThisFrame.ShouldBe(true); firstEntity.X += 10000; firstEntity.ForceUpdateDependenciesDeep(); collided = relationship.DoCollisions(); collided.ShouldBe(false); relationship.CollidedThisFrame.ShouldBe(false); firstEntity.Destroy(); secondEntity.Destroy(); } private void TestEntityVsShapeCollection() { var singleEntity = new Entities.CollidableEntity(); // for now just testing that the method exists: var relationship = CollisionManager.Self.CreateRelationship(singleEntity, ShapeCollectionInstance); CollisionManager.Self.Relationships.Remove(relationship); singleEntity.Destroy(); } private void TestNullSubcollision() { CollisionEntityList[0].Collision.ShouldNotBe(null); // event collision, both null var relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetFirstSubCollision(item => item.NullCollidableEntityInstance); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.CollisionOccurred += (first, second) => { }; relationship.DoCollisions(); // Move collision, both null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetFirstSubCollision(item => item.NullCollidableEntityInstance); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetMoveCollision(1, 1); relationship.DoCollisions(); // Bounce collision, both null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetFirstSubCollision(item => item.NullCollidableEntityInstance); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetBounceCollision(1, 1, 1); relationship.DoCollisions(); // event collision, second null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.CollisionOccurred += (first, second) => { }; relationship.DoCollisions(); // Move collision, second null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetMoveCollision(1, 1); relationship.DoCollisions(); // Bounce collision, second null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetBounceCollision(1, 1, 1); relationship.DoCollisions(); } private void CreateCollisionRelationships() { var subcollision = CollisionManager.Self.CreateRelationship(PlayerList, ShipList); var selfCollidingRelationship = CollisionManager.Self.CreateRelationship(SelfCollisionList, SelfCollisionList); selfCollidingRelationship.SetMoveCollision(1, 1); var fullVsEmptyRelationship = CollisionManager.Self.CreateRelationship(PlayerList, EmptyList1); var emptyVsFullRelationship = CollisionManager.Self.CreateRelationship(EmptyList1, PlayerList); var emptyVsEmptyRelationship = CollisionManager.Self.CreateRelationship(EmptyList1, EmptyList2); var emptyVsSameEmptyRelationship = CollisionManager.Self.CreateRelationship(EmptyList1, EmptyList1); } private void TestEntityListVsShapeCollection() { var entityVsShapeCollection = CollisionManager.Self.CreateRelationship(CollidableList, ShapeCollectionInstance); List<Entities.CollidableEntity> collidedEntities = new List<Entities.CollidableEntity>(); entityVsShapeCollection.CollisionOccurred += (entity, shapeCollection) => { collidedEntities.Add(entity); }; entityVsShapeCollection.DoCollisions(); collidedEntities.Contains(At0).ShouldBe(true); collidedEntities.Contains(At100).ShouldBe(true); collidedEntities.Contains(At200).ShouldBe(true); collidedEntities.Contains(At400).ShouldBe(false); } private void Test_L_RepositonDirection() { ShapeCollection rectangles = new ShapeCollection(); // This tests the following bug: // https://trello.com/c/twwOTKFz/411-l-shaped-corners-can-cause-entities-to-teleport-through-despite-using-proper-reposition-directions // make corner first so it is tested first var corner = new AxisAlignedRectangle(); corner.X = 0; corner.Y = 0; corner.Width = 32; corner.Height = 32; corner.RepositionDirections = RepositionDirections.Left | RepositionDirections.Down; corner.RepositionHalfSize = true; rectangles.AxisAlignedRectangles.Add(corner); var top = new AxisAlignedRectangle(); top.X = 0; top.Y = 32; top.Width = 32; top.Height = 32; top.RepositionDirections = RepositionDirections.Left | RepositionDirections.Right; rectangles.AxisAlignedRectangles.Add(top); var right = new AxisAlignedRectangle(); right.X = 32; right.Y = 0; right.Width = 32; right.Height = 32; right.RepositionDirections = RepositionDirections.Up | RepositionDirections.Down; rectangles.AxisAlignedRectangles.Add(right); var movable = new AxisAlignedRectangle(); movable.X = 32 - 1; movable.Y = 32 - 1; movable.Width = 32; movable.Height = 32; movable.CollideAgainstMove(rectangles, 0, 1); movable.X.ShouldBeGreaterThan(31); movable.Y.ShouldBeGreaterThan(31); } void CustomActivity(bool firstTimeCalled) { var shouldContinue = this.ActivityCallCount > 5; // give the screen a chance to call if(!firstTimeCalled) { var areAllDifferent = C1.X != C2.X && C2.X != C3.X && C3.X != C4.X; areAllDifferent.ShouldBe(true, "because all items in this list should self move collide"); } if (shouldContinue) { IsActivityFinished = true; } } void CustomDestroy() { CollisionManager.Self.Relationships.Count.ShouldBe(0); } static void CustomLoadStaticContent(string contentManagerName) { } } }
/** * \file GameManager.cs * * \brief Implements the GameManager class. */ using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Imaging; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Input; using API.Framework; using API; namespace SpaceShips { public class GameManager : GameActor { public UInt32 cnt = 0; private int cursor = 0; private bool analogBlock = true; private bool arcade = true; private Font font61; public Dictionary<string, SimpleSprite> gameManagerSprites; /** * \fn GameManager(Game gs, string name) * * \brief Default constructor. * * Creates the sprites of each texture and set to the start position. * * \param gs Variable that contains the game framework class. * \param name Name of the object. */ public GameManager(Game gs, string name) : base (gs, name) { SimpleSprite sprite; gameManagerSprites = new Dictionary<string, SimpleSprite>(); sprite = new SimpleSprite(gs.Graphics, gs.textureMenu, 0, 38, gs.textureMenu.Width,75, gs.textureMenu.Width, 37, 90.0f, new Vector2(gs.rectScreen.Width/2-37*2, gs.rectScreen.Height/2+gs.textureMenu.Width/2)); gameManagerSprites.Add("title", sprite); sprite = new SimpleSprite(gs.Graphics, gs.textureMenu, 0,0,gs.textureMenu.Width,37, gs.textureMenu.Width, 37, 90.0f, new Vector2(gameManagerSprites["title"].Position.X+128, gameManagerSprites["title"].Position.Y+10)); gameManagerSprites.Add("pressStart", sprite); sprite = new SimpleSprite(gs.Graphics, gs.textureMenu, 0,gs.textureMenu.Height-37, gs.textureMenu.Width,gs.textureMenu.Height, gs.textureMenu.Width, 37, 90.0f, new Vector2(gameManagerSprites["title"].Position.X+128, gameManagerSprites["title"].Position.Y-50)); gameManagerSprites.Add("arcade", sprite); sprite = new SimpleSprite(gs.Graphics, gs.textureMenu, 0,114,gs.textureMenu.Width,151, gs.textureMenu.Width, 37, 90.0f, new Vector2(gameManagerSprites["arcade"].Position.X+64, gameManagerSprites["title"].Position.Y-30)); gameManagerSprites.Add("survival", sprite); sprite = new SimpleSprite(gs.Graphics, gs.textureMenu, 0,76,gs.textureMenu.Width,113, gs.textureMenu.Width, 37, 90.0f, new Vector2(gs.rectScreen.Width/2-37*2, gs.rectScreen.Height/2+235/2)); gameManagerSprites.Add("gameover", sprite); font61 = new Font("/Application/assets/fonts/Pixel-li.ttf", 61, FontStyle.Regular); } /** * \fn Update() * * \brief Overrided update method. * * Handle the differents game states. */ public override void Update() { #if DEBUG // gs.debugStringScore.Clear(); // gs.debugStringShip.Clear(); // // string str = String.Format("Score: {0:d8}", gs.Score); // gs.debugStringScore.SetPosition(new Vector3( gs.rectScreen.Width/2-(str.Length*10/2), 2, 0)); // gs.debugStringScore.WriteLine(str); // // str = String.Format("Ships:{0}", gs.NumShips); // gs.debugStringShip.SetPosition(new Vector3( gs.rectScreen.Width-(str.Length*10), 2, 0)); // gs.debugStringShip.WriteLine(str); #endif switch(gs.Step) { case Game.StepType.Opening: break; case Game.StepType.Title: if (gs.playerInput.StartButton()) { gs.Step = Game.StepType.StartMenu; gs.audioManager.playSound("systemSelect"); } break; case Game.StepType.StartMenu: #if DEBUG gs.debugString.WriteLine("StartMenu"); #endif // Cursor handler cursorHandler(); // Menu handler switch (cursor) { case 0: gameManagerSprites["arcade"].SetColor(1.0f, 1.0f, 1.0f, 0.75f); gameManagerSprites["survival"].SetColor(1.0f, 1.0f, 1.0f, 1.0f); if (gs.playerInput.SpecialButton()) { arcade = true; gs.audioManager.playSound("systemSelect"); gs.Step = Game.StepType.SelectPlayer; } break; case 1: gameManagerSprites["arcade"].SetColor(1.0f, 1.0f, 1.0f, 1.0f); gameManagerSprites["survival"].SetColor(1.0f, 1.0f, 1.0f, 0.75f); if (gs.playerInput.SpecialButton()) { arcade = false; gs.audioManager.playSound("systemSelect"); gs.Step = Game.StepType.SelectPlayer; cursor = 0; } break; default: break; } break; case Game.StepType.SelectPlayer: if (gs.playerInput.SpecialButton()) { PlayerSelect playerSelect = (PlayerSelect)gs.Root.Search("playerSelect"); Player player = (Player)gs.Root.Search("Player"); player.Initialize(playerSelect.SelectShip()); gs.Root.Search("bulletManager").Children.Clear(); gs.Root.Search("enemyManager").Children.Clear(); gs.Root.Search("enemyBulletManager").Children.Clear(); gs.GameCounter = 0; gs.NumShips = 3; gs.Score = 0; if (arcade) { gs.levelParser.LoadLevel(gs, "/Application/assets/levels/Level1.tmx"); gs.audioManager.ChangeSong("BlueSpace.mp3"); } else { EnemyCommander enemyCommander =(EnemyCommander)gs.Root.Search("enemyCommander"); enemyCommander.Status = Actor.ActorStatus.Action; enemyCommander.Initialize(); gs.audioManager.ChangeSong("LongSeamlessLoop.mp3"); } gs.Root.Search("playerSelect").Children.Clear(); gs.Step = Game.StepType.Gameplay; } break; case Game.StepType.Gameplay: #if DEBUG gs.debugString.WriteLine("Gameplay"); #endif // Game over if player stock falls to zero. if(gs.NumShips <= 0) { gs.Step= Game.StepType.GameOver; gs.audioManager.PauseSong(); cnt=0; } if (gs.playerInput.StartButton()) { gs.Step = Game.StepType.Pause; pause(); } ++gs.GameCounter; if (gs.appCounter % 100 == 0) System.GC.Collect(); break; case Game.StepType.Pause: #if DEBUG gs.debugString.WriteLine("Pause"); #endif var texture = Text.createTexture("Pause", font61, 0xffff0000); var textSprite = new TextSprite(texture, gs.rectScreen.Width/2-texture.Height/2 , gs.rectScreen.Height/2+texture.Width/2, 0.5f, 0.5f, -90.0f, 1.0f, 1.0f); gs.textList.Add(textSprite); cursorHandler(); switch (cursor) { case 0: if (gs.playerInput.SpecialButton()) { gs.audioManager.playSound("systemSelect"); gs.Step = Game.StepType.Gameplay; resume(); } gs.textList.Add(textSprite); texture = Text.createTexture("Continue", font61, 0xbfff0000); textSprite = new TextSprite(texture, textSprite.PositionX+texture.Height*2, gs.rectScreen.Height/2+texture.Width/2,0.5f, 0.5f, -90.0f, 1.0f, 1.0f); gs.textList.Add(textSprite); texture = Text.createTexture("Exit", font61, 0xffff0000); textSprite = new TextSprite(texture, textSprite.PositionX+texture.Height, gs.rectScreen.Height/2+texture.Width/2,0.5f, 0.5f, -90.0f, 1.0f, 1.0f); gs.textList.Add(textSprite); break; case 1: if (gs.playerInput.SpecialButton()) { gs.audioManager.playSound("systemSelect"); gs.Root.Search("Map").Status = Actor.ActorStatus.Action; gameOver(); gs.NumShips=0; cursor = 0; } gs.textList.Add(textSprite); texture = Text.createTexture("Continue", font61, 0xffff0000); textSprite = new TextSprite(texture, textSprite.PositionX+texture.Height*2, gs.rectScreen.Height/2+texture.Width/2,0.5f, 0.5f, -90.0f, 1.0f, 1.0f); gs.textList.Add(textSprite); texture = Text.createTexture("Exit", font61, 0xbfff0000); textSprite = new TextSprite(texture, textSprite.PositionX+texture.Height, gs.rectScreen.Height/2+texture.Width/2,0.5f, 0.5f, -90.0f, 1.0f, 1.0f); gs.textList.Add(textSprite); break; default: break; } if (gs.playerInput.StartButton()) { gs.Step = Game.StepType.Gameplay; resume(); } texture.Dispose(); break; case Game.StepType.GameOver: #if DEBUG gs.debugString.WriteLine("GameOver"); #endif GameUI gameUI = (GameUI)gs.Root.Search("gameUI"); if(gs.playerInput.StartButton()) { PlayerSelect playerSelect = (PlayerSelect)gs.Root.Search("playerSelect"); Player player =(Player)gs.Root.Search("Player"); player.Status = Actor.ActorStatus.Action; player.Initialize(playerSelect.SelectShip()); player.playerStatus = Player.PlayerStatus.Explosion; gameUI.ResetCountdown(); gs.NumShips = 3; gs.audioManager.ResumeSong(); gs.Step = Game.StepType.Gameplay; } else if(gameUI.countdown == 9) { gameOver(); } break; default: throw new Exception("default in StepType."); } base.Update(); } private void pause() { gs.Root.Search("Player").Status = Actor.ActorStatus.Rest; foreach (var child in gs.Root.Search("enemyManager").Children) child.Status = Actor.ActorStatus.Rest; foreach (var child in gs.Root.Search("effectManager").Children) child.Status = Actor.ActorStatus.Rest; foreach (var child in gs.Root.Search("bulletManager").Children) child.Status = Actor.ActorStatus.Rest; foreach (var child in gs.Root.Search("enemyBulletManager").Children) child.Status = Actor.ActorStatus.Rest; gs.Root.Search("Map").Status = Actor.ActorStatus.Rest; gs.Root.Search("enemyCommander").Status = Actor.ActorStatus.Rest; } private void resume() { gs.Root.Search("Player").Status = Actor.ActorStatus.Action; gs.Root.Search("Map").Status = Actor.ActorStatus.Action; foreach (var child in gs.Root.Search("enemyManager").Children) child.Status = Actor.ActorStatus.Action; foreach (var child in gs.Root.Search("effectManager").Children) child.Status = Actor.ActorStatus.Action; foreach (var child in gs.Root.Search("bulletManager").Children) child.Status = Actor.ActorStatus.Action; foreach (var child in gs.Root.Search("enemyBulletManager").Children) child.Status = Actor.ActorStatus.Action; gs.Root.Search("enemyCommander").Status = Actor.ActorStatus.Action; } private void cursorHandler() { if (gs.playerInput.LeftRightAxis() < 0.0f && analogBlock) { analogBlock = false; gs.audioManager.playSound("systemSelect"); if (cursor==0) cursor = 1; else cursor = 0; } else if (gs.playerInput.LeftRightAxis() > 0.0f && analogBlock) { analogBlock = false; gs.audioManager.playSound("systemSelect"); if (cursor==1) cursor = 0; else cursor = 1; } if (gs.playerInput.LeftRightAxis() == 0.0f) analogBlock = true; } private void gameOver() { gs.Root.Search("Player").Children.Clear(); gs.Root.Search("enemyManager").Children.Clear(); gs.Root.Search("enemyBulletManager").Children.Clear(); gs.audioManager.ChangeSong("Music1.mp3"); if (!arcade) { EnemyCommander enemyCommander =(EnemyCommander)gs.Root.Search("enemyCommander"); enemyCommander.Status = Actor.ActorStatus.Rest; enemyCommander.resetWave(); } GameUI gameUI = (GameUI)gs.Root.Search("gameUI"); gameUI.ResetCountdown(); gs.Step= Game.StepType.Title; System.GC.Collect(); } } }
// // RescanPipeline.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Unix; using Hyena; using Hyena.Jobs; using Hyena.Collections; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.Sources; using Banshee.Collection.Database; using Banshee.Library; using Banshee.Metadata; using Banshee.ServiceStack; namespace Banshee.Collection { // Goals: // 1. Add new files that are on disk but not in the library // 2. Find the updated location of files that were moved // 3. Update metadata for files that were changed since we last scanned/imported // 4. Remove tracks that aren't on disk and weren't found to have moved // // Approach: // 1. For each file in the source's directory, find orphaned db track if any, or add if new // and update if modified; update the LastScannedAt stamp // 2. Remove all db tracks from the database that weren't scanned (LastScannedAt < scan_started) public class RescanPipeline : QueuePipeline<string> { private DateTime scan_started; private PrimarySource psource; private BatchUserJob job; private TrackSyncPipelineElement track_sync; private Func<int, bool> remove_confirmation; private readonly int MAX_NOWARN_TRACKS_REMOVAL = 50; public RescanPipeline (LibrarySource psource, Func<int, bool> removeConfirmation) : base () { this.psource = psource; scan_started = DateTime.Now; remove_confirmation = removeConfirmation; AddElement (new Banshee.IO.DirectoryScannerPipelineElement ()); AddElement (track_sync = new TrackSyncPipelineElement (psource, scan_started)); Finished += OnFinished; BuildJob (); Enqueue (psource.BaseDirectory); } private void BuildJob () { job = new BatchUserJob (Catalog.GetString ("Rescanning {0} of {1}"), "system-search", "gtk-find"); job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database); job.PriorityHints = PriorityHints.SpeedSensitive; job.CanCancel = true; job.CancelRequested += delegate { cancelled = true; Cancel (); }; track_sync.ProcessedItem += delegate { job.Total = track_sync.TotalCount; job.Completed = track_sync.ProcessedCount; job.Status = track_sync.Status; }; job.Register (); } private bool cancelled = false; private void OnFinished (object o, EventArgs args) { job.Finish (); if (cancelled || remove_confirmation == null) { return; } //Hyena.Log.DebugFormat ("Have {0} items before delete", ServiceManager.DbConnection.Query<int>("select count(*) from coretracks where primarysourceid=?", psource.DbId)); // Delete tracks that are under the BaseDirectory and that weren't rescanned just now string condition = String.Format ( @"WHERE PrimarySourceID = ? AND {0} LIKE ? ESCAPE '\' AND {1} IS NOT NULL AND {1} < ?", Banshee.Query.BansheeQuery.UriField.Column, "CoreTracks.LastSyncedStamp" ); string uri = Hyena.StringUtil.EscapeLike (new SafeUri (psource.BaseDirectoryWithSeparator).AbsoluteUri) + "%"; int remove_count = ServiceManager.DbConnection.Query<int> ( String.Format (@"SELECT COUNT('x') FROM CoreTracks {0}", condition), psource.DbId, uri, scan_started); if (remove_count > MAX_NOWARN_TRACKS_REMOVAL) { if (!remove_confirmation (remove_count)) { Refresh (); return; } } if (remove_count > 0) { ServiceManager.DbConnection.Execute (String.Format (@"BEGIN; DELETE FROM CorePlaylistEntries WHERE TrackID IN (SELECT TrackID FROM CoreTracks {0}); DELETE FROM CoreSmartPlaylistEntries WHERE TrackID IN (SELECT TrackID FROM CoreTracks {0}); DELETE FROM CoreTracks {0}; COMMIT", condition), psource.DbId, uri, scan_started, psource.DbId, uri, scan_started, psource.DbId, uri, scan_started ); } // TODO prune artists/albums Refresh (); //Hyena.Log.DebugFormat ("Have {0} items after delete", ServiceManager.DbConnection.Query<int>("select count(*) from coretracks where primarysourceid=?", psource.DbId)); } private void Refresh () { psource.Reload (); psource.NotifyTracksChanged (); } } public class TrackSyncPipelineElement : QueuePipelineElement<string> { private PrimarySource psource; private DateTime scan_started; private HyenaSqliteCommand fetch_command, fetch_similar_command; private string status; public string Status { get { return status; } } public TrackSyncPipelineElement (PrimarySource psource, DateTime scan_started) : base () { this.psource = psource; this.scan_started = scan_started; fetch_command = DatabaseTrackInfo.Provider.CreateFetchCommand (String.Format ( "CoreTracks.PrimarySourceID = ? AND {0} = ? LIMIT 1", Banshee.Query.BansheeQuery.UriField.Column)); fetch_similar_command = DatabaseTrackInfo.Provider.CreateFetchCommand ( "CoreTracks.PrimarySourceID = ? AND CoreTracks.LastSyncedStamp < ? AND CoreTracks.MetadataHash = ?"); } protected override string ProcessItem (string file_path) { if (!DatabaseImportManager.IsWhiteListedFile (file_path)) { return null; } // Hack to ignore Podcast files if (file_path.Contains ("Podcasts")) { return null; } //Hyena.Log.DebugFormat ("Rescanning item {0}", file_path); try { SafeUri uri = new SafeUri (file_path); using (var reader = ServiceManager.DbConnection.Query (fetch_command, psource.DbId, uri.AbsoluteUri)) { if (reader.Read () ) { //Hyena.Log.DebugFormat ("Found it in the db!"); DatabaseTrackInfo track = DatabaseTrackInfo.Provider.Load (reader); MergeIfModified (track); // Either way, update the LastSyncStamp track.LastSyncedStamp = DateTime.Now; track.Save (false); status = String.Format ("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle); } else { // This URI is not in the database - try to find it based on MetadataHash in case it was simply moved DatabaseTrackInfo track = new DatabaseTrackInfo (); Banshee.Streaming.StreamTagger.TrackInfoMerge (track, uri); using (var similar_reader = ServiceManager.DbConnection.Query ( fetch_similar_command, psource.DbId, scan_started, track.MetadataHash)) { DatabaseTrackInfo similar_track = null; while (similar_reader.Read ()) { similar_track = DatabaseTrackInfo.Provider.Load (similar_reader); if (!Banshee.IO.File.Exists (similar_track.Uri)) { //Hyena.Log.DebugFormat ("Apparently {0} was moved to {1}", similar_track.Uri, file_path); similar_track.Uri = uri; MergeIfModified (similar_track); similar_track.LastSyncedStamp = DateTime.Now; similar_track.Save (false); status = String.Format ("{0} - {1}", similar_track.DisplayArtistName, similar_track.DisplayTrackTitle); break; } similar_track = null; } // If we still couldn't find it, try to import it if (similar_track == null) { //Hyena.Log.DebugFormat ("Couldn't find it, so queueing to import it"); status = System.IO.Path.GetFileNameWithoutExtension (file_path); ServiceManager.Get<Banshee.Library.LibraryImportManager> ().ImportTrack (uri); } } } } } catch (Exception e) { Hyena.Log.Exception (e); } return null; } private void MergeIfModified (TrackInfo track) { long mtime = Banshee.IO.File.GetModifiedTime (track.Uri); // If the file was modified since we last scanned, parse the file's metadata if (mtime > track.FileModifiedStamp) { using (var file = Banshee.Streaming.StreamTagger.ProcessUri (track.Uri)) { Banshee.Streaming.StreamTagger.TrackInfoMerge (track, file, false, SaveTrackMetadataService.WriteRatingsEnabled.Value, SaveTrackMetadataService.WritePlayCountsEnabled.Value); } } } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ #define SPINE_OPTIONAL_MATERIALOVERRIDE // Contributed by: Lost Polygon using System; using System.Collections.Generic; using UnityEngine; namespace Spine.Unity.Modules { [ExecuteInEditMode] public class SkeletonRendererCustomMaterials : MonoBehaviour { #region Inspector public SkeletonRenderer skeletonRenderer; [SerializeField] protected List<SlotMaterialOverride> customSlotMaterials = new List<SlotMaterialOverride>(); [SerializeField] protected List<AtlasMaterialOverride> customMaterialOverrides = new List<AtlasMaterialOverride>(); #if UNITY_EDITOR void Reset () { skeletonRenderer = GetComponent<SkeletonRenderer>(); // Populate atlas list if (skeletonRenderer != null && skeletonRenderer.skeletonDataAsset != null) { AtlasAsset[] atlasAssets = skeletonRenderer.skeletonDataAsset.atlasAssets; var initialAtlasMaterialOverrides = new List<AtlasMaterialOverride>(); foreach (AtlasAsset atlasAsset in atlasAssets) { foreach (Material atlasMaterial in atlasAsset.materials) { var atlasMaterialOverride = new AtlasMaterialOverride(); atlasMaterialOverride.overrideDisabled = true; atlasMaterialOverride.originalMaterial = atlasMaterial; initialAtlasMaterialOverrides.Add(atlasMaterialOverride); } } customMaterialOverrides = initialAtlasMaterialOverrides; } } #endif #endregion void SetCustomSlotMaterials () { if (skeletonRenderer == null) { Debug.LogError("skeletonRenderer == null"); return; } for (int i = 0; i < customSlotMaterials.Count; i++) { SlotMaterialOverride slotMaterialOverride = customSlotMaterials[i]; if (slotMaterialOverride.overrideDisabled || string.IsNullOrEmpty(slotMaterialOverride.slotName)) continue; Slot slotObject = skeletonRenderer.skeleton.FindSlot(slotMaterialOverride.slotName); skeletonRenderer.CustomSlotMaterials[slotObject] = slotMaterialOverride.material; } } void RemoveCustomSlotMaterials () { if (skeletonRenderer == null) { Debug.LogError("skeletonRenderer == null"); return; } for (int i = 0; i < customSlotMaterials.Count; i++) { SlotMaterialOverride slotMaterialOverride = customSlotMaterials[i]; if (string.IsNullOrEmpty(slotMaterialOverride.slotName)) continue; Slot slotObject = skeletonRenderer.skeleton.FindSlot(slotMaterialOverride.slotName); Material currentMaterial; if (!skeletonRenderer.CustomSlotMaterials.TryGetValue(slotObject, out currentMaterial)) continue; // Do not revert the material if it was changed by something else if (currentMaterial != slotMaterialOverride.material) continue; skeletonRenderer.CustomSlotMaterials.Remove(slotObject); } } void SetCustomMaterialOverrides () { if (skeletonRenderer == null) { Debug.LogError("skeletonRenderer == null"); return; } #if SPINE_OPTIONAL_MATERIALOVERRIDE for (int i = 0; i < customMaterialOverrides.Count; i++) { AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i]; if (atlasMaterialOverride.overrideDisabled) continue; skeletonRenderer.CustomMaterialOverride[atlasMaterialOverride.originalMaterial] = atlasMaterialOverride.replacementMaterial; } #endif } void RemoveCustomMaterialOverrides () { if (skeletonRenderer == null) { Debug.LogError("skeletonRenderer == null"); return; } #if SPINE_OPTIONAL_MATERIALOVERRIDE for (int i = 0; i < customMaterialOverrides.Count; i++) { AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i]; Material currentMaterial; if (!skeletonRenderer.CustomMaterialOverride.TryGetValue(atlasMaterialOverride.originalMaterial, out currentMaterial)) continue; // Do not revert the material if it was changed by something else if (currentMaterial != atlasMaterialOverride.replacementMaterial) continue; skeletonRenderer.CustomMaterialOverride.Remove(atlasMaterialOverride.originalMaterial); } #endif } // OnEnable applies the overrides at runtime, and when the editor loads. void OnEnable () { if (skeletonRenderer == null) skeletonRenderer = GetComponent<SkeletonRenderer>(); if (skeletonRenderer == null) { Debug.LogError("skeletonRenderer == null"); return; } skeletonRenderer.Initialize(false); SetCustomMaterialOverrides(); SetCustomSlotMaterials(); } // OnDisable removes the overrides at runtime, and in the editor when the component is disabled or destroyed. void OnDisable () { if (skeletonRenderer == null) { Debug.LogError("skeletonRenderer == null"); return; } RemoveCustomMaterialOverrides(); RemoveCustomSlotMaterials(); } [Serializable] public struct SlotMaterialOverride : IEquatable<SlotMaterialOverride> { public bool overrideDisabled; [SpineSlot] public string slotName; public Material material; public bool Equals (SlotMaterialOverride other) { return overrideDisabled == other.overrideDisabled && slotName == other.slotName && material == other.material; } } [Serializable] public struct AtlasMaterialOverride : IEquatable<AtlasMaterialOverride> { public bool overrideDisabled; public Material originalMaterial; public Material replacementMaterial; public bool Equals (AtlasMaterialOverride other) { return overrideDisabled == other.overrideDisabled && originalMaterial == other.originalMaterial && replacementMaterial == other.replacementMaterial; } } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Collections; using System.Drawing.Drawing2D; using System.IO; using Reporting.Rdl; using Reporting.Viewer; using Reporting.Rdl.Utility; namespace Reporting.Viewer.Canvas.Drawing { /// <summary> /// This class contains the methods used to draw to a Canvas object. /// </summary> public static class CanvasPainter { #region Drawing methods /// <summary> /// A simple draw of an entire page. Useful when printing or creating an image. /// </summary> public static void Draw(Graphics g, int page, Pages pages, Rectangle clipRectangle, bool drawBackground, ref CanvasProperties cp, ref PageItemManager cpim) { cp.Dpi = new PointF(g.DpiX, g.DpiY); // this can change (e.g. printing graphics context) cp.HighlightText = null; cp.HighlightItem = null; cp.HighlightAll = false; cp.HighlightCaseSensitive = false; // g.InterpolationMode = InterpolationMode.HighQualityBilinear; // try to unfuzz charts g.PageUnit = GraphicsUnit.Pixel; g.ScaleTransform(1, 1); if (!cp.Offset.IsEmpty) // used when correcting for non-printable area on paper { g.TranslateTransform(cp.Offset.X, cp.Offset.Y); } cp.Left = 0; cp.Top = 0; cp.Scroll = new PointF(0, 0); RectangleF r = new RectangleF(clipRectangle.X, clipRectangle.Y, clipRectangle.Width, clipRectangle.Height); if (drawBackground) g.FillRectangle( Brushes.White, Measurement.PixelsFromPoints(cp.Left, cp.Dpi.X), Measurement.PixelsFromPoints(cp.Top, cp.Dpi.Y), Measurement.PixelsFromPoints(pages.PageWidth, cp.Dpi.X), Measurement.PixelsFromPoints(pages.PageHeight, cp.Dpi.Y)); ProcessPage(g, pages[page], r, false, cp, ref cpim); } /// <summary> /// A draw accounting for scrolling and zoom factors. /// </summary> public static void Draw(Graphics g, Pages pages, float pageGap, Rectangle clipRectangle, ref CanvasProperties cp, ref PageItemManager cpim) { if (pages == null) { // No pages; means nothing to draw g.FillRectangle(Brushes.White, clipRectangle); return; } g.PageUnit = GraphicsUnit.Pixel; g.ScaleTransform(cp.Zoom, cp.Zoom); cp.Dpi = new PointF(g.DpiX, g.DpiY); // Zoom affects how much will show on the screen. Adjust our perceived clipping rectangle // to account for it. RectangleF r; r = new RectangleF((clipRectangle.X) / cp.Zoom, (clipRectangle.Y) / cp.Zoom, (clipRectangle.Width) / cp.Zoom, (clipRectangle.Height) / cp.Zoom); // Calculate the top of the page int fpage = (int)(cp.Scroll.Y / Measurement.PixelsFromPoints(pages.PageHeight + pageGap, cp.Dpi.Y)); int lpage = (int)((cp.Scroll.Y + r.Height) / Measurement.PixelsFromPoints(pages.PageHeight + pageGap, cp.Dpi.X)) + 1; if (fpage >= pages.PageCount) return; if (lpage >= pages.PageCount) lpage = pages.PageCount - 1; cp.Left = cp.Offset.X; cp.Top = pageGap; // Loop thru the visible pages for (int p = fpage; p <= lpage; p++) { cp.Scroll = new PointF( cp.Scroll.X, (cp.Scroll.Y - Measurement.PixelsFromPoints(p * (pages.PageHeight + pageGap), cp.Dpi.Y)) ); System.Drawing.Rectangle pr = new System.Drawing.Rectangle( (int)(Measurement.PixelsFromPoints(cp.Left, cp.Dpi.X) - cp.Scroll.X), (int)(Measurement.PixelsFromPoints(cp.Top, cp.Dpi.Y) - cp.Scroll.Y), (int)Measurement.PixelsFromPoints(pages.PageWidth, cp.Dpi.X), (int)Measurement.PixelsFromPoints(pages.PageHeight, cp.Dpi.Y)); g.FillRectangle(Brushes.White, pr); ProcessPage(g, pages[p], r, true, cp, ref cpim); // Draw the page outline using (Pen pn = new Pen(Brushes.Black, 1)) { int z3 = Math.Min((int)(3f / cp.Zoom), 3); if (z3 <= 0) z3 = 1; int z4 = Math.Min((int)(4f / cp.Zoom), 4); if (z4 <= 0) z4 = 1; g.DrawRectangle(pn, pr); // outline of page g.FillRectangle(Brushes.Black, pr.X + pr.Width, pr.Y + z3, z3, pr.Height); // right side of page g.FillRectangle(Brushes.Black, pr.X + z3, pr.Y + pr.Height, pr.Width, z4); // bottom of page } } } /// <summary> /// Renders all the objects in a Page or composite object. /// </summary> private static void ProcessPage(Graphics g, IEnumerable p, RectangleF clipRect, bool bHitList, CanvasProperties cp, ref PageItemManager cpim) { foreach (PageItem pi in p) { if (pi is PageTextHtml) { // PageTextHtml is actually a composite object (just like a page) if (cpim.SelectToolEnabled && bHitList) { RectangleF hr = new RectangleF( Measurement.PixelsFromPoints(pi.X + cp.Left - cp.Scroll.X, cp.Dpi.X), Measurement.PixelsFromPoints(pi.Y + cp.Scroll.X - cp.Scroll.Y, cp.Dpi.Y), Measurement.PixelsFromPoints(pi.W, cp.Dpi.X), Measurement.PixelsFromPoints(pi.H, cp.Dpi.Y)); cpim.HitList.Add(new HitListEntry(hr, pi)); } ProcessHtml(pi as PageTextHtml, g, clipRect, bHitList, cp, ref cpim); continue; } if (pi is PageLine) { PageLine pl = pi as PageLine; CanvasPainter.DrawLine( pl.SI.BColorLeft, pl.SI.BStyleLeft, pl.SI.BWidthLeft, g, Measurement.PixelsFromPoints(pl.X + cp.Left - cp.Scroll.X, cp.Dpi.X), Measurement.PixelsFromPoints(pl.Y + cp.Top - cp.Scroll.Y, cp.Dpi.Y), Measurement.PixelsFromPoints(pl.X2 + cp.Left - cp.Scroll.X, cp.Dpi.X), Measurement.PixelsFromPoints(pl.Y2 + cp.Top - cp.Scroll.Y, cp.Dpi.Y)); continue; } RectangleF rect = new RectangleF( Measurement.PixelsFromPoints(pi.X + cp.Left - cp.Scroll.X, cp.Dpi.X), Measurement.PixelsFromPoints(pi.Y + cp.Top - cp.Scroll.Y, cp.Dpi.Y), Measurement.PixelsFromPoints(pi.W, cp.Dpi.X), Measurement.PixelsFromPoints(pi.H, cp.Dpi.Y)); // Maintain the hit list if (bHitList) { if (cpim.SelectToolEnabled) { // we need all PageText and PageImage items that have been displayed if (pi is PageText || pi is PageImage) { cpim.HitList.Add(new HitListEntry(rect, pi)); } } // Only care about items with links and tips else if (pi.HyperLink != null || pi.BookmarkLink != null || pi.Tooltip != null) { HitListEntry hle; if (pi is PagePolygon) hle = new HitListEntry(pi as PagePolygon, cp.Left - cp.Scroll.X, cp.Top - cp.Scroll.Y, ((Canvas)cp.Parent)); else hle = new HitListEntry(rect, pi); cpim.HitList.Add(hle); } } if ((pi is PagePolygon) || (pi is PageCurve)) { // intentionally empty; polygon's rectangles aren't calculated } else if (!rect.IntersectsWith(clipRect)) continue; if (pi.SI.BackgroundImage != null) { // put out any background image PageImage i = pi.SI.BackgroundImage; CanvasPainter.DrawImageBackground(i, pi.SI, g, rect); } if (pi is PageText) { PageText pt = pi as PageText; CanvasPainter.DrawString(pt, g, rect, cp, cpim); } else if (pi is PageImage) { PageImage i = pi as PageImage; CanvasPainter.DrawImage(i, g, rect, cp, cpim); } else if (pi is PageRectangle) { CanvasPainter.DrawBackground(g, rect, pi.SI); } else if (pi is PageEllipse) { PageEllipse pe = pi as PageEllipse; CanvasPainter.DrawEllipse(pe, g, rect); } else if (pi is PagePie) { PagePie pp = pi as PagePie; CanvasPainter.DrawPie(pp, g, rect); } else if (pi is PagePolygon) { PagePolygon ppo = pi as PagePolygon; CanvasPainter.FillPolygon(ppo, g, rect, cp); } else if (pi is PageCurve) { PageCurve pc = pi as PageCurve; CanvasPainter.DrawCurve(pc.SI.BColorLeft, pc.SI.BStyleLeft, pc.SI.BWidthLeft, g, pc.Points, pc.Offset, pc.Tension, cp); } CanvasPainter.DrawBorder(pi, g, rect); } } /// <summary> /// Pre-Processes the HTML prior to rendering it in a page. /// </summary> public static void ProcessHtml(PageTextHtml pth, Graphics g, RectangleF clipRect, bool bHitList, CanvasProperties cp, ref PageItemManager cpim) { pth.Build(g); // Builds the subobjects that make up the html CanvasPainter.ProcessPage(g, pth, clipRect, bHitList, cp, ref cpim); } /// <summary> /// Parses out the text from the HTML selected form a web page. /// </summary> public static void SelectTextHtml(PageTextHtml ph, StringBuilder sb) { bool bFirst = true; float lastY = float.MaxValue; foreach (PageItem pi in ph) { if (bFirst) // we ignore the contents of the first item { bFirst = false; continue; } PageText pt = pi as PageText; if (pt == null) continue; if (pt.Y > lastY) // we've gone to a new line; put a blank in between the text sb.Append(' '); // this isn't always ideal: if user was just selecting html text // then they might want to retain the new lines; but when selecting // html page items and other page items new lines affect the table building sb.Append(pt.Text); // append on this text lastY = pt.Y; } return; } #region Internal Static private static void DrawBackground(Graphics g, System.Drawing.RectangleF rect, StyleInfo si) { LinearGradientBrush linGrBrush = null; SolidBrush sb = null; HatchBrush hb = null; try { if (si.BackgroundGradientType != BackgroundGradientTypeEnum.None && !si.BackgroundGradientEndColor.IsEmpty && !si.BackgroundColor.IsEmpty) { Color c = si.BackgroundColor; Color ec = si.BackgroundGradientEndColor; switch (si.BackgroundGradientType) { case BackgroundGradientTypeEnum.LeftRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.TopBottom: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; case BackgroundGradientTypeEnum.Center: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.DiagonalLeft: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.ForwardDiagonal); break; case BackgroundGradientTypeEnum.DiagonalRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.BackwardDiagonal); break; case BackgroundGradientTypeEnum.HorizontalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.VerticalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; default: break; } } if (si.PatternType != patternTypeEnum.None) { switch (si.PatternType) { case patternTypeEnum.BackwardDiagonal: hb = new HatchBrush(HatchStyle.BackwardDiagonal, si.Color, si.BackgroundColor); break; case patternTypeEnum.CheckerBoard: hb = new HatchBrush(HatchStyle.LargeCheckerBoard, si.Color, si.BackgroundColor); break; case patternTypeEnum.Cross: hb = new HatchBrush(HatchStyle.Cross, si.Color, si.BackgroundColor); break; case patternTypeEnum.DarkDownwardDiagonal: hb = new HatchBrush(HatchStyle.DarkDownwardDiagonal, si.Color, si.BackgroundColor); break; case patternTypeEnum.DarkHorizontal: hb = new HatchBrush(HatchStyle.DarkHorizontal, si.Color, si.BackgroundColor); break; case patternTypeEnum.DiagonalBrick: hb = new HatchBrush(HatchStyle.DiagonalBrick, si.Color, si.BackgroundColor); break; case patternTypeEnum.HorizontalBrick: hb = new HatchBrush(HatchStyle.HorizontalBrick, si.Color, si.BackgroundColor); break; case patternTypeEnum.LargeConfetti: hb = new HatchBrush(HatchStyle.LargeConfetti, si.Color, si.BackgroundColor); break; case patternTypeEnum.OutlinedDiamond: hb = new HatchBrush(HatchStyle.OutlinedDiamond, si.Color, si.BackgroundColor); break; case patternTypeEnum.SmallConfetti: hb = new HatchBrush(HatchStyle.SmallConfetti, si.Color, si.BackgroundColor); break; case patternTypeEnum.SolidDiamond: hb = new HatchBrush(HatchStyle.SolidDiamond, si.Color, si.BackgroundColor); break; case patternTypeEnum.Vertical: hb = new HatchBrush(HatchStyle.Vertical, si.Color, si.BackgroundColor); break; } } if (linGrBrush != null) { g.FillRectangle(linGrBrush, rect); linGrBrush.Dispose(); } else if (hb != null) { g.FillRectangle(hb, rect); hb.Dispose(); } else if (!si.BackgroundColor.IsEmpty) { sb = new SolidBrush(si.BackgroundColor); g.FillRectangle(sb, rect); sb.Dispose(); } } finally { if (linGrBrush != null) linGrBrush.Dispose(); if (sb != null) sb.Dispose(); } return; } private static void DrawBorder(PageItem pi, Graphics g, RectangleF r) { if (pi.GetType().Name.Equals("PagePie")) return; if (r.Height <= 0 || r.Width <= 0) // no bounding box to use return; StyleInfo si = pi.SI; DrawLine(si.BColorTop, si.BStyleTop, si.BWidthTop, g, r.X, r.Y, r.Right, r.Y); DrawLine(si.BColorRight, si.BStyleRight, si.BWidthRight, g, r.Right, r.Y, r.Right, r.Bottom); DrawLine(si.BColorLeft, si.BStyleLeft, si.BWidthLeft, g, r.X, r.Y, r.X, r.Bottom); DrawLine(si.BColorBottom, si.BStyleBottom, si.BWidthBottom, g, r.X, r.Bottom, r.Right, r.Bottom); return; } private static void DrawImage(PageImage pi, Graphics g, RectangleF r, CanvasProperties cp, PageItemManager cpim) { Stream strm = null; System.Drawing.Image im = null; try { strm = new MemoryStream(pi.ImageData); im = Image.FromStream(strm); DrawImageSized(pi, im, g, r, cp, cpim); } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } } private static void DrawImageBackground(PageImage pi, StyleInfo si, Graphics g, RectangleF r) { Stream strm = null; System.Drawing.Image im = null; try { strm = new MemoryStream(pi.ImageData); im = System.Drawing.Image.FromStream(strm); //RectangleF r2 = new RectangleF(r.Left + PixelsX(si.PaddingLeft), // r.Top + PixelsY(si.PaddingTop), // r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), // r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); // http://www.fyireporting.com/forum/viewtopic.php?t=892 //A.S.> convert pt to px if needed(when printing we need px, when draw preview - pt) RectangleF r2; if (g.PageUnit == GraphicsUnit.Pixel) { r2 = new RectangleF(r.Left + (si.PaddingLeft * g.DpiX) / 72, r.Top + (si.PaddingTop * g.DpiX) / 72, r.Width - ((si.PaddingLeft + si.PaddingRight) * g.DpiX) / 72, r.Height - ((si.PaddingTop + si.PaddingBottom) * g.DpiX) / 72); } else { // adjust drawing rectangle based on padding r2 = new RectangleF(r.Left + si.PaddingLeft, r.Top + si.PaddingTop, r.Width - si.PaddingLeft - si.PaddingRight, r.Height - si.PaddingTop - si.PaddingBottom); } int repeatX = 0; int repeatY = 0; switch (pi.Repeat) { case ImageRepeat.Repeat: repeatX = (int)Math.Floor(r2.Width / pi.SamplesW); repeatY = (int)Math.Floor(r2.Height / pi.SamplesH); break; case ImageRepeat.RepeatX: repeatX = (int)Math.Floor(r2.Width / pi.SamplesW); repeatY = 1; break; case ImageRepeat.RepeatY: repeatY = (int)Math.Floor(r2.Height / pi.SamplesH); repeatX = 1; break; case ImageRepeat.NoRepeat: default: repeatX = repeatY = 1; break; } //make sure the image is drawn at least 1 times repeatX = Math.Max(repeatX, 1); repeatY = Math.Max(repeatY, 1); float startX = r2.Left; float startY = r2.Top; Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; for (int i = 0; i < repeatX; i++) { for (int j = 0; j < repeatY; j++) { float currX = startX + i * pi.SamplesW; float currY = startY + j * pi.SamplesH; g.DrawImage(im, new RectangleF(currX, currY, pi.SamplesW, pi.SamplesH)); } } g.Clip = saveRegion; } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } } private static void DrawImageSized(PageImage pi, Image im, Graphics g, RectangleF r, CanvasProperties cp, PageItemManager cpim) { float height, width; // some work variables StyleInfo si = pi.SI; // adjust drawing rectangle based on padding //RectangleF r2 = new RectangleF(r.Left + PixelsX(si.PaddingLeft), // r.Top + PixelsY(si.PaddingTop), // r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), // r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); // http://www.fyireporting.com/forum/viewtopic.php?t=892 //A.S.> convert pt to px if needed(when printing we need px, when draw preview - pt) RectangleF r2; if (g.PageUnit == GraphicsUnit.Pixel) { r2 = new RectangleF(r.Left + (si.PaddingLeft * g.DpiX) / 72, r.Top + (si.PaddingTop * g.DpiX) / 72, r.Width - ((si.PaddingLeft + si.PaddingRight) * g.DpiX) / 72, r.Height - ((si.PaddingTop + si.PaddingBottom) * g.DpiX) / 72); } else { // adjust drawing rectangle based on padding r2 = new RectangleF(r.Left + si.PaddingLeft, r.Top + si.PaddingTop, r.Width - si.PaddingLeft - si.PaddingRight, r.Height - si.PaddingTop - si.PaddingBottom); } Rectangle ir; // int work rectangle ir = new Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); switch (pi.Sizing) { case ImageSizingEnum.AutoSize: // Note: GDI+ will stretch an image when you only provide // the left/top coordinates. This seems pretty stupid since // it results in the image being out of focus even though // you don't want the image resized. if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } g.DrawImage(im, ir); break; case ImageSizingEnum.Clip: Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } g.DrawImage(im, ir); g.Clip = saveRegion; break; case ImageSizingEnum.FitProportional: float ratioIm = (float)im.Height / (float)im.Width; float ratioR = r2.Height / r2.Width; height = r2.Height; width = r2.Width; if (ratioIm > ratioR) { // this means the rectangle width must be corrected width = height * (1 / ratioIm); } else if (ratioIm < ratioR) { // this means the ractangle height must be corrected height = width * ratioIm; } r2 = new RectangleF(r2.X, r2.Y, width, height); g.DrawImage(im, r2); break; case ImageSizingEnum.Fit: default: g.DrawImage(im, r2); break; } if (cpim.SelectToolEnabled && pi.AllowSelect && cpim.SelectedItemList.Contains(pi)) { g.FillRectangle(new SolidBrush(Color.FromArgb(50, cp.SelectItemColor)), ir); } return; } private static void DrawLine(Color c, BorderStyleEnum bs, float w, Graphics g, float x, float y, float x2, float y2) { if (bs == BorderStyleEnum.None || c.IsEmpty || w <= 0) // nothing to draw return; Pen p = null; try { //Changed from forum, user :Aleksey http://www.fyireporting.com/forum/viewtopic.php?t=892 float tmpW = w; if (g.PageUnit == GraphicsUnit.Pixel) tmpW = (tmpW * g.DpiX) / 72; p = new Pen(c, tmpW); switch (bs) { case BorderStyleEnum.Dashed: p.DashStyle = DashStyle.Dash; break; case BorderStyleEnum.Dotted: p.DashStyle = DashStyle.Dot; break; case BorderStyleEnum.Double: case BorderStyleEnum.Groove: case BorderStyleEnum.Inset: case BorderStyleEnum.Solid: case BorderStyleEnum.Outset: case BorderStyleEnum.Ridge: case BorderStyleEnum.WindowInset: default: p.DashStyle = DashStyle.Solid; break; } g.DrawLine(p, x, y, x2, y2); } finally { if (p != null) p.Dispose(); } } private static void DrawCurve(Color c, BorderStyleEnum bs, float w, Graphics g, PointF[] points, int Offset, float Tension, CanvasProperties cp) { if (bs == BorderStyleEnum.None || c.IsEmpty || w <= 0) // nothing to draw return; Pen p = null; try { p = new Pen(c, w); switch (bs) { case BorderStyleEnum.Dashed: p.DashStyle = DashStyle.Dash; break; case BorderStyleEnum.Dotted: p.DashStyle = DashStyle.Dot; break; case BorderStyleEnum.Double: case BorderStyleEnum.Groove: case BorderStyleEnum.Inset: case BorderStyleEnum.Solid: case BorderStyleEnum.Outset: case BorderStyleEnum.Ridge: case BorderStyleEnum.WindowInset: default: p.DashStyle = DashStyle.Solid; break; } PointF[] tmp = new PointF[points.Length]; for (int i = 0; i < points.Length; i++) { tmp[i] = Measurement.PixelsFromPoints(points[i].X + cp.Left - cp.Scroll.X, points[i].Y + cp.Top - cp.Scroll.Y, cp.Dpi); } g.DrawCurve(p, tmp, Offset, tmp.Length - 1, Tension); } finally { if (p != null) p.Dispose(); } } private static void DrawEllipse(PageEllipse pe, Graphics g, RectangleF r) { StyleInfo si = pe.SI; if (!si.BackgroundColor.IsEmpty) { g.FillEllipse(new SolidBrush(si.BackgroundColor), r); } if (si.BStyleTop != BorderStyleEnum.None) { Pen p = new Pen(si.BColorTop, si.BWidthTop); switch (si.BStyleTop) { case BorderStyleEnum.Dashed: p.DashStyle = DashStyle.Dash; break; case BorderStyleEnum.Dotted: p.DashStyle = DashStyle.Dot; break; case BorderStyleEnum.Double: case BorderStyleEnum.Groove: case BorderStyleEnum.Inset: case BorderStyleEnum.Solid: case BorderStyleEnum.Outset: case BorderStyleEnum.Ridge: case BorderStyleEnum.WindowInset: default: p.DashStyle = DashStyle.Solid; break; } g.DrawEllipse(p, r); } } private static void FillPolygon(PagePolygon pp, Graphics g, RectangleF r, CanvasProperties cp) { StyleInfo si = pp.SI; PointF[] tmp = new PointF[pp.Points.Length]; if (!si.BackgroundColor.IsEmpty) //RectangleF(PixelsX(pi.X + _left - _hScroll), PixelsY(pi.Y + _top - _vScroll), // PixelsX(pi.W), PixelsY(pi.H)) { for (int i = 0; i < pp.Points.Length; i++) { tmp[i] = Measurement.PixelsFromPoints(pp.Points[i].X + cp.Left - cp.Scroll.X, pp.Points[i].Y + cp.Top - cp.Scroll.Y, cp.Dpi); } g.FillPolygon(new SolidBrush(si.BackgroundColor), tmp); } } private static void DrawPie(PagePie pp, Graphics g, RectangleF r) { StyleInfo si = pp.SI; if (!si.BackgroundColor.IsEmpty) { g.FillPie(new SolidBrush(si.BackgroundColor), (int)r.X, (int)r.Y, (int)r.Width, (int)r.Height, (float)pp.StartAngle, (float)pp.SweepAngle); } if (si.BStyleTop != BorderStyleEnum.None) { Pen p = new Pen(si.BColorTop, si.BWidthTop); switch (si.BStyleTop) { case BorderStyleEnum.Dashed: p.DashStyle = DashStyle.Dash; break; case BorderStyleEnum.Dotted: p.DashStyle = DashStyle.Dot; break; case BorderStyleEnum.Double: case BorderStyleEnum.Groove: case BorderStyleEnum.Inset: case BorderStyleEnum.Solid: case BorderStyleEnum.Outset: case BorderStyleEnum.Ridge: case BorderStyleEnum.WindowInset: default: p.DashStyle = DashStyle.Solid; break; } g.DrawPie(p, r, pp.StartAngle, pp.SweepAngle); } } private static void DrawString(PageText pt, Graphics g, RectangleF r, CanvasProperties cp, PageItemManager cpim) { StyleInfo si = pt.SI; string s = pt.Text; Font drawFont = null; StringFormat drawFormat = null; Brush drawBrush = null; try { // STYLE System.Drawing.FontStyle fs = 0; if (si.FontStyle == FontStyleEnum.Italic) fs |= System.Drawing.FontStyle.Italic; switch (si.TextDecoration) { case TextDecorationEnum.Underline: fs |= System.Drawing.FontStyle.Underline; break; case TextDecorationEnum.LineThrough: fs |= System.Drawing.FontStyle.Strikeout; break; case TextDecorationEnum.Overline: case TextDecorationEnum.None: break; } // WEIGHT switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: fs |= System.Drawing.FontStyle.Bold; break; default: break; } try { drawFont = new Font(si.GetFontFamily(), si.FontSize, fs); // si.FontSize already in points } catch (ArgumentException) { drawFont = new Font("Arial", si.FontSize, fs); // if this fails we'll let the error pass thru } // ALIGNMENT drawFormat = new StringFormat(); switch (si.TextAlign) { case TextAlignEnum.Right: drawFormat.Alignment = StringAlignment.Far; break; case TextAlignEnum.Center: drawFormat.Alignment = StringAlignment.Center; break; case TextAlignEnum.Left: default: drawFormat.Alignment = StringAlignment.Near; break; } if (pt.SI.WritingMode == WritingModeEnum.tb_rl) { drawFormat.FormatFlags |= StringFormatFlags.DirectionRightToLeft; drawFormat.FormatFlags |= StringFormatFlags.DirectionVertical; } switch (si.VerticalAlign) { case VerticalAlignEnum.Bottom: drawFormat.LineAlignment = StringAlignment.Far; break; case VerticalAlignEnum.Middle: drawFormat.LineAlignment = StringAlignment.Center; break; case VerticalAlignEnum.Top: default: drawFormat.LineAlignment = StringAlignment.Near; break; } // draw the background DrawBackground(g, r, si); // adjust drawing rectangle based on padding //RectangleF r2 = new RectangleF(r.Left + si.PaddingLeft, // r.Top + si.PaddingTop, // r.Width - si.PaddingLeft - si.PaddingRight, // r.Height - si.PaddingTop - si.PaddingBottom); // http://www.fyireporting.com/forum/viewtopic.php?t=892 //A.S.> convert pt to px if needed(when printing we need px, when draw preview - pt) RectangleF r2; if (g.PageUnit == GraphicsUnit.Pixel) { r2 = new RectangleF(r.Left + (si.PaddingLeft * g.DpiX) / 72, r.Top + (si.PaddingTop * g.DpiX) / 72, r.Width - ((si.PaddingLeft + si.PaddingRight) * g.DpiX) / 72, r.Height - ((si.PaddingTop + si.PaddingBottom) * g.DpiX) / 72); } else { // adjust drawing rectangle based on padding r2 = new RectangleF(r.Left + si.PaddingLeft, r.Top + si.PaddingTop, r.Width - si.PaddingLeft - si.PaddingRight, r.Height - si.PaddingTop - si.PaddingBottom); } drawBrush = new SolidBrush(si.Color); if (si.TextAlign == TextAlignEnum.Justified) //Added from forum: Hugo http://www.fyireporting.com/forum/viewtopic.php?t=552 GraphicsExtended.DrawStringJustified(g, pt.Text, drawFont, drawBrush, r2, '-'); else if (pt.NoClip) // request not to clip text { g.DrawString(pt.Text, drawFont, drawBrush, new PointF(r.Left, r.Top), drawFormat); HighlightString(g, pt, new RectangleF(r.Left, r.Top, float.MaxValue, float.MaxValue), drawFont, drawFormat, cp); } else { g.DrawString(pt.Text, drawFont, drawBrush, r2, drawFormat); HighlightString(g, pt, r2, drawFont, drawFormat, cp); } if (cpim.SelectToolEnabled) { if (pt.AllowSelect && cpim.SelectedItemList.Contains(pt)) g.FillRectangle(new SolidBrush(Color.FromArgb(50, cp.SelectItemColor)), r2); } } finally { if (drawFont != null) drawFont.Dispose(); if (drawFormat != null) drawFont.Dispose(); if (drawBrush != null) drawBrush.Dispose(); } } private static void HighlightString(Graphics g, PageText dtext, RectangleF r, Font f, StringFormat sf, CanvasProperties cp) { if (cp.HighlightText == null || cp.HighlightText.Length == 0) return; // nothing to highlight bool bhighlightItem = dtext == cp.HighlightItem || (cp.HighlightItem != null && dtext.HtmlParent == cp.HighlightItem); if (!(cp.HighlightAll || bhighlightItem)) return; // not highlighting all and not on current highlight item string hlt = cp.HighlightCaseSensitive ? cp.HighlightText : cp.HighlightText.ToLower(); string text = cp.HighlightCaseSensitive ? dtext.Text : dtext.Text.ToLower(); if (text.IndexOf(hlt) < 0) return; // string not in text StringFormat sf2 = null; try { // Create a CharacterRange array with the highlight location and length // Handle multiple occurences of text List<CharacterRange> rangel = new List<CharacterRange>(); int loc = text.IndexOf(hlt); int hlen = hlt.Length; int len = text.Length; while (loc >= 0) { rangel.Add(new CharacterRange(loc, hlen)); if (loc + hlen < len) // out of range of text loc = text.IndexOf(hlt, loc + hlen); else loc = -1; } if (rangel.Count <= 0) // we should have gotten one; but return; CharacterRange[] ranges = rangel.ToArray(); // Construct a new StringFormat object. sf2 = sf.Clone() as StringFormat; // Set the ranges on the StringFormat object. sf2.SetMeasurableCharacterRanges(ranges); // Get the Regions to highlight by calling the // MeasureCharacterRanges method. if (r.Width <= 0 || r.Height <= 0) { SizeF ts = g.MeasureString(dtext.Text, f); r.Height = ts.Height; r.Width = ts.Width; } Region[] charRegion = g.MeasureCharacterRanges(dtext.Text, f, r, sf2); // Fill in the region using a semi-transparent color to highlight foreach (Region rg in charRegion) { Color hl = bhighlightItem ? cp.HighlightItemColor : cp.HighlightAllColor; g.FillRegion(new SolidBrush(Color.FromArgb(50, hl)), rg); } } catch { } // if highlighting fails we don't care; need to continue finally { if (sf2 != null) sf2.Dispose(); } } #endregion #endregion /// <summary> /// A compare method that sorts page items by their XY coordinates. /// </summary> /// <returns>An integer indicating the relative location of one page item to the other.</returns> public static int ComparePageItemByPageXY(PageItem pi1, PageItem pi2) { if (pi1.Page.Count != pi2.Page.Count) return pi1.Page.Count - pi2.Page.Count; if (pi1.Y != pi2.Y) { return Convert.ToInt32((pi1.Y - pi2.Y) * 1000); } return Convert.ToInt32((pi1.X - pi2.X) * 1000); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.IO; namespace System.Security.Cryptography { public abstract partial class ECDsa : AsymmetricAlgorithm { protected ECDsa() { } public static new ECDsa Create(string algorithm) { if (algorithm == null) { throw new ArgumentNullException(nameof(algorithm)); } return CryptoConfig.CreateFromName(algorithm) as ECDsa; } /// <summary> /// When overridden in a derived class, exports the named or explicit ECParameters for an ECCurve. /// If the curve has a name, the Curve property will contain named curve parameters otherwise it will contain explicit parameters. /// </summary> /// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param> /// <returns></returns> public virtual ECParameters ExportParameters(bool includePrivateParameters) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } /// <summary> /// When overridden in a derived class, exports the explicit ECParameters for an ECCurve. /// </summary> /// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param> /// <returns></returns> public virtual ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } /// <summary> /// When overridden in a derived class, imports the specified ECParameters. /// </summary> /// <param name="parameters">The curve parameters.</param> public virtual void ImportParameters(ECParameters parameters) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } /// <summary> /// When overridden in a derived class, generates a new public/private keypair for the specified curve. /// </summary> /// <param name="curve">The curve to use.</param> public virtual void GenerateKey(ECCurve curve) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); return SignData(data, 0, data.Length, hashAlgorithm); } public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash); } public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); } if (TryHashData(data, destination, hashAlgorithm, out int hashLength) && TrySignHash(destination.Slice(0, hashLength), destination, out bytesWritten)) { return true; } bytesWritten = 0; return false; } public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash); } public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); return VerifyData(data, 0, data.Length, signature, hashAlgorithm); } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature); } public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); } for (int i = 256; ; i = checked(i * 2)) { int hashLength = 0; byte[] hash = ArrayPool<byte>.Shared.Rent(i); try { if (TryHashData(data, hash, hashAlgorithm, out hashLength)) { return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature); } } finally { Array.Clear(hash, 0, hashLength); ArrayPool<byte>.Shared.Return(hash); } } } public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { if (data == null) throw new ArgumentNullException(nameof(data)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature); } public abstract byte[] SignHash(byte[] hash); public abstract bool VerifyHash(byte[] hash, byte[] signature); public override string KeyExchangeAlgorithm => null; public override string SignatureAlgorithm => "ECDsa"; protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { byte[] array = ArrayPool<byte>.Shared.Rent(data.Length); try { data.CopyTo(array); byte[] hash = HashData(array, 0, data.Length, hashAlgorithm); if (hash.Length <= destination.Length) { new ReadOnlySpan<byte>(hash).CopyTo(destination); bytesWritten = hash.Length; return true; } else { bytesWritten = 0; return false; } } finally { Array.Clear(array, 0, data.Length); ArrayPool<byte>.Shared.Return(array); } } public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten) { byte[] result = SignHash(hash.ToArray()); if (result.Length <= destination.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } else { bytesWritten = 0; return false; } } public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) => VerifyHash(hash.ToArray(), signature.ToArray()); } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System; using System.Collections; using System.Collections.Generic; using TouchScript.Utils; using TouchScript.Utils.Attributes; using TouchScript.Pointers; using UnityEngine; using UnityEngine.Profiling; namespace TouchScript.Gestures { /// <summary> /// Gesture which recognizes a point cluster which didn't move for specified time since it appeared. /// </summary> [AddComponentMenu("TouchScript/Gestures/Long Press Gesture")] [HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Gestures_LongPressGesture.htm")] public class LongPressGesture : Gesture { #region Constants /// <summary> /// Message name when gesture is recognized /// </summary> public const string LONG_PRESS_MESSAGE = "OnLongPress"; #endregion #region Events /// <summary> /// Occurs when gesture is recognized. /// </summary> public event EventHandler<EventArgs> LongPressed { add { longPressedInvoker += value; } remove { longPressedInvoker -= value; } } // Needed to overcome iOS AOT limitations private EventHandler<EventArgs> longPressedInvoker; /// <summary> /// Unity event, occurs when gesture is recognized. /// </summary> public GestureEvent OnLongPress = new GestureEvent(); #endregion #region Public properties /// <summary> /// Gets or sets total time in seconds required to hold pointers still. /// </summary> /// <value> Time in seconds. </value> public float TimeToPress { get { return timeToPress; } set { timeToPress = value; } } /// <summary> /// Gets or sets maximum distance in cm pointers can move before gesture fails. /// </summary> /// <value> Distance in cm. </value> public float DistanceLimit { get { return distanceLimit; } set { distanceLimit = value; distanceLimitInPixelsSquared = Mathf.Pow(distanceLimit * touchManager.DotsPerCentimeter, 2); } } #endregion #region Private variables [SerializeField] private float timeToPress = 1; [SerializeField] [NullToggle(NullFloatValue = float.PositiveInfinity)] private float distanceLimit = float.PositiveInfinity; private float distanceLimitInPixelsSquared; private Vector2 totalMovement; private CustomSampler gestureSampler; #endregion #region Unity methods /// <inheritdoc /> protected override void Awake() { base.Awake(); gestureSampler = CustomSampler.Create("[TouchScript] Long Press Gesture"); } /// <inheritdoc /> protected override void OnEnable() { base.OnEnable(); distanceLimitInPixelsSquared = Mathf.Pow(distanceLimit * touchManager.DotsPerCentimeter, 2); } [ContextMenu("Basic Editor")] private void switchToBasicEditor() { basicEditor = true; } #endregion #region Gesture callbacks /// <inheritdoc /> protected override void pointersPressed(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersPressed(pointers); if (pointersNumState == PointersNumState.PassedMaxThreshold || pointersNumState == PointersNumState.PassedMinMaxThreshold) { setState(GestureState.Failed); } else if (pointersNumState == PointersNumState.PassedMinThreshold) { setState(GestureState.Possible); StartCoroutine("wait"); } gestureSampler.End(); } /// <inheritdoc /> protected override void pointersUpdated(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersUpdated(pointers); if (distanceLimit < float.PositiveInfinity) { totalMovement += ScreenPosition - PreviousScreenPosition; if (totalMovement.sqrMagnitude > distanceLimitInPixelsSquared) setState(GestureState.Failed); } gestureSampler.End(); } /// <inheritdoc /> protected override void pointersReleased(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersReleased(pointers); if (pointersNumState == PointersNumState.PassedMinThreshold) { setState(GestureState.Failed); } gestureSampler.End(); } /// <inheritdoc /> protected override void onRecognized() { base.onRecognized(); if (longPressedInvoker != null) longPressedInvoker.InvokeHandleExceptions(this, EventArgs.Empty); if (UseSendMessage && SendMessageTarget != null) SendMessageTarget.SendMessage(LONG_PRESS_MESSAGE, this, SendMessageOptions.DontRequireReceiver); if (UseUnityEvents) OnLongPress.Invoke(this); } /// <inheritdoc /> protected override void reset() { base.reset(); totalMovement = Vector2.zero; StopCoroutine("wait"); } #endregion #region Private functions private IEnumerator wait() { // WaitForSeconds is affected by time scale! var targetTime = Time.unscaledTime + TimeToPress; while (targetTime > Time.unscaledTime) yield return null; if (State == GestureState.Possible) { var data = GetScreenPositionHitData(); if (data.Target == null || !data.Target.IsChildOf(cachedTransform)) setState(GestureState.Failed); else setState(GestureState.Recognized); } } #endregion } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if APARTMENT_STATE using System; using System.Threading; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { [TestFixture] public class ApartmentAttributeTests : ThreadingTests { #if APARTMENT_STATE [Test] public void ApartmentStateUnknownIsNotRunnable() { var testSuite = TestBuilder.MakeFixture(typeof(ApartmentDataApartmentAttribute)); Assert.That(testSuite, Has.Property(nameof(TestSuite.RunState)).EqualTo(RunState.NotRunnable)); } #endif [Test, Apartment(ApartmentState.STA)] public void TestWithRequiresSTARunsInSTA() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); if (ParentThreadApartment == ApartmentState.STA) Assert.That(Thread.CurrentThread, Is.EqualTo(ParentThread)); } [Test] #if THREAD_ABORT [Timeout(10000)] #endif [Apartment(ApartmentState.STA)] public void TestWithTimeoutAndSTARunsInSTA() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); } [TestFixture] #if THREAD_ABORT [Timeout(10000)] #endif [Apartment(ApartmentState.STA)] public class FixtureWithTimeoutRequiresSTA { [Test] public void RequiresSTACanBeSetOnTestFixtureWithTimeout() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); } } [TestFixture, Apartment(ApartmentState.STA)] public class FixtureRequiresSTA { [Test] public void RequiresSTACanBeSetOnTestFixture() { Assert.That( GetApartmentState( Thread.CurrentThread ), Is.EqualTo( ApartmentState.STA ) ); } } [TestFixture] public class ChildFixtureRequiresSTA : FixtureRequiresSTA { // Issue #36 - Make RequiresThread, RequiresSTA, RequiresMTA inheritable // https://github.com/nunit/nunit-framework/issues/36 [Test] public void RequiresSTAAttributeIsInheritable() { Attribute[] attributes = Attribute.GetCustomAttributes(GetType(), typeof(ApartmentAttribute), true); Assert.That(attributes, Has.Length.EqualTo(1), "RequiresSTAAttribute was not inherited from the base class"); } } [Test, Apartment(ApartmentState.MTA)] public void TestWithRequiresMTARunsInMTA() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.MTA)); if (ParentThreadApartment == ApartmentState.MTA) Assert.That(Thread.CurrentThread, Is.EqualTo(ParentThread)); } [TestFixture, Apartment(ApartmentState.MTA)] public class FixtureRequiresMTA { [Test] public void RequiresMTACanBeSetOnTestFixture() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.MTA)); } } [TestFixture] public class ChildFixtureRequiresMTA : FixtureRequiresMTA { // Issue #36 - Make RequiresThread, RequiresSTA, RequiresMTA inheritable // https://github.com/nunit/nunit-framework/issues/36 [Test] public void RequiresMTAAttributeIsInheritable() { Attribute[] attributes = Attribute.GetCustomAttributes(GetType(), typeof(ApartmentAttribute), true); Assert.That(attributes, Has.Length.EqualTo(1), "RequiresMTAAttribute was not inherited from the base class"); } } [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.Children)] public class ParallelStaFixture { [Test] public void TestMethodsShouldInheritApartmentFromFixture() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } [TestCase(1)] [TestCase(2)] public void TestCasesShouldInheritApartmentFromFixture(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } } [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.Children)] public class ParallelStaFixtureWithMtaTests { [Test] [Apartment(ApartmentState.MTA)] public void TestMethodsShouldRespectTheirApartment() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } [TestCase(1)] [TestCase(2)] [Apartment(ApartmentState.MTA)] public void TestCasesShouldRespectTheirApartment(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } } [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.None)] public class NonParallelStaFixture { [Test] public void TestMethodsShouldInheritApartmentFromFixture() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } [TestCase(1)] [TestCase(2)] public void TestCasesShouldInheritApartmentFromFixture(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } } [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.None)] public class NonParallelStaFixtureWithMtaTests { [Test] [Apartment(ApartmentState.MTA)] public void TestMethodsShouldRespectTheirApartment() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } [TestCase(1)] [TestCase(2)] [Apartment(ApartmentState.MTA)] public void TestCasesShouldRespectTheirApartment(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } } } } #endif
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using 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 sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.PrivateCatalog.V1Beta1 { /// <summary>Settings for <see cref="PrivateCatalogClient"/> instances.</summary> public sealed partial class PrivateCatalogSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="PrivateCatalogSettings"/>.</summary> /// <returns>A new instance of the default <see cref="PrivateCatalogSettings"/>.</returns> public static PrivateCatalogSettings GetDefault() => new PrivateCatalogSettings(); /// <summary>Constructs a new <see cref="PrivateCatalogSettings"/> object with default settings.</summary> public PrivateCatalogSettings() { } private PrivateCatalogSettings(PrivateCatalogSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); SearchCatalogsSettings = existing.SearchCatalogsSettings; SearchProductsSettings = existing.SearchProductsSettings; SearchVersionsSettings = existing.SearchVersionsSettings; OnCopy(existing); } partial void OnCopy(PrivateCatalogSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PrivateCatalogClient.SearchCatalogs</c> and <c>PrivateCatalogClient.SearchCatalogsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings SearchCatalogsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PrivateCatalogClient.SearchProducts</c> and <c>PrivateCatalogClient.SearchProductsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings SearchProductsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PrivateCatalogClient.SearchVersions</c> and <c>PrivateCatalogClient.SearchVersionsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings SearchVersionsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="PrivateCatalogSettings"/> object.</returns> public PrivateCatalogSettings Clone() => new PrivateCatalogSettings(this); } /// <summary> /// Builder class for <see cref="PrivateCatalogClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class PrivateCatalogClientBuilder : gaxgrpc::ClientBuilderBase<PrivateCatalogClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public PrivateCatalogSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public PrivateCatalogClientBuilder() { UseJwtAccessWithScopes = PrivateCatalogClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref PrivateCatalogClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PrivateCatalogClient> task); /// <summary>Builds the resulting client.</summary> public override PrivateCatalogClient Build() { PrivateCatalogClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<PrivateCatalogClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<PrivateCatalogClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private PrivateCatalogClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return PrivateCatalogClient.Create(callInvoker, Settings); } private async stt::Task<PrivateCatalogClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return PrivateCatalogClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => PrivateCatalogClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => PrivateCatalogClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => PrivateCatalogClient.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>PrivateCatalog client wrapper, for convenient use.</summary> /// <remarks> /// `PrivateCatalog` allows catalog consumers to retrieve `Catalog`, `Product` /// and `Version` resources under a target resource context. /// /// `Catalog` is computed based on the [Association][]s linked to the target /// resource and its ancestors. Each association's /// [google.cloud.privatecatalogproducer.v1beta.Catalog][] is transformed into a /// `Catalog`. If multiple associations have the same parent /// [google.cloud.privatecatalogproducer.v1beta.Catalog][], they are /// de-duplicated into one `Catalog`. Users must have /// `cloudprivatecatalog.catalogTargets.get` IAM permission on the resource /// context in order to access catalogs. `Catalog` contains the resource name and /// a subset of data of the original /// [google.cloud.privatecatalogproducer.v1beta.Catalog][]. /// /// `Product` is child resource of the catalog. A `Product` contains the resource /// name and a subset of the data of the original /// [google.cloud.privatecatalogproducer.v1beta.Product][]. /// /// `Version` is child resource of the product. A `Version` contains the resource /// name and a subset of the data of the original /// [google.cloud.privatecatalogproducer.v1beta.Version][]. /// </remarks> public abstract partial class PrivateCatalogClient { /// <summary> /// The default endpoint for the PrivateCatalog service, which is a host of "cloudprivatecatalog.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "cloudprivatecatalog.googleapis.com:443"; /// <summary>The default PrivateCatalog scopes.</summary> /// <remarks> /// The default PrivateCatalog scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="PrivateCatalogClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="PrivateCatalogClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="PrivateCatalogClient"/>.</returns> public static stt::Task<PrivateCatalogClient> CreateAsync(st::CancellationToken cancellationToken = default) => new PrivateCatalogClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="PrivateCatalogClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="PrivateCatalogClientBuilder"/>. /// </summary> /// <returns>The created <see cref="PrivateCatalogClient"/>.</returns> public static PrivateCatalogClient Create() => new PrivateCatalogClientBuilder().Build(); /// <summary> /// Creates a <see cref="PrivateCatalogClient"/> 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="PrivateCatalogSettings"/>.</param> /// <returns>The created <see cref="PrivateCatalogClient"/>.</returns> internal static PrivateCatalogClient Create(grpccore::CallInvoker callInvoker, PrivateCatalogSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } PrivateCatalog.PrivateCatalogClient grpcClient = new PrivateCatalog.PrivateCatalogClient(callInvoker); return new PrivateCatalogClientImpl(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 PrivateCatalog client</summary> public virtual PrivateCatalog.PrivateCatalogClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Search [Catalog][google.cloud.privatecatalog.v1beta1.Catalog] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Catalog"/> resources.</returns> public virtual gax::PagedEnumerable<SearchCatalogsResponse, Catalog> SearchCatalogs(SearchCatalogsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Search [Catalog][google.cloud.privatecatalog.v1beta1.Catalog] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Catalog"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<SearchCatalogsResponse, Catalog> SearchCatalogsAsync(SearchCatalogsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Search [Product][google.cloud.privatecatalog.v1beta1.Product] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Product"/> resources.</returns> public virtual gax::PagedEnumerable<SearchProductsResponse, Product> SearchProducts(SearchProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Search [Product][google.cloud.privatecatalog.v1beta1.Product] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Product"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<SearchProductsResponse, Product> SearchProductsAsync(SearchProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Search [Version][google.cloud.privatecatalog.v1beta1.Version] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Version"/> resources.</returns> public virtual gax::PagedEnumerable<SearchVersionsResponse, Version> SearchVersions(SearchVersionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Search [Version][google.cloud.privatecatalog.v1beta1.Version] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Version"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<SearchVersionsResponse, Version> SearchVersionsAsync(SearchVersionsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); } /// <summary>PrivateCatalog client wrapper implementation, for convenient use.</summary> /// <remarks> /// `PrivateCatalog` allows catalog consumers to retrieve `Catalog`, `Product` /// and `Version` resources under a target resource context. /// /// `Catalog` is computed based on the [Association][]s linked to the target /// resource and its ancestors. Each association's /// [google.cloud.privatecatalogproducer.v1beta.Catalog][] is transformed into a /// `Catalog`. If multiple associations have the same parent /// [google.cloud.privatecatalogproducer.v1beta.Catalog][], they are /// de-duplicated into one `Catalog`. Users must have /// `cloudprivatecatalog.catalogTargets.get` IAM permission on the resource /// context in order to access catalogs. `Catalog` contains the resource name and /// a subset of data of the original /// [google.cloud.privatecatalogproducer.v1beta.Catalog][]. /// /// `Product` is child resource of the catalog. A `Product` contains the resource /// name and a subset of the data of the original /// [google.cloud.privatecatalogproducer.v1beta.Product][]. /// /// `Version` is child resource of the product. A `Version` contains the resource /// name and a subset of the data of the original /// [google.cloud.privatecatalogproducer.v1beta.Version][]. /// </remarks> public sealed partial class PrivateCatalogClientImpl : PrivateCatalogClient { private readonly gaxgrpc::ApiCall<SearchCatalogsRequest, SearchCatalogsResponse> _callSearchCatalogs; private readonly gaxgrpc::ApiCall<SearchProductsRequest, SearchProductsResponse> _callSearchProducts; private readonly gaxgrpc::ApiCall<SearchVersionsRequest, SearchVersionsResponse> _callSearchVersions; /// <summary> /// Constructs a client wrapper for the PrivateCatalog service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="PrivateCatalogSettings"/> used within this client.</param> public PrivateCatalogClientImpl(PrivateCatalog.PrivateCatalogClient grpcClient, PrivateCatalogSettings settings) { GrpcClient = grpcClient; PrivateCatalogSettings effectiveSettings = settings ?? PrivateCatalogSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callSearchCatalogs = clientHelper.BuildApiCall<SearchCatalogsRequest, SearchCatalogsResponse>(grpcClient.SearchCatalogsAsync, grpcClient.SearchCatalogs, effectiveSettings.SearchCatalogsSettings).WithGoogleRequestParam("resource", request => request.Resource); Modify_ApiCall(ref _callSearchCatalogs); Modify_SearchCatalogsApiCall(ref _callSearchCatalogs); _callSearchProducts = clientHelper.BuildApiCall<SearchProductsRequest, SearchProductsResponse>(grpcClient.SearchProductsAsync, grpcClient.SearchProducts, effectiveSettings.SearchProductsSettings).WithGoogleRequestParam("resource", request => request.Resource); Modify_ApiCall(ref _callSearchProducts); Modify_SearchProductsApiCall(ref _callSearchProducts); _callSearchVersions = clientHelper.BuildApiCall<SearchVersionsRequest, SearchVersionsResponse>(grpcClient.SearchVersionsAsync, grpcClient.SearchVersions, effectiveSettings.SearchVersionsSettings).WithGoogleRequestParam("resource", request => request.Resource); Modify_ApiCall(ref _callSearchVersions); Modify_SearchVersionsApiCall(ref _callSearchVersions); 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_SearchCatalogsApiCall(ref gaxgrpc::ApiCall<SearchCatalogsRequest, SearchCatalogsResponse> call); partial void Modify_SearchProductsApiCall(ref gaxgrpc::ApiCall<SearchProductsRequest, SearchProductsResponse> call); partial void Modify_SearchVersionsApiCall(ref gaxgrpc::ApiCall<SearchVersionsRequest, SearchVersionsResponse> call); partial void OnConstruction(PrivateCatalog.PrivateCatalogClient grpcClient, PrivateCatalogSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC PrivateCatalog client</summary> public override PrivateCatalog.PrivateCatalogClient GrpcClient { get; } partial void Modify_SearchCatalogsRequest(ref SearchCatalogsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_SearchProductsRequest(ref SearchProductsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_SearchVersionsRequest(ref SearchVersionsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Search [Catalog][google.cloud.privatecatalog.v1beta1.Catalog] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Catalog"/> resources.</returns> public override gax::PagedEnumerable<SearchCatalogsResponse, Catalog> SearchCatalogs(SearchCatalogsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchCatalogsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<SearchCatalogsRequest, SearchCatalogsResponse, Catalog>(_callSearchCatalogs, request, callSettings); } /// <summary> /// Search [Catalog][google.cloud.privatecatalog.v1beta1.Catalog] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Catalog"/> resources.</returns> public override gax::PagedAsyncEnumerable<SearchCatalogsResponse, Catalog> SearchCatalogsAsync(SearchCatalogsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchCatalogsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<SearchCatalogsRequest, SearchCatalogsResponse, Catalog>(_callSearchCatalogs, request, callSettings); } /// <summary> /// Search [Product][google.cloud.privatecatalog.v1beta1.Product] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Product"/> resources.</returns> public override gax::PagedEnumerable<SearchProductsResponse, Product> SearchProducts(SearchProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchProductsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<SearchProductsRequest, SearchProductsResponse, Product>(_callSearchProducts, request, callSettings); } /// <summary> /// Search [Product][google.cloud.privatecatalog.v1beta1.Product] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Product"/> resources.</returns> public override gax::PagedAsyncEnumerable<SearchProductsResponse, Product> SearchProductsAsync(SearchProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchProductsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<SearchProductsRequest, SearchProductsResponse, Product>(_callSearchProducts, request, callSettings); } /// <summary> /// Search [Version][google.cloud.privatecatalog.v1beta1.Version] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Version"/> resources.</returns> public override gax::PagedEnumerable<SearchVersionsResponse, Version> SearchVersions(SearchVersionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchVersionsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<SearchVersionsRequest, SearchVersionsResponse, Version>(_callSearchVersions, request, callSettings); } /// <summary> /// Search [Version][google.cloud.privatecatalog.v1beta1.Version] resources that consumers have access to, within the /// scope of the consumer cloud resource hierarchy context. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Version"/> resources.</returns> public override gax::PagedAsyncEnumerable<SearchVersionsResponse, Version> SearchVersionsAsync(SearchVersionsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchVersionsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<SearchVersionsRequest, SearchVersionsResponse, Version>(_callSearchVersions, request, callSettings); } } public partial class SearchCatalogsRequest : gaxgrpc::IPageRequest { } public partial class SearchProductsRequest : gaxgrpc::IPageRequest { } public partial class SearchVersionsRequest : gaxgrpc::IPageRequest { } public partial class SearchCatalogsResponse : gaxgrpc::IPageResponse<Catalog> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Catalog> GetEnumerator() => Catalogs.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class SearchProductsResponse : gaxgrpc::IPageResponse<Product> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Product> GetEnumerator() => Products.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class SearchVersionsResponse : gaxgrpc::IPageResponse<Version> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Version> GetEnumerator() => Versions.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public static partial class CertificatesOperationsExtensions { /// <summary> /// Creates new or update existing certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the subscription. /// </param> /// <param name='parameters'> /// Required. Create parameters. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateOrUpdate(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag) { return Task.Factory.StartNew((object s) => { return ((ICertificatesOperations)s).CreateOrUpdateAsync(resourceGroupName, serviceName, certificateId, parameters, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates new or update existing certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the subscription. /// </param> /// <param name='parameters'> /// Required. Create parameters. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateOrUpdateAsync(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag) { return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, certificateId, parameters, etag, CancellationToken.None); } /// <summary> /// Deletes specific certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId, string etag) { return Task.Factory.StartNew((object s) => { return ((ICertificatesOperations)s).DeleteAsync(resourceGroupName, serviceName, certificateId, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes specific certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId, string etag) { return operations.DeleteAsync(resourceGroupName, serviceName, certificateId, etag, CancellationToken.None); } /// <summary> /// Gets specific certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <returns> /// Get Certificate operation response details. /// </returns> public static CertificateGetResponse Get(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId) { return Task.Factory.StartNew((object s) => { return ((ICertificatesOperations)s).GetAsync(resourceGroupName, serviceName, certificateId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets specific certificate. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <returns> /// Get Certificate operation response details. /// </returns> public static Task<CertificateGetResponse> GetAsync(this ICertificatesOperations operations, string resourceGroupName, string serviceName, string certificateId) { return operations.GetAsync(resourceGroupName, serviceName, certificateId, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <returns> /// List Certificates operation response details. /// </returns> public static CertificateListResponse List(this ICertificatesOperations operations, string resourceGroupName, string serviceName, QueryParameters query) { return Task.Factory.StartNew((object s) => { return ((ICertificatesOperations)s).ListAsync(resourceGroupName, serviceName, query); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <returns> /// List Certificates operation response details. /// </returns> public static Task<CertificateListResponse> ListAsync(this ICertificatesOperations operations, string resourceGroupName, string serviceName, QueryParameters query) { return operations.ListAsync(resourceGroupName, serviceName, query, CancellationToken.None); } /// <summary> /// List all certificates of the Api Management service instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List Certificates operation response details. /// </returns> public static CertificateListResponse ListNext(this ICertificatesOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((ICertificatesOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List all certificates of the Api Management service instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.ICertificatesOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List Certificates operation response details. /// </returns> public static Task<CertificateListResponse> ListNextAsync(this ICertificatesOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
using Microsoft.SPOT; using System; using System.Threading; namespace NetduinoRGBLCDShield { public enum BacklightColor : byte { Red = 0x1, Yellow = 0x3, Green = 0x2, Teal = 0x6, Blue = 0x4, Violet = 0x5, White = 0x7 } [Flags] public enum Button : byte { Up = 0x08, Down = 0x04, Left = 0x10, Right = 0x02, Select = 0x01 } public class RGBLCDShield { private MCP23017 mcp23017; private const byte rsPin = 15; private const byte rwPin = 14; private const byte enablePin = 13; private static readonly byte[] dataPins = new byte[] { 12, 11, 10, 9 }; private static readonly byte[] buttonPins = new byte[] { 0, 1, 2, 3, 4 }; private static readonly byte[] rowStart = new byte[] { 0x00, 0x40, 0x14, 0x54 }; [Flags] public enum DisplayFunction : byte { LCD_4BITMODE = 0x00, LCD_8BITMODE = 0x10, LCD_1LINE = 0x00, LCD_2LINE = 0x08, LCD_5x8DOTS = 0x00, LCD_5x10DOTS = 0x04 } [Flags] public enum DisplayControl : byte { LCD_DISPLAYON = 0x04, LCD_DISPLAYOFF = 0x00, LCD_CURSORON = 0x02, LCD_CURSOROFF = 0x00, LCD_BLINKON = 0x01, LCD_BLINKOFF = 0x00 } [Flags] public enum DisplayMode : byte { LCD_ENTRYRIGHT = 0x00, LCD_ENTRYLEFT = 0x02, LCD_ENTRYSHIFTINCREMENT = 0x01, LCD_ENTRYSHIFTDECREMENT = 0x00 } public enum Commands : byte { LCD_CLEARDISPLAY = 0x01, LCD_RETURNHOME = 0x02, LCD_ENTRYMODESET = 0x04, LCD_DISPLAYCONTROL = 0x08, LCD_CURSORSHIFT = 0x10, LCD_FUNCTIONSET = 0x20, LCD_SETCGRAMADDR = 0x40, LCD_SETDDRAMADDR = 0x80 } private DisplayFunction displayFunction; private DisplayControl displayControl; private DisplayMode displayMode; public RGBLCDShield(MCP23017 mcp23017, byte cols = 16, byte rows = 2, byte dotsize = 0) { this.mcp23017 = mcp23017; this.displayFunction = 0x00; // initialize the MCP23017 for this board mcp23017.PinMode(8, MCP23017.Direction.Output); mcp23017.PinMode(6, MCP23017.Direction.Output); mcp23017.PinMode(7, MCP23017.Direction.Output); SetBacklight(BacklightColor.White); mcp23017.PinMode(rsPin, MCP23017.Direction.Output); mcp23017.PinMode(rwPin, MCP23017.Direction.Output); mcp23017.PinMode(enablePin, MCP23017.Direction.Output); for (int i = 0; i < dataPins.Length; i++) mcp23017.PinMode(dataPins[i], MCP23017.Direction.Output); for (int i = 0; i < buttonPins.Length; i++) { mcp23017.PinMode(buttonPins[i], MCP23017.Direction.Input); mcp23017.PullUp(buttonPins[i], 0x01); } Thread.Sleep(50); mcp23017.DigitalWrite(rsPin, 0x00); mcp23017.DigitalWrite(enablePin, 0x00); mcp23017.DigitalWrite(rwPin, 0x00); // put the LCD screen into 4 bit mode Write4Bits(0x03); Thread.Sleep(5); Write4Bits(0x03); Thread.Sleep(1); Write4Bits(0x03); Write4Bits(0x02); this.displayFunction = DisplayFunction.LCD_2LINE | DisplayFunction.LCD_4BITMODE | DisplayFunction.LCD_5x8DOTS; command((byte)((byte)Commands.LCD_FUNCTIONSET | (byte)this.displayFunction)); this.displayControl = DisplayControl.LCD_DISPLAYON | DisplayControl.LCD_CURSOROFF | DisplayControl.LCD_BLINKOFF; Display(); Clear(); this.displayMode = DisplayMode.LCD_ENTRYLEFT | DisplayMode.LCD_ENTRYSHIFTDECREMENT; command((byte)((byte)Commands.LCD_ENTRYMODESET | (byte)this.displayMode)); } public void Display() { this.displayControl |= DisplayControl.LCD_DISPLAYON; command((byte)((byte)Commands.LCD_DISPLAYCONTROL | (byte)this.displayControl)); } public void NoDisplay() { this.displayControl &= ~DisplayControl.LCD_DISPLAYON; command((byte)((int)Commands.LCD_DISPLAYCONTROL | (int)this.displayControl)); } public void Clear() { command(Commands.LCD_CLEARDISPLAY); Thread.Sleep(2); } public void Home() { command(Commands.LCD_RETURNHOME); Thread.Sleep(2); } private void command(byte command) { SendCommand(command, 0x00); } private void command(Commands command) { SendCommand((byte)command, 0x00); } private void write(byte value) { SendCommand(value, 0x01); } public void SetPosition(byte row, byte column) { byte data = 0x80; data += (byte)(rowStart[row] + column); SendCommand(data, 0x00); } public void Write(string data, bool mode = false) { byte[] buffer = new byte[data.Length]; for (int i = 0; i < data.Length; i++) buffer[i] = (byte)data[i]; this.write(buffer, mode); } private void write(byte[] value, bool mode) { mcp23017.DigitalWrite(rsPin, (byte)(mode ? 0x00 : 0x01)); for (int i = 0; i < value.Length; i++) { Write4Bits(value[i] >> 4); Write4Bits(value[i] & 0x0f); } } private void SendCommand(byte value, byte mode) { mcp23017.DigitalWrite(rsPin, mode); mcp23017.DigitalWrite(rwPin, 0x00); Write4Bits(value >> 4); Write4Bits(value & 0x0f); } private void Write4Bits(int value) { ushort gpio = mcp23017.ReadGpioAB(); for (int i = 0; i < 4; i++) { gpio &= (ushort)(~(1 << dataPins[i])); gpio |= (ushort)(((value >> i) & 0x01) << dataPins[i]); } mcp23017.WriteGpioAB(gpio); gpio |= (ushort)(1 << enablePin); mcp23017.WriteGpioAB(gpio); gpio &= (ushort)((~(1 << enablePin)) & 0xFFFF); // who promotes to int on bit negation?!? mcp23017.WriteGpioAB(gpio); } public void SetBacklight(BacklightColor color) { byte status = (byte)color; mcp23017.DigitalWrite(8, (byte)(~(status >> 2) & 0x01)); mcp23017.DigitalWrite(7, (byte)(~(status >> 1) & 0x01)); mcp23017.DigitalWrite(6, (byte)(~status & 0x01)); } public Button ReadButtons() { return (Button)(~mcp23017.i2cDevice.ReadRegister((byte)MCP23017.Command.MCP23017_GPIOA) & 0x1f); } } }
using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Permissions; using System.Threading; using System.Transactions.Diagnostics; namespace System.Transactions.Oletx { internal sealed class OletxResourceManager { internal Guid resourceManagerIdentifier; internal IResourceManagerShim resourceManagerShim; internal Hashtable enlistmentHashtable; internal static Hashtable volatileEnlistmentHashtable = new Hashtable(); internal OletxTransactionManager oletxTransactionManager; // reenlistList is a simple ArrayList of OletxEnlistment objects that are either in the // Preparing or Prepared state when we receive a TMDown notification or have had // ReenlistTransaction called for them. The ReenlistThread is responsible for traversing this // list trying to obtain the outcome for the enlistments. All access, read or write, to this // list should get a lock on the list. // Special Note: If you are going to lock both the OletxResourceManager object AND the // reenlistList, lock the reenlistList FIRST. internal ArrayList reenlistList; // reenlistPendingList is also a simple ArrayList of OletxEnlistment objects. But for these // we have received the outcome from the proxy and have called into the RM to deliver the // notification, but the RM has not yet called EnlistmentDone to let us know that the outcome // has been processed. This list must be empty, in addition to the reenlistList, in order for // the ReenlistThread to call RecoveryComplete and not be rescheduled. Access to this list // should be protected by locking the reenlistList. The lists are always accessed together, // so there is no reason to grab two locks. internal ArrayList reenlistPendingList; // This is where we keep the reenlistThread and thread timer values. If there is a reenlist thread running, // reenlistThread will be non-null. If reenlistThreadTimer is non-null, we have a timer scheduled which will // fire off a reenlist thread when it expires. Only one or the other should be non-null at a time. However, they // could both be null, which means that there is no reenlist thread running and there is no timer scheduled to // create one. Access to these members should be done only after obtaining a lock on the OletxResourceManager object. internal Timer reenlistThreadTimer; internal Thread reenlistThread; // This boolean is set to true if the resource manager application has called RecoveryComplete. // A lock on the OletxResourceManager instance will be obtained when retrieving or modifying // this value. Before calling ReenlistComplete on the DTC proxy, this value must be true. private bool recoveryCompleteCalledByApplication; internal OletxResourceManager( OletxTransactionManager transactionManager, Guid resourceManagerIdentifier ) { Debug.Assert( null != transactionManager, "Argument is null" ); // This will get set later, after the resource manager is created with the proxy. this.resourceManagerShim = null; this.oletxTransactionManager = transactionManager; this.resourceManagerIdentifier = resourceManagerIdentifier; this.enlistmentHashtable = new Hashtable(); this.reenlistList = new ArrayList(); this.reenlistPendingList = new ArrayList(); reenlistThreadTimer = null; reenlistThread = null; recoveryCompleteCalledByApplication = false; } internal IResourceManagerShim ResourceManagerShim { get { IResourceManagerShim localResourceManagerShim = null; if ( null == this.resourceManagerShim ) { lock ( this ) { if ( null == this.resourceManagerShim ) { this.oletxTransactionManager.dtcTransactionManagerLock.AcquireReaderLock( -1 ); try { Guid rmGuid = this.resourceManagerIdentifier; IntPtr handle = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { handle = HandleTable.AllocHandle( this ); this.oletxTransactionManager.DtcTransactionManager.ProxyShimFactory.CreateResourceManager( rmGuid, handle, out localResourceManagerShim ); } finally { if ( null == localResourceManagerShim && handle != IntPtr.Zero ) { HandleTable.FreeHandle( handle ); } } } catch ( COMException ex ) { if ( ( NativeMethods.XACT_E_CONNECTION_DOWN == ex.ErrorCode ) || ( NativeMethods.XACT_E_TMNOTAVAILABLE == ex.ErrorCode ) ) { // Just to make sure... localResourceManagerShim = null; if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), ex ); } } else { throw; } } catch ( TransactionException ex ) { COMException comEx = ex.InnerException as COMException; if ( null != comEx ) { // Tolerate TM down. if ( ( NativeMethods.XACT_E_CONNECTION_DOWN == comEx.ErrorCode ) || ( NativeMethods.XACT_E_TMNOTAVAILABLE == comEx.ErrorCode ) ) { // Just to make sure... localResourceManagerShim = null; if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), ex ); } } else { throw; } } else { throw; } } finally { this.oletxTransactionManager.dtcTransactionManagerLock.ReleaseReaderLock(); } Thread.MemoryBarrier(); this.resourceManagerShim = localResourceManagerShim; } } } return this.resourceManagerShim; } set { Debug.Assert( null == value, "set_ResourceManagerShim, value not null" ); this.resourceManagerShim = value; } } internal bool CallProxyReenlistComplete() { bool success = false; if ( RecoveryCompleteCalledByApplication ) { IResourceManagerShim localResourceManagerShim = null; try { localResourceManagerShim = this.ResourceManagerShim; if ( null != localResourceManagerShim ) { localResourceManagerShim.ReenlistComplete(); success = true; } // If we don't have an iResourceManagerOletx, just tell the caller that // we weren't successful and it will schedule a retry. } catch ( COMException ex ) { // If we get a TMDown error, eat it and indicate that we were unsuccessful. if ( ( NativeMethods.XACT_E_CONNECTION_DOWN == ex.ErrorCode ) || ( NativeMethods.XACT_E_TMNOTAVAILABLE == ex.ErrorCode ) ) { success = false; if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), ex ); } } // We might get an XACT_E_RECOVERYALREADYDONE if there are multiple OletxTransactionManager // objects for the same backend TM. We can safely ignore this error. else if ( NativeMethods.XACT_E_RECOVERYALREADYDONE != ex.ErrorCode ) { OletxTransactionManager.ProxyException( ex ); throw; } // Getting XACT_E_RECOVERYALREADYDONE is considered success. else { success = true; } } finally { localResourceManagerShim = null; } } else // The application has not yet called RecoveryComplete, so lie just a little. { success = true; } return success; } internal bool RecoveryCompleteCalledByApplication { get { return this.recoveryCompleteCalledByApplication; } set { this.recoveryCompleteCalledByApplication = value; } } // This is called by the internal RM when it gets a TM Down notification. This routine will // tell the enlistments about the TMDown from the internal RM. The enlistments will then // decide what to do, based on their state. This is mainly to work around COMPlus bug 36760/36758, // where Phase0 enlistments get Phase0Request( abortHint = false ) when the TM goes down. We want // to try to avoid telling the application to prepare when we know the transaction will abort. // We can't do this out of the normal TMDown notification to the RM because it is too late. The // Phase0Request gets sent before the TMDown notification. internal void TMDownFromInternalRM( OletxTransactionManager oletxTM ) { Hashtable localEnlistmentHashtable = null; IDictionaryEnumerator enlistEnum = null; OletxEnlistment enlistment = null; // If the internal RM got a TMDown, we will shortly, so null out our ResourceManagerShim now. this.ResourceManagerShim = null; // Make our own copy of the hashtable of enlistments. lock ( enlistmentHashtable.SyncRoot ) { localEnlistmentHashtable = (Hashtable) this.enlistmentHashtable.Clone(); } // Tell all of our enlistments that the TM went down. The proxy only // tells enlistments that are in the Prepared state, but we want our Phase0 // enlistments to know so they can avoid sending Prepare when they get a // Phase0Request - COMPlus bug 36760/36758. enlistEnum = localEnlistmentHashtable.GetEnumerator(); while ( enlistEnum.MoveNext() ) { enlistment = enlistEnum.Value as OletxEnlistment; if ( null != enlistment ) { enlistment.TMDownFromInternalRM( oletxTM ); } } } #region IResourceManagerSink public void TMDown() { // The ResourceManagerShim was already set to null by TMDownFromInternalRM, so we don't need to do it again here. // Just start the ReenlistThread. StartReenlistThread(); return; } #endregion internal OletxEnlistment EnlistDurable( OletxTransaction oletxTransaction, bool canDoSinglePhase, IEnlistmentNotificationInternal enlistmentNotification, EnlistmentOptions enlistmentOptions ) { IResourceManagerShim localResourceManagerShim = null; Debug.Assert( null != oletxTransaction, "Argument is null" ); Debug.Assert( null != enlistmentNotification, "Argument is null" ); IEnlistmentShim enlistmentShim = null; IPhase0EnlistmentShim phase0Shim = null; Guid txUow = Guid.Empty; IntPtr handlePhase0 = IntPtr.Zero; bool phase0EnlistSucceeded = false; bool undecidedEnlistmentsIncremented = false; // Create our enlistment object. OletxEnlistment enlistment = new OletxEnlistment( canDoSinglePhase, enlistmentNotification, oletxTransaction.RealTransaction.TxGuid, enlistmentOptions, this, oletxTransaction ); bool enlistmentSucceeded = false; RuntimeHelpers.PrepareConstrainedRegions(); try { if ( (enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0 ) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { oletxTransaction.RealTransaction.IncrementUndecidedEnlistments(); undecidedEnlistmentsIncremented = true; } } // This entire sequense needs to be executed before we can go on. lock ( enlistment ) { RuntimeHelpers.PrepareConstrainedRegions(); try { // Do the enlistment on the proxy. localResourceManagerShim = this.ResourceManagerShim; if ( null == localResourceManagerShim ) { // The TM must be down. Throw the appropriate exception. throw TransactionManagerCommunicationException.Create( SR.GetString( SR.TraceSourceOletx), null ); } if ( (enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0 ) { // We need to create an EnlistmentNotifyShim if native threads are not allowed to enter managed code. handlePhase0 = HandleTable.AllocHandle( enlistment ); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { oletxTransaction.RealTransaction.TransactionShim.Phase0Enlist( handlePhase0, out phase0Shim ); phase0EnlistSucceeded = true; } enlistment.Phase0EnlistmentShim = phase0Shim; } enlistment.phase1Handle = HandleTable.AllocHandle( enlistment ); localResourceManagerShim.Enlist( oletxTransaction.RealTransaction.TransactionShim, enlistment.phase1Handle, out enlistmentShim ); enlistment.EnlistmentShim = enlistmentShim; } catch (COMException comException) { // There is no string mapping for XACT_E_TOOMANY_ENLISTMENTS, so we need to do it here. if ( NativeMethods.XACT_E_TOOMANY_ENLISTMENTS == comException.ErrorCode ) { throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString( SR.OletxTooManyEnlistments ), comException, enlistment == null ? Guid.Empty : enlistment.DistributedTxId ); } OletxTransactionManager.ProxyException( comException ); throw; } finally { if ( enlistment.EnlistmentShim == null ) { // If the enlistment shim was never assigned then something blew up. // Perform some cleanup. if ( handlePhase0 != IntPtr.Zero && !phase0EnlistSucceeded ) { // Only clean up the phase0 handle if the phase 0 enlistment did not succeed. // This is because the notification processing code expects it to exist. HandleTable.FreeHandle( handlePhase0 ); } if ( enlistment.phase1Handle != IntPtr.Zero ) { HandleTable.FreeHandle( enlistment.phase1Handle ); } // Note this code used to call unenlist however this allows race conditions where // it is unclear if the handlePhase0 should be freed or not. The notification // thread should get a phase0Request and it will free the Handle at that point. } } } enlistmentSucceeded = true; } finally { if ( !enlistmentSucceeded && ((enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0) && undecidedEnlistmentsIncremented ) { oletxTransaction.RealTransaction.DecrementUndecidedEnlistments(); } } return enlistment; } internal OletxEnlistment Reenlist( int prepareInfoLength, byte[] prepareInfo, IEnlistmentNotificationInternal enlistmentNotification ) { OletxTransactionOutcome outcome = OletxTransactionOutcome.NotKnownYet; OletxTransactionStatus xactStatus = OletxTransactionStatus.OLETX_TRANSACTION_STATUS_NONE; // Put the recovery information into a stream. MemoryStream stream = new MemoryStream( prepareInfo ); // First extract the OletxRecoveryInformation from the stream. IFormatter formatter = new BinaryFormatter(); OletxRecoveryInformation oletxRecoveryInformation; try { oletxRecoveryInformation = formatter.Deserialize( stream ) as OletxRecoveryInformation; } catch (SerializationException se) { throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "prepareInfo", se ); } if ( null == oletxRecoveryInformation ) { throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "prepareInfo" ); } // Verify that the resource manager guid in the recovery info matches that of the calling resource manager. byte[] rmGuidArray = new byte[16]; for ( int i = 0; i < 16; i++ ) { rmGuidArray[i] = oletxRecoveryInformation.proxyRecoveryInformation[i + 16]; } Guid rmGuid = new Guid( rmGuidArray ); if ( rmGuid != this.resourceManagerIdentifier ) { throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString( SR.ResourceManagerIdDoesNotMatchRecoveryInformation ), null ); } // Ask the proxy resource manager to reenlist. IResourceManagerShim localResourceManagerShim = null; try { localResourceManagerShim = this.ResourceManagerShim; if ( null == localResourceManagerShim ) { // The TM must be down. Throw the exception that will get caught below and will cause // the enlistment to start the ReenlistThread. The TMDown thread will be trying to reestablish // connection with the TM and will start the reenlist thread when it does. throw new COMException( SR.GetString( SR.DtcTransactionManagerUnavailable ), NativeMethods.XACT_E_CONNECTION_DOWN ); } // Only wait for 5 milliseconds. If the TM doesn't have the outcome now, we will // put the enlistment on the reenlistList for later processing. localResourceManagerShim.Reenlist( Convert.ToUInt32( oletxRecoveryInformation.proxyRecoveryInformation.Length, CultureInfo.InvariantCulture ), oletxRecoveryInformation.proxyRecoveryInformation, out outcome ); if ( OletxTransactionOutcome.Committed == outcome ) { xactStatus = OletxTransactionStatus.OLETX_TRANSACTION_STATUS_COMMITTED; } else if ( OletxTransactionOutcome.Aborted == outcome ) { xactStatus = OletxTransactionStatus.OLETX_TRANSACTION_STATUS_ABORTED; } else // we must not know the outcome yet. { xactStatus = OletxTransactionStatus.OLETX_TRANSACTION_STATUS_PREPARED; StartReenlistThread(); } } catch ( COMException ex ) { if ( NativeMethods.XACT_E_CONNECTION_DOWN == ex.ErrorCode ) { xactStatus = OletxTransactionStatus.OLETX_TRANSACTION_STATUS_PREPARED; this.ResourceManagerShim = null; StartReenlistThread(); if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), ex ); } } else { throw; } } finally { localResourceManagerShim = null; } // Now create our enlistment to tell the client the outcome. OletxEnlistment enlistment = new OletxEnlistment( enlistmentNotification, xactStatus, oletxRecoveryInformation.proxyRecoveryInformation, this ); return enlistment; } internal void RecoveryComplete() { Timer localTimer = null; // Remember that the application has called RecoveryComplete. RecoveryCompleteCalledByApplication = true; try { // Remove the OletxEnlistment objects from the reenlist list because the RM says it doesn't // have any unresolved transactions, so we don't need to keep asking and the reenlist thread can exit. // Leave the reenlistPendingList alone. If we have notifications outstanding, we still can't remove those. lock ( this.reenlistList ) { // If the ReenlistThread is not running and there are no reenlistPendingList entries, we need to call ReenlistComplete ourself. lock ( this ) { if ( ( 0 == this.reenlistList.Count ) && ( 0 == this.reenlistPendingList.Count ) ) { if ( null != this.reenlistThreadTimer ) { // If we have a pending reenlistThreadTimer, cancel it. We do the cancel // in the finally block to satisfy FXCop. localTimer = this.reenlistThreadTimer; this.reenlistThreadTimer = null; } // Try to tell the proxy RenlistmentComplete. bool success = CallProxyReenlistComplete(); if ( !success ) { // We are now responsible for calling RecoveryComplete. Fire up the ReenlistThread // to do it for us. StartReenlistThread(); } } else { StartReenlistThread(); } } } } finally { if ( null != localTimer ) { localTimer.Dispose(); } } return; } internal void StartReenlistThread() { // We are not going to check the reenlistList.Count. Just always start the thread. We do this because // if we get a COMException from calling ReenlistComplete, we start the reenlistThreadTimer to retry it for us // in the background. lock ( this ) { // We don't need a MemoryBarrier here because all access to the reenlistThreadTimer member is done while // holding a lock on the OletxResourceManager object. if ( ( null == this.reenlistThreadTimer ) && ( null == this.reenlistThread ) ) { this.reenlistThreadTimer = new Timer( this.ReenlistThread, this, 10, Timeout.Infinite ); } } } // This routine searches the reenlistPendingList for the specified enlistment and if it finds // it, removes it from the list. An enlistment calls this routine when it is "finishing" because // the RM has called EnlistmentDone or it was InDoubt. But it only calls it if the enlistment does NOT // have a WrappedTransactionEnlistmentAsync value, indicating that it is a recovery enlistment. internal void RemoveFromReenlistPending( OletxEnlistment enlistment ) { // We lock the reenlistList because we have decided to lock that list when accessing either // the reenlistList or the reenlistPendingList. lock ( reenlistList ) { // This will do a linear search of the list, but that is what we need to do because // the enlistments may change indicies while notifications are outstanding. Also, // this does not throw if the enlistment isn't on the list. reenlistPendingList.Remove( enlistment ); lock ( this ) { // If we have a ReenlistThread timer and both the reenlistList and the reenlistPendingList // are empty, kick the ReenlistThread now. if ( ( null != this.reenlistThreadTimer ) && ( 0 == this.reenlistList.Count ) && ( 0 == this.reenlistPendingList.Count ) ) { if ( !this.reenlistThreadTimer.Change( 0, Timeout.Infinite )) { throw TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceLtm ), SR.GetString(SR.UnexpectedTimerFailure), null ); } } } } } internal void ReenlistThread( object state ) { int localLoopCount = 0; bool done = false; OletxEnlistment localEnlistment = null; IResourceManagerShim localResourceManagerShim = null; bool success = false; Timer localTimer = null; bool disposeLocalTimer = false; OletxResourceManager resourceManager = (OletxResourceManager) state; try { if ( DiagnosticTrace.Information ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), "OletxResourceManager.ReenlistThread" ); } lock ( resourceManager ) { localResourceManagerShim = resourceManager.ResourceManagerShim; localTimer = resourceManager.reenlistThreadTimer; resourceManager.reenlistThreadTimer = null; resourceManager.reenlistThread = Thread.CurrentThread; } // We only want to do work if we have a resourceManagerShim. if ( null != localResourceManagerShim ) { lock ( resourceManager.reenlistList ) { // Get the current count on the list. localLoopCount = resourceManager.reenlistList.Count; } done = false; while ( !done && ( localLoopCount > 0 ) && ( null != localResourceManagerShim ) ) { lock ( resourceManager.reenlistList ) { localEnlistment = null; localLoopCount--; if ( 0 == resourceManager.reenlistList.Count ) { done = true; } else { localEnlistment = resourceManager.reenlistList[0] as OletxEnlistment; if ( null == localEnlistment ) { // if ( DiagnosticTrace.Critical ) { InternalErrorTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), "" ); } throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx), SR.GetString( SR.InternalError ), null ); } resourceManager.reenlistList.RemoveAt( 0 ); Object syncRoot = localEnlistment; lock ( syncRoot ) { if ( OletxEnlistment.OletxEnlistmentState.Done == localEnlistment.State ) { // We may be racing with a RecoveryComplete here. Just forget about this // enlistment. localEnlistment = null; } else if ( OletxEnlistment.OletxEnlistmentState.Prepared != localEnlistment.State ) { // The app hasn't yet responded to Prepare, so we don't know // if it is indoubt or not yet. So just re-add it to the end // of the list. resourceManager.reenlistList.Add( localEnlistment ); localEnlistment = null; } } } } if ( null != localEnlistment ) { OletxTransactionOutcome localOutcome = OletxTransactionOutcome.NotKnownYet; try { Debug.Assert( null != localResourceManagerShim, "ReenlistThread - localResourceManagerShim is null" ); // Make sure we have a prepare info. if ( null == localEnlistment.ProxyPrepareInfoByteArray ) { Debug.Assert( false, string.Format( null, "this.prepareInfoByteArray == null in RecoveryInformation()" )); if ( DiagnosticTrace.Critical ) { InternalErrorTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), "" ); } throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx), SR.GetString( SR.InternalError ), null ); } localResourceManagerShim.Reenlist( (UInt32) localEnlistment.ProxyPrepareInfoByteArray.Length, localEnlistment.ProxyPrepareInfoByteArray, out localOutcome ); if ( OletxTransactionOutcome.NotKnownYet == localOutcome ) { Object syncRoot = localEnlistment; lock ( syncRoot ) { if ( OletxEnlistment.OletxEnlistmentState.Done == localEnlistment.State ) { // We may be racing with a RecoveryComplete here. Just forget about this // enlistment. localEnlistment = null; } else { // Put the enlistment back on the end of the list for retry later. lock ( resourceManager.reenlistList ) { resourceManager.reenlistList.Add( localEnlistment ); localEnlistment = null; } } } } } catch ( COMException ex ) // or whatever exception gets thrown if we get a bad hr. { if ( NativeMethods.XACT_E_CONNECTION_DOWN == ex.ErrorCode ) { if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), ex ); } if ( NativeMethods.XACT_E_CONNECTION_DOWN == ex.ErrorCode ) { // Release the resource manager so we can create a new one. resourceManager.ResourceManagerShim = null; // Now create a new resource manager with the proxy. localResourceManagerShim = resourceManager.ResourceManagerShim; } } else { // Unexpected exception, rethrow it. throw; } } // If we get here and we still have localEnlistment, then we got the outcome. if ( null != localEnlistment ) { Object syncRoot = localEnlistment; lock ( syncRoot ) { if ( OletxEnlistment.OletxEnlistmentState.Done == localEnlistment.State ) { // We may be racing with a RecoveryComplete here. Just forget about this // enlistment. localEnlistment = null; } else { // We are going to send the notification to the RM. We need to put the // enlistment on the reenlistPendingList. We lock the reenlistList because // we have decided that is the lock that protects both lists. The entry will // be taken off the reenlistPendingList when the enlistment has // EnlistmentDone called on it. The enlistment will call // RemoveFromReenlistPending. lock ( resourceManager.reenlistList ) { resourceManager.reenlistPendingList.Add( localEnlistment ); } if ( OletxTransactionOutcome.Committed == localOutcome ) { localEnlistment.State = OletxEnlistment.OletxEnlistmentState.Committing; if ( DiagnosticTrace.Verbose ) { EnlistmentNotificationCallTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), localEnlistment.EnlistmentTraceId, NotificationCall.Commit ); } localEnlistment.EnlistmentNotification.Commit( localEnlistment ); } else if ( OletxTransactionOutcome.Aborted == localOutcome ) { localEnlistment.State = OletxEnlistment.OletxEnlistmentState.Aborting; if ( DiagnosticTrace.Verbose ) { EnlistmentNotificationCallTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), localEnlistment.EnlistmentTraceId, NotificationCall.Rollback ); } localEnlistment.EnlistmentNotification.Rollback( localEnlistment ); } else { if ( DiagnosticTrace.Critical ) { InternalErrorTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), "" ); } throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString( SR.InternalError ), null ); } } } } // end of if null != localEnlistment } // end of if null != localEnlistment } } localResourceManagerShim = null; // Check to see if there is more work to do. lock ( resourceManager.reenlistList ) { lock ( resourceManager ) { // Get the current count on the list. localLoopCount = resourceManager.reenlistList.Count; if ( ( 0 >= localLoopCount ) && ( 0 >= resourceManager.reenlistPendingList.Count ) ) { // No more entries on the list. Try calling ReenlistComplete on the proxy, if // appropriate. // If the application has called RecoveryComplete, // we are responsible for calling ReenlistComplete on the // proxy. success = resourceManager.CallProxyReenlistComplete(); if ( success ) { // Okay, the reenlist thread is done and we don't need to schedule another one. disposeLocalTimer = true; } else { // We couldn't talk to the proxy to do ReenlistComplete, so schedule // the thread again for 10 seconds from now. resourceManager.reenlistThreadTimer = localTimer; if ( !localTimer.Change( 10000, Timeout.Infinite )) { throw TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceLtm ), SR.GetString(SR.UnexpectedTimerFailure), null ); } } } else { // There are still entries on the list, so they must not be // resovled, yet. Schedule the thread again in 10 seconds. resourceManager.reenlistThreadTimer = localTimer; if ( !localTimer.Change( 10000, Timeout.Infinite )) { throw TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceLtm ), SR.GetString(SR.UnexpectedTimerFailure), null ); } } resourceManager.reenlistThread = null; } if ( DiagnosticTrace.Information ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), "OletxResourceManager.ReenlistThread" ); } return; } } // end of outer-most try finally { localResourceManagerShim = null; if ( ( disposeLocalTimer ) && ( null != localTimer ) ) { localTimer.Dispose(); } } } // end of ReenlistThread method; } // This is the base class for all enlistment objects. The enlistment objects provide the callback // that is made from the application and pass it through to the proxy. abstract class OletxBaseEnlistment { protected Guid enlistmentGuid; protected OletxResourceManager oletxResourceManager; protected OletxTransaction oletxTransaction; internal OletxTransaction OletxTransaction { get { return this.oletxTransaction; } } internal Guid DistributedTxId { get { Guid returnValue = Guid.Empty; if (this.OletxTransaction != null) { returnValue = this.OletxTransaction.DistributedTxId; } return returnValue; } } protected string transactionGuidString; protected int enlistmentId; // this needs to be internal so it can be set from the recovery information during Reenlist. internal EnlistmentTraceIdentifier traceIdentifier; // Owning public Enlistment object protected InternalEnlistment internalEnlistment; public OletxBaseEnlistment( OletxResourceManager oletxResourceManager, OletxTransaction oletxTransaction ) { Guid resourceManagerId = Guid.Empty; enlistmentGuid = Guid.NewGuid(); this.oletxResourceManager = oletxResourceManager; this.oletxTransaction = oletxTransaction; if ( null != oletxTransaction ) { this.enlistmentId = oletxTransaction.realOletxTransaction.enlistmentCount++; this.transactionGuidString = oletxTransaction.realOletxTransaction.TxGuid.ToString(); } else { this.transactionGuidString = Guid.Empty.ToString(); } this.traceIdentifier = EnlistmentTraceIdentifier.Empty; } protected EnlistmentTraceIdentifier InternalTraceIdentifier { get { if ( EnlistmentTraceIdentifier.Empty == this.traceIdentifier ) { lock ( this ) { if ( EnlistmentTraceIdentifier.Empty == this.traceIdentifier ) { Guid rmId = Guid.Empty; if ( null != oletxResourceManager ) { rmId = this.oletxResourceManager.resourceManagerIdentifier; } EnlistmentTraceIdentifier temp; if ( null != this.oletxTransaction ) { temp = new EnlistmentTraceIdentifier( rmId, oletxTransaction.TransactionTraceId, this.enlistmentId ); } else { TransactionTraceIdentifier txTraceId = new TransactionTraceIdentifier( this.transactionGuidString, 0 ); temp = new EnlistmentTraceIdentifier( rmId, txTraceId, this.enlistmentId ); } Thread.MemoryBarrier(); this.traceIdentifier = temp; } } } return this.traceIdentifier; } } protected void AddToEnlistmentTable() { lock ( oletxResourceManager.enlistmentHashtable.SyncRoot ) { oletxResourceManager.enlistmentHashtable.Add( enlistmentGuid, this ); } } protected void RemoveFromEnlistmentTable() { lock ( oletxResourceManager.enlistmentHashtable.SyncRoot ) { oletxResourceManager.enlistmentHashtable.Remove( enlistmentGuid ); } } } } // end of namespace
// ******************************************************************************************************** // Product Name: DotSpatial.Plugins.ShapeEditor.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/11/2009 11:03:39 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Controls; using DotSpatial.Data; using DotSpatial.NTSExtension; using DotSpatial.Symbology; using GeoAPI.Geometries; using NetTopologySuite.Geometries; using Point = System.Drawing.Point; namespace DotSpatial.Plugins.ShapeEditor { /// <summary> /// This function allows interacting with the map through mouse clicks to create a new shape. /// </summary> public class AddShapeFunction : SnappableMapFunction, IDisposable { #region private variables private ContextMenu _context; private CoordinateDialog _coordinateDialog; private List<Coordinate> _coordinates; private bool _disposed; private IFeatureSet _featureSet; private MenuItem _finishPart; private Point _mousePosition; private List<List<Coordinate>> _parts; private bool _standBy; private IMapLineLayer _tempLayer; private IFeatureLayer _layer; #endregion #region Constructors /// <summary> /// Initializes a new instance of the AddShapeFunction class. This specifies the Map that this function should be applied to. /// </summary> /// <param name="map">The map control that implements the IMap interface that this function uses.</param> public AddShapeFunction(IMap map) : base(map) { Configure(); } private void Configure() { YieldStyle = (YieldStyles.LeftButton | YieldStyles.RightButton); _context = new ContextMenu(); _context.MenuItems.Add("Delete", DeleteShape); _finishPart = new MenuItem("Finish Part", FinishPart); _context.MenuItems.Add(_finishPart); _context.MenuItems.Add("Finish Shape", FinishShape); _parts = new List<List<Coordinate>>(); } #endregion #region Methods /// <summary> /// Forces this function to begin collecting points for building a new shape. /// </summary> protected override void OnActivate() { if (_coordinateDialog == null) _coordinateDialog = new CoordinateDialog(); _coordinateDialog.ShowZValues = _featureSet.CoordinateType == CoordinateType.Z; _coordinateDialog.ShowMValues = _featureSet.CoordinateType == CoordinateType.M || _featureSet.CoordinateType == CoordinateType.Z; if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint) { if (_context.MenuItems.Contains(_finishPart)) _context.MenuItems.Remove(_finishPart); } else if (!_context.MenuItems.Contains(_finishPart)) _context.MenuItems.Add(1, _finishPart); _coordinateDialog.Show(); _coordinateDialog.FormClosing += CoordinateDialogFormClosing; if (!_standBy) _coordinates = new List<Coordinate>(); if (_tempLayer != null) { Map.MapFrame.DrawingLayers.Remove(_tempLayer); Map.MapFrame.Invalidate(); Map.Invalidate(); _tempLayer = null; } _standBy = false; base.OnActivate(); } /// <summary> /// Allows for new behavior during deactivation. /// </summary> protected override void OnDeactivate() { if (_standBy) { return; } // Don't completely deactivate, but rather go into standby mode // where we draw only the content that we have actually locked in. _standBy = true; if (_coordinateDialog != null) { _coordinateDialog.Hide(); } if (_coordinates != null && _coordinates.Count > 1) { LineString ls = new LineString(_coordinates.ToArray()); FeatureSet fs = new FeatureSet(FeatureType.Line); fs.Features.Add(new Feature(ls)); MapLineLayer gll = new MapLineLayer(fs) { Symbolizer = { ScaleMode = ScaleMode.Symbolic, Smoothing = true }, MapFrame = Map.MapFrame }; _tempLayer = gll; Map.MapFrame.DrawingLayers.Add(gll); Map.MapFrame.Invalidate(); Map.Invalidate(); } base.Deactivate(); } /// <summary> /// Handles drawing of editing features. /// </summary> /// <param name="e">The drawing args for the draw method.</param> protected override void OnDraw(MapDrawArgs e) { if (_standBy) { return; } // Begin snapping changes DoSnapDrawing(e.Graphics, _mousePosition); // End snapping changes if (_featureSet.FeatureType == FeatureType.Point) { return; } // Draw any completed parts first so that they are behind my active drawing content. if (_parts != null) { GraphicsPath gp = new GraphicsPath(); List<Point> partPoints = new List<Point>(); foreach (List<Coordinate> part in _parts) { partPoints.AddRange(part.Select(c => Map.ProjToPixel(c))); if (_featureSet.FeatureType == FeatureType.Line) { gp.AddLines(partPoints.ToArray()); } if (_featureSet.FeatureType == FeatureType.Polygon) { gp.AddPolygon(partPoints.ToArray()); } partPoints.Clear(); } e.Graphics.DrawPath(Pens.Blue, gp); if (_featureSet.FeatureType == FeatureType.Polygon) { Brush fill = new SolidBrush(Color.FromArgb(70, Color.LightCyan)); e.Graphics.FillPath(fill, gp); fill.Dispose(); } } Pen bluePen = new Pen(Color.Blue, 2F); Pen redPen = new Pen(Color.Red, 3F); Brush redBrush = new SolidBrush(Color.Red); List<Point> points = new List<Point>(); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; if (_coordinates != null) { points.AddRange(_coordinates.Select(coord => Map.ProjToPixel(coord))); foreach (Point pt in points) { e.Graphics.FillRectangle(redBrush, new Rectangle(pt.X - 2, pt.Y - 2, 4, 4)); } if (points.Count > 1) { if (_featureSet.FeatureType != FeatureType.MultiPoint) { e.Graphics.DrawLines(bluePen, points.ToArray()); } } if (points.Count > 0 && _standBy == false) { if (_featureSet.FeatureType != FeatureType.MultiPoint) { e.Graphics.DrawLine(redPen, points[points.Count - 1], _mousePosition); } } } bluePen.Dispose(); redPen.Dispose(); redBrush.Dispose(); base.OnDraw(e); } /// <summary> /// This method occurs as the mouse moves. /// </summary> /// <param name="e">The GeoMouseArcs class describes the mouse condition along with geographic coordinates.</param> protected override void OnMouseMove(GeoMouseArgs e) { if (_standBy) { return; } // Begin snapping changes Coordinate snappedCoord = e.GeographicLocation; bool prevWasSnapped = IsSnapped; IsSnapped = ComputeSnappedLocation(e, ref snappedCoord); _coordinateDialog.X = snappedCoord.X; _coordinateDialog.Y = snappedCoord.Y; // End snapping changes if (_coordinates != null && _coordinates.Count > 0) { List<Point> points = _coordinates.Select(coord => Map.ProjToPixel(coord)).ToList(); Rectangle oldRect = SymbologyGlobal.GetRectangle(_mousePosition, points[points.Count - 1]); Rectangle newRect = SymbologyGlobal.GetRectangle(e.Location, points[points.Count - 1]); Rectangle invalid = Rectangle.Union(newRect, oldRect); invalid.Inflate(20, 20); Map.Invalidate(invalid); } // Begin snapping changes _mousePosition = IsSnapped ? Map.ProjToPixel(snappedCoord) : e.Location; DoMouseMoveForSnapDrawing(prevWasSnapped, _mousePosition); // End snapping changes base.OnMouseMove(e); } /// <summary> /// Handles the Mouse-Up situation. /// </summary> /// <param name="e">The GeoMouseArcs class describes the mouse condition along with geographic coordinates.</param> protected override void OnMouseUp(GeoMouseArgs e) { if (_standBy) { return; } if (_featureSet == null || _featureSet.IsDisposed) { return; } if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right) { // Add the current point to the featureset if (_featureSet.FeatureType == FeatureType.Point) { // Begin snapping changes Coordinate snappedCoord = _coordinateDialog.Coordinate; ComputeSnappedLocation(e, ref snappedCoord); // End snapping changes Feature f = new Feature(snappedCoord); _featureSet.Features.Add(f); _featureSet.ShapeIndices = null; // Reset shape indices _featureSet.UpdateExtent(); _layer.AssignFastDrawnStates(); _featureSet.InvalidateVertices(); return; } if (e.Button == MouseButtons.Right) { _context.Show((Control)Map, e.Location); } else { if (_coordinates == null) { _coordinates = new List<Coordinate>(); } // Begin snapping changes Coordinate snappedCoord = e.GeographicLocation; ComputeSnappedLocation(e, ref snappedCoord); // End snapping changes _coordinates.Add(snappedCoord); // Snapping changes if (_coordinates.Count > 1) { Point p1 = Map.ProjToPixel(_coordinates[_coordinates.Count - 1]); Point p2 = Map.ProjToPixel(_coordinates[_coordinates.Count - 2]); Rectangle invalid = SymbologyGlobal.GetRectangle(p1, p2); invalid.Inflate(20, 20); Map.Invalidate(invalid); } } } base.OnMouseUp(e); } /// <summary> /// Delete the shape currently being edited. /// </summary> /// <param name="sender">The sender of the DeleteShape event.</param> /// <param name="e">An empty EventArgument.</param> public void DeleteShape(object sender, EventArgs e) { _coordinates = new List<Coordinate>(); _parts = new List<List<Coordinate>>(); Map.Invalidate(); } /// <summary> /// Finish the shape. /// </summary> /// <param name="sender">The object sender.</param> /// <param name="e">An empty EventArgs class.</param> public void FinishShape(object sender, EventArgs e) { if (_featureSet != null && !_featureSet.IsDisposed) { Feature f = null; if (_featureSet.FeatureType == FeatureType.MultiPoint) { f = new Feature(new MultiPoint(_coordinates.CastToPointArray())); } if (_featureSet.FeatureType == FeatureType.Line || _featureSet.FeatureType == FeatureType.Polygon) { FinishPart(sender, e); Shape shp = new Shape(_featureSet.FeatureType); foreach (List<Coordinate> part in _parts) { if (part.Count >= 2) { shp.AddPart(part, _featureSet.CoordinateType); } } f = new Feature(shp); } if (f != null) { _featureSet.Features.Add(f); } _featureSet.ShapeIndices = null; // Reset shape indices _featureSet.UpdateExtent(); _layer.AssignFastDrawnStates(); _featureSet.InvalidateVertices(); } _coordinates = new List<Coordinate>(); _parts = new List<List<Coordinate>>(); } /// <summary> /// Finish the part of the shape being edited. /// </summary> /// <param name="sender">The object sender.</param> /// <param name="e">An empty EventArgs class.</param> public void FinishPart(object sender, EventArgs e) { if (_featureSet.FeatureType == FeatureType.Polygon && !_coordinates[0].Equals2D(_coordinates[_coordinates.Count - 1])) _coordinates.Add(_coordinates[0]); //close polygons because they must be closed _parts.Add(_coordinates); _coordinates = new List<Coordinate>(); Map.Invalidate(); } /// <summary> /// Occurs when this function is removed. /// </summary> protected override void OnUnload() { if (Enabled) { _coordinates = null; _coordinateDialog.Hide(); } if (_tempLayer != null) { Map.MapFrame.DrawingLayers.Remove(_tempLayer); Map.MapFrame.Invalidate(); _tempLayer = null; } Map.Invalidate(); } #endregion /// <summary> /// Gets a value indicating whether the "dispose" method has been called. /// </summary> public bool IsDisposed { get { return _disposed; } } public IFeatureLayer Layer { get { return _layer; } set { if (_layer == value) return; _layer = value; _featureSet = _layer != null ? _layer.DataSet : null; } } #region IDisposable Members /// <summary> /// Actually, this creates disposable items but doesn't own them. /// When the ribbon disposes it will remove the items. /// </summary> public void Dispose() { Dispose(true); // This exists to prevent FX Cop from complaining. GC.SuppressFinalize(this); } #endregion private void CoordinateDialogFormClosing(object sender, FormClosingEventArgs e) { // This signals that we are done with editing, and should therefore close up shop Enabled = false; } /// <summary> /// Finalizes an instance of the AddShapeFunction class. /// </summary> ~AddShapeFunction() { Dispose(false); } /// <summary> /// Disposes this handler, removing any buttons that it is responsible for adding. /// </summary> /// <param name="disposeManagedResources">Disposes of the resources.</param> protected virtual void Dispose(bool disposeManagedResources) { if (!_disposed) { // One option would be to leave the non-working tools, // but if this gets disposed we should clean up after // ourselves and remove any added controls. if (disposeManagedResources) { if (!_coordinateDialog.IsDisposed) { _coordinateDialog.Dispose(); } if (_context != null) { _context.Dispose(); } if (_finishPart != null) { _finishPart.Dispose(); } _featureSet = null; _coordinates = null; _coordinateDialog = null; _tempLayer = null; _context = null; _finishPart = null; _parts = null; _layer = null; } _disposed = true; } } } }